2018-08-09 18:25:48 +00:00
|
|
|
// Package blockchain defines the life-cycle and status of the beacon chain.
|
2018-07-19 16:31:50 +00:00
|
|
|
package blockchain
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2018-07-31 04:41:27 +00:00
|
|
|
"fmt"
|
2018-07-19 16:31:50 +00:00
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
"github.com/ethereum/go-ethereum/ethdb"
|
|
|
|
"github.com/ethereum/go-ethereum/event"
|
|
|
|
"github.com/prysmaticlabs/prysm/beacon-chain/casper"
|
2018-07-22 16:58:14 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/beacon-chain/powchain"
|
|
|
|
"github.com/prysmaticlabs/prysm/beacon-chain/types"
|
2018-08-29 00:55:56 +00:00
|
|
|
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
|
2018-07-21 17:51:18 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
2018-07-19 16:31:50 +00:00
|
|
|
)
|
|
|
|
|
2018-07-21 17:51:18 +00:00
|
|
|
var log = logrus.WithField("prefix", "blockchain")
|
2018-09-02 16:44:03 +00:00
|
|
|
var nilBlock = &types.Block{}
|
|
|
|
var nilActiveState = &types.ActiveState{}
|
|
|
|
var nilCrystallizedState = &types.CrystallizedState{}
|
2018-07-21 17:51:18 +00:00
|
|
|
|
2018-07-19 16:31:50 +00:00
|
|
|
// ChainService represents a service that handles the internal
|
|
|
|
// logic of managing the full PoS beacon chain.
|
|
|
|
type ChainService struct {
|
2018-08-24 04:09:59 +00:00
|
|
|
ctx context.Context
|
|
|
|
cancel context.CancelFunc
|
|
|
|
beaconDB ethdb.Database
|
|
|
|
chain *BeaconChain
|
|
|
|
web3Service *powchain.Web3Service
|
|
|
|
validator bool
|
|
|
|
incomingBlockFeed *event.Feed
|
|
|
|
incomingBlockChan chan *types.Block
|
|
|
|
canonicalBlockFeed *event.Feed
|
|
|
|
canonicalCrystallizedStateFeed *event.Feed
|
|
|
|
latestProcessedBlock chan *types.Block
|
2018-09-02 16:44:03 +00:00
|
|
|
candidateBlock *types.Block
|
|
|
|
candidateActiveState *types.ActiveState
|
|
|
|
candidateCrystallizedState *types.CrystallizedState
|
2018-07-19 16:31:50 +00:00
|
|
|
}
|
|
|
|
|
2018-08-09 22:54:59 +00:00
|
|
|
// Config options for the service.
|
|
|
|
type Config struct {
|
2018-08-24 04:09:59 +00:00
|
|
|
BeaconBlockBuf int
|
|
|
|
IncomingBlockBuf int
|
|
|
|
Chain *BeaconChain
|
|
|
|
Web3Service *powchain.Web3Service
|
|
|
|
BeaconDB ethdb.Database
|
2018-08-09 22:54:59 +00:00
|
|
|
}
|
|
|
|
|
2018-07-19 16:31:50 +00:00
|
|
|
// NewChainService instantiates a new service instance that will
|
|
|
|
// be registered into a running beacon node.
|
2018-08-24 04:09:59 +00:00
|
|
|
func NewChainService(ctx context.Context, cfg *Config) (*ChainService, error) {
|
2018-07-19 16:31:50 +00:00
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
2018-08-20 15:50:11 +00:00
|
|
|
var isValidator bool
|
2018-08-24 04:09:59 +00:00
|
|
|
if cfg.Web3Service == nil {
|
2018-08-20 15:50:11 +00:00
|
|
|
isValidator = false
|
|
|
|
} else {
|
|
|
|
isValidator = true
|
|
|
|
}
|
2018-07-31 04:41:27 +00:00
|
|
|
return &ChainService{
|
2018-09-02 16:44:03 +00:00
|
|
|
ctx: ctx,
|
|
|
|
chain: cfg.Chain,
|
|
|
|
cancel: cancel,
|
|
|
|
beaconDB: cfg.BeaconDB,
|
|
|
|
web3Service: cfg.Web3Service,
|
|
|
|
validator: isValidator,
|
|
|
|
latestProcessedBlock: make(chan *types.Block, cfg.BeaconBlockBuf),
|
|
|
|
incomingBlockChan: make(chan *types.Block, cfg.IncomingBlockBuf),
|
|
|
|
incomingBlockFeed: new(event.Feed),
|
|
|
|
canonicalBlockFeed: new(event.Feed),
|
|
|
|
canonicalCrystallizedStateFeed: new(event.Feed),
|
|
|
|
candidateBlock: nilBlock,
|
|
|
|
candidateActiveState: nilActiveState,
|
|
|
|
candidateCrystallizedState: nilCrystallizedState,
|
2018-07-31 04:41:27 +00:00
|
|
|
}, nil
|
2018-07-19 16:31:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start a blockchain service's main event loop.
|
|
|
|
func (c *ChainService) Start() {
|
2018-08-20 15:50:11 +00:00
|
|
|
if c.validator {
|
|
|
|
log.Infof("Starting service as validator")
|
|
|
|
} else {
|
|
|
|
log.Infof("Starting service as observer")
|
|
|
|
}
|
2018-08-24 04:09:59 +00:00
|
|
|
// TODO: Fetch the slot: (block, state) DAGs from persistent storage
|
|
|
|
// to truly continue across sessions.
|
|
|
|
go c.blockProcessing(c.ctx.Done())
|
2018-07-19 16:31:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Stop the blockchain service's main event loop and associated goroutines.
|
|
|
|
func (c *ChainService) Stop() error {
|
|
|
|
defer c.cancel()
|
2018-07-25 16:57:44 +00:00
|
|
|
log.Info("Stopping service")
|
2018-07-31 04:41:27 +00:00
|
|
|
log.Infof("Persisting current active and crystallized states before closing")
|
|
|
|
if err := c.chain.PersistActiveState(); err != nil {
|
|
|
|
return fmt.Errorf("Error persisting active state: %v", err)
|
|
|
|
}
|
|
|
|
if err := c.chain.PersistCrystallizedState(); err != nil {
|
|
|
|
return fmt.Errorf("Error persisting crystallized state: %v", err)
|
|
|
|
}
|
2018-07-19 16:31:50 +00:00
|
|
|
return nil
|
|
|
|
}
|
2018-07-22 16:58:14 +00:00
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
// IncomingBlockFeed returns a feed that a sync service can send incoming p2p blocks into.
|
|
|
|
// The chain service will subscribe to this feed in order to process incoming blocks.
|
|
|
|
func (c *ChainService) IncomingBlockFeed() *event.Feed {
|
|
|
|
return c.incomingBlockFeed
|
|
|
|
}
|
|
|
|
|
2018-08-07 12:12:10 +00:00
|
|
|
// HasStoredState checks if there is any Crystallized/Active State or blocks(not implemented) are
|
|
|
|
// persisted to the db.
|
|
|
|
func (c *ChainService) HasStoredState() (bool, error) {
|
|
|
|
|
2018-09-02 16:44:03 +00:00
|
|
|
hasCrystallized, err := c.beaconDB.Has(crystallizedStateLookupKey)
|
2018-08-07 12:12:10 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
2018-09-02 16:44:03 +00:00
|
|
|
return hasCrystallized, nil
|
2018-08-07 12:12:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// SaveBlock is a mock which saves a block to the local db using the
|
|
|
|
// blockhash as the key.
|
|
|
|
func (c *ChainService) SaveBlock(block *types.Block) error {
|
|
|
|
return c.chain.saveBlock(block)
|
|
|
|
}
|
|
|
|
|
2018-07-25 16:57:44 +00:00
|
|
|
// ContainsBlock checks if a block for the hash exists in the chain.
|
2018-08-14 00:58:37 +00:00
|
|
|
// This method must be safe to call from a goroutine.
|
2018-07-28 19:53:02 +00:00
|
|
|
func (c *ChainService) ContainsBlock(h [32]byte) bool {
|
2018-07-25 16:57:44 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2018-07-31 04:41:27 +00:00
|
|
|
// CurrentCrystallizedState of the canonical chain.
|
|
|
|
func (c *ChainService) CurrentCrystallizedState() *types.CrystallizedState {
|
|
|
|
return c.chain.CrystallizedState()
|
|
|
|
}
|
|
|
|
|
|
|
|
// CurrentActiveState of the canonical chain.
|
|
|
|
func (c *ChainService) CurrentActiveState() *types.ActiveState {
|
|
|
|
return c.chain.ActiveState()
|
|
|
|
}
|
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
// CanonicalBlockFeed returns a channel that is written to
|
2018-08-18 03:34:56 +00:00
|
|
|
// whenever a new block is determined to be canonical in the chain.
|
2018-08-24 04:09:59 +00:00
|
|
|
func (c *ChainService) CanonicalBlockFeed() *event.Feed {
|
|
|
|
return c.canonicalBlockFeed
|
2018-08-18 03:34:56 +00:00
|
|
|
}
|
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
// CanonicalCrystallizedStateFeed returns a feed that is written to
|
2018-08-18 03:34:56 +00:00
|
|
|
// whenever a new crystallized state is determined to be canonical in the chain.
|
2018-08-24 04:09:59 +00:00
|
|
|
func (c *ChainService) CanonicalCrystallizedStateFeed() *event.Feed {
|
|
|
|
return c.canonicalCrystallizedStateFeed
|
|
|
|
}
|
|
|
|
|
|
|
|
// updateHead applies the fork choice rule to the last received
|
|
|
|
// slot.
|
|
|
|
func (c *ChainService) updateHead(slot uint64) {
|
|
|
|
// Super naive fork choice rule: pick the first element at each slot
|
|
|
|
// level as canonical.
|
|
|
|
//
|
|
|
|
// TODO: Implement real fork choice rule here.
|
2018-09-02 16:44:03 +00:00
|
|
|
log.WithField("slotNumber", c.candidateBlock.SlotNumber()).Info("Applying fork choice rule")
|
|
|
|
if err := c.chain.SetActiveState(c.candidateActiveState); err != nil {
|
2018-08-24 04:09:59 +00:00
|
|
|
log.Errorf("Write active state to disk failed: %v", err)
|
|
|
|
}
|
|
|
|
|
2018-09-02 16:44:03 +00:00
|
|
|
if err := c.chain.SetCrystallizedState(c.candidateCrystallizedState); err != nil {
|
2018-08-24 04:09:59 +00:00
|
|
|
log.Errorf("Write crystallized state to disk failed: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: Utilize this value in the fork choice rule.
|
2018-08-31 02:55:52 +00:00
|
|
|
vals, err := casper.ShuffleValidatorsToCommittees(
|
2018-09-02 16:44:03 +00:00
|
|
|
c.candidateCrystallizedState.DynastySeed(),
|
|
|
|
c.candidateCrystallizedState.Validators(),
|
|
|
|
c.candidateCrystallizedState.CurrentDynasty(),
|
|
|
|
c.candidateCrystallizedState.CrosslinkingStartShard(),
|
|
|
|
)
|
2018-08-25 18:59:46 +00:00
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
if err != nil {
|
2018-09-01 16:01:53 +00:00
|
|
|
log.Errorf("Unable to get validators by slot and by shard: %v", err)
|
2018-08-24 04:09:59 +00:00
|
|
|
return
|
|
|
|
}
|
2018-09-01 16:01:53 +00:00
|
|
|
log.Debugf("Received %d validators by slot", len(vals))
|
2018-08-24 04:09:59 +00:00
|
|
|
|
2018-09-02 16:44:03 +00:00
|
|
|
h, err := c.candidateBlock.Hash()
|
2018-08-24 04:09:59 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Unable to hash canonical block: %v", err)
|
|
|
|
return
|
|
|
|
}
|
2018-09-02 16:44:03 +00:00
|
|
|
|
|
|
|
// Save canonical slotnumber to DB.
|
|
|
|
if err := c.chain.saveCanonicalSlotNumber(c.candidateBlock.SlotNumber(), h); err != nil {
|
|
|
|
log.Errorf("Unable to save slot number to db: %v", err)
|
|
|
|
}
|
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
// Save canonical block to DB.
|
2018-09-02 16:44:03 +00:00
|
|
|
if err := c.chain.saveCanonicalBlock(c.candidateBlock); err != nil {
|
2018-08-24 04:09:59 +00:00
|
|
|
log.Errorf("Unable to save block to db: %v", err)
|
|
|
|
}
|
|
|
|
log.WithField("blockHash", fmt.Sprintf("0x%x", h)).Info("Canonical block determined")
|
|
|
|
|
|
|
|
// We fire events that notify listeners of a new block (or crystallized state in
|
|
|
|
// the case of a state transition). This is useful for the beacon node's gRPC
|
|
|
|
// server to stream these events to beacon clients.
|
|
|
|
transition := c.chain.IsCycleTransition(slot)
|
|
|
|
if transition {
|
2018-09-02 16:44:03 +00:00
|
|
|
c.canonicalCrystallizedStateFeed.Send(c.candidateCrystallizedState)
|
2018-08-24 04:09:59 +00:00
|
|
|
}
|
2018-09-02 16:44:03 +00:00
|
|
|
c.canonicalBlockFeed.Send(c.candidateBlock)
|
|
|
|
|
|
|
|
c.candidateBlock = nilBlock
|
|
|
|
c.candidateActiveState = nilActiveState
|
|
|
|
c.candidateCrystallizedState = nilCrystallizedState
|
2018-08-18 03:34:56 +00:00
|
|
|
}
|
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
func (c *ChainService) blockProcessing(done <-chan struct{}) {
|
|
|
|
sub := c.incomingBlockFeed.Subscribe(c.incomingBlockChan)
|
|
|
|
defer sub.Unsubscribe()
|
2018-07-22 16:58:14 +00:00
|
|
|
for {
|
|
|
|
select {
|
2018-08-24 04:09:59 +00:00
|
|
|
case <-done:
|
|
|
|
log.Debug("Chain service context closed, exiting goroutine")
|
|
|
|
return
|
|
|
|
// Listen for a newly received incoming block from the sync service.
|
|
|
|
case block := <-c.incomingBlockChan:
|
|
|
|
// 3 steps:
|
|
|
|
// - Compute the active state for the block.
|
|
|
|
// - Compute the crystallized state for the block if cycle transition.
|
|
|
|
// - Store both states and the block into a data structure used for fork choice.
|
|
|
|
//
|
|
|
|
// Another routine will run that will continually compute
|
|
|
|
// the canonical block and states from this data structure using the
|
|
|
|
// fork choice rule.
|
|
|
|
var canProcess bool
|
|
|
|
var err error
|
2018-08-29 23:21:15 +00:00
|
|
|
var blockVoteCache map[[32]byte]*types.VoteCache
|
2018-08-24 04:09:59 +00:00
|
|
|
|
|
|
|
h, err := block.Hash()
|
2018-08-14 00:58:37 +00:00
|
|
|
if err != nil {
|
2018-08-24 04:09:59 +00:00
|
|
|
log.Debugf("Could not hash incoming block: %v", err)
|
2018-08-14 00:58:37 +00:00
|
|
|
}
|
2018-07-29 16:22:15 +00:00
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
receivedSlotNumber := block.SlotNumber()
|
|
|
|
|
|
|
|
log.WithField("blockHash", fmt.Sprintf("0x%x", h)).Info("Received full block, processing validity conditions")
|
|
|
|
|
2018-09-02 16:44:03 +00:00
|
|
|
parentExists, err := c.chain.hasBlock(block.ParentHash())
|
|
|
|
if err != nil {
|
|
|
|
log.Debugf("Could not check existence of parent hash: %v", err)
|
2018-07-29 16:22:15 +00:00
|
|
|
}
|
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
// If parentHash does not exist, received block fails validity conditions.
|
2018-09-02 16:44:03 +00:00
|
|
|
if !parentExists && receivedSlotNumber > 1 {
|
2018-08-24 04:09:59 +00:00
|
|
|
continue
|
2018-08-15 04:49:59 +00:00
|
|
|
}
|
2018-08-18 03:34:56 +00:00
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
// Process block as a validator if beacon node has registered, else process block as an observer.
|
|
|
|
if c.validator {
|
|
|
|
canProcess, err = c.chain.CanProcessBlock(c.web3Service.Client(), block, true)
|
|
|
|
} else {
|
|
|
|
canProcess, err = c.chain.CanProcessBlock(nil, block, false)
|
|
|
|
}
|
2018-08-15 04:49:59 +00:00
|
|
|
if err != nil {
|
2018-08-24 04:09:59 +00:00
|
|
|
// We might receive a lot of blocks that fail validity conditions,
|
|
|
|
// so we create a debug level log instead of an error log.
|
|
|
|
log.Debugf("Incoming block failed validity conditions: %v", err)
|
2018-08-15 04:49:59 +00:00
|
|
|
}
|
|
|
|
|
2018-08-31 02:55:52 +00:00
|
|
|
// If we cannot process this block, we keep listening.
|
|
|
|
if !canProcess {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-08-29 00:55:56 +00:00
|
|
|
// Process attestations as a beacon chain node.
|
|
|
|
var processedAttestations []*pb.AttestationRecord
|
|
|
|
for index, attestation := range block.Attestations() {
|
|
|
|
// Don't add invalid attestation to block vote cache.
|
|
|
|
if err := c.chain.processAttestation(index, block); err == nil {
|
|
|
|
processedAttestations = append(processedAttestations, attestation)
|
|
|
|
blockVoteCache, err = c.chain.calculateBlockVoteCache(index, block)
|
|
|
|
if err != nil {
|
|
|
|
log.Debugf("could not calculate new block vote cache: %v", nil)
|
|
|
|
}
|
|
|
|
}
|
2018-08-24 16:07:23 +00:00
|
|
|
}
|
|
|
|
|
2018-09-02 16:44:03 +00:00
|
|
|
// If we cannot process this block, we keep listening.
|
|
|
|
if !canProcess {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.candidateBlock != nilBlock && receivedSlotNumber > c.candidateBlock.SlotNumber() && receivedSlotNumber > 1 {
|
2018-08-24 04:09:59 +00:00
|
|
|
c.updateHead(receivedSlotNumber)
|
2018-08-18 03:34:56 +00:00
|
|
|
}
|
2018-08-24 04:09:59 +00:00
|
|
|
|
2018-09-02 16:44:03 +00:00
|
|
|
if err := c.chain.saveBlock(block); err != nil {
|
|
|
|
log.Errorf("Failed to save block: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Info("Finished processing received block")
|
|
|
|
|
|
|
|
// Do not proceed further, because a candidate has already been chosen.
|
|
|
|
if c.candidateBlock != nilBlock {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
// 3 steps:
|
|
|
|
// - Compute the active state for the block.
|
|
|
|
// - Compute the crystallized state for the block if cycle transition.
|
|
|
|
// - Store both states and the block into a data structure used for fork choice
|
|
|
|
//
|
|
|
|
// This data structure will be used by the updateHead function to determine
|
|
|
|
// canonical blocks and states.
|
|
|
|
// TODO: Using latest block hash for seed, this will eventually be replaced by randao.
|
2018-08-29 23:21:15 +00:00
|
|
|
|
2018-08-24 04:09:59 +00:00
|
|
|
// Entering cycle transitions.
|
2018-09-02 16:44:03 +00:00
|
|
|
isTransition := c.chain.IsCycleTransition(receivedSlotNumber)
|
|
|
|
activeState := c.chain.ActiveState()
|
|
|
|
crystallizedState := c.chain.CrystallizedState()
|
|
|
|
if isTransition {
|
|
|
|
crystallizedState, activeState = c.chain.initCycle(crystallizedState, activeState)
|
|
|
|
}
|
2018-08-29 23:21:15 +00:00
|
|
|
|
2018-09-02 16:44:03 +00:00
|
|
|
activeState, err = c.chain.computeNewActiveState(processedAttestations, activeState, blockVoteCache, h)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Compute active state failed: %v", err)
|
2018-08-24 04:09:59 +00:00
|
|
|
}
|
|
|
|
|
2018-09-02 16:44:03 +00:00
|
|
|
c.candidateBlock = block
|
|
|
|
c.candidateActiveState = activeState
|
|
|
|
c.candidateCrystallizedState = crystallizedState
|
|
|
|
|
|
|
|
log.Info("Finished processing state for candidate block")
|
2018-07-22 16:58:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|