-
Notifications
You must be signed in to change notification settings - Fork 1
/
service.go
74 lines (62 loc) · 2.26 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package blockchain
import (
"context"
"github.com/ovcharovvladimir/Prysm/beacon-chain/database"
"github.com/ovcharovvladimir/Prysm/beacon-chain/powchain"
"github.com/ovcharovvladimir/Prysm/beacon-chain/types"
"github.com/sirupsen/logrus"
)
var log = logrus.WithField("prefix", "blockchain")
// ChainService represents a service that handles the internal
// logic of managing the full PoS beacon chain.
type ChainService struct {
ctx context.Context
cancel context.CancelFunc
beaconDB *database.BeaconDB
chain *BeaconChain
web3Service *powchain.Web3Service
latestBeaconBlock chan *types.Block
}
// NewChainService instantiates a new service instance that will
// be registered into a running beacon node.
func NewChainService(ctx context.Context, beaconDB *database.BeaconDB, web3Service *powchain.Web3Service) (*ChainService, error) {
ctx, cancel := context.WithCancel(ctx)
return &ChainService{ctx, cancel, beaconDB, nil, web3Service, nil}, nil
}
// Start a blockchain service's main event loop.
func (c *ChainService) Start() {
log.Infof("Starting blockchain service")
beaconChain, err := NewBeaconChain(c.beaconDB.DB())
if err != nil {
log.Errorf("Unable to setup blockchain: %v", err)
}
c.chain = beaconChain
go c.updateActiveState()
}
// Stop the blockchain service's main event loop and associated goroutines.
func (c *ChainService) Stop() error {
defer c.cancel()
log.Info("Stopping blockchain service")
return nil
}
// updateActiveState receives a beacon block, computes a new active state and writes it to db.
func (c *ChainService) updateActiveState() {
for {
select {
case block := <-c.latestBeaconBlock:
log.WithFields(logrus.Fields{"activeStateHash": block.Data().ActiveStateHash}).Debug("Received beacon block")
// TODO: Using latest block hash for seed, this will eventually be replaced by randao
activeState, err := c.chain.computeNewActiveState(c.web3Service.LatestBlockHash())
if err != nil {
log.Errorf("Compute active state failed: %v", err)
}
err = c.chain.MutateActiveState(activeState)
if err != nil {
log.Errorf("Write active state to disk failed: %v", err)
}
case <-c.ctx.Done():
log.Debug("Chain service context closed, exiting goroutine")
return
}
}
}