prysm-pulse/beacon-chain/blockchain/execution_engine.go

277 lines
11 KiB
Go
Raw Normal View History

package blockchain
import (
"context"
"fmt"
"github.com/pkg/errors"
2022-04-06 23:36:52 +00:00
types "github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
2022-04-06 23:36:52 +00:00
"github.com/prysmaticlabs/prysm/beacon-chain/core/time"
"github.com/prysmaticlabs/prysm/beacon-chain/core/transition"
"github.com/prysmaticlabs/prysm/beacon-chain/db/kv"
"github.com/prysmaticlabs/prysm/beacon-chain/powchain"
2022-04-06 23:36:52 +00:00
"github.com/prysmaticlabs/prysm/beacon-chain/state"
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
enginev1 "github.com/prysmaticlabs/prysm/proto/engine/v1"
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1/block"
2022-04-06 23:36:52 +00:00
"github.com/prysmaticlabs/prysm/time/slots"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)
// notifyForkchoiceUpdate signals execution engine the fork choice updates. Execution engine should:
// 1. Re-organizes the execution payload chain and corresponding state to make head_block_hash the head.
// 2. Applies finality to the execution state: it irreversibly persists the chain of all execution payloads and corresponding state, up to and including finalized_block_hash.
2022-04-06 23:36:52 +00:00
func (s *Service) notifyForkchoiceUpdate(ctx context.Context, headState state.BeaconState, headBlk block.BeaconBlock, headRoot [32]byte, finalizedRoot [32]byte) (*enginev1.PayloadIDBytes, error) {
ctx, span := trace.StartSpan(ctx, "blockChain.notifyForkchoiceUpdate")
defer span.End()
if headBlk == nil || headBlk.IsNil() || headBlk.Body().IsNil() {
return nil, errors.New("nil head block")
}
// Must not call fork choice updated until the transition conditions are met on the Pow network.
isExecutionBlk, err := blocks.IsExecutionBlock(headBlk.Body())
if err != nil {
return nil, errors.Wrap(err, "could not determine if block is execution block")
}
if !isExecutionBlk {
return nil, nil
}
headPayload, err := headBlk.Body().ExecutionPayload()
if err != nil {
return nil, errors.Wrap(err, "could not get execution payload")
}
finalizedBlock, err := s.cfg.BeaconDB.Block(ctx, s.ensureRootNotZeros(finalizedRoot))
if err != nil {
return nil, errors.Wrap(err, "could not get finalized block")
}
Enable Bellatrix E2E (#10437) * Fix finding terminal block hash calculation * Update mainnet_config.go * Update beacon_block.pb.go * Various fixes to pass all spec tests for Merge (#9777) * Proper upgrade altair to merge state * Use uint64 for ttd * Correctly upgrade to merge state + object mapping fixes * Use proper receive block path for initial syncing * Disable contract lookback * Disable deposit contract lookback * Go fmt * Merge: switch from go bindings to raw rpc calls (#9803) * Disable genesis ETH1.0 chain header logging * Update htrutils.go * all gossip tests passing * Remove gas validations * Update penalty params for Merge * Fix gossip and tx size limits for the merge part 1 * Remove extraneous p2p condition * Add and use * Add and use TBH_ACTIVATION_EPOCH * Update WORKSPACE * Update Kintsugi engine API (#9865) * Kintsugi ssz (#9867) * All spec tests pass * Update spec test shas * Update Kintsugi consensus implementations (#9872) * Remove secp256k1 * Remove unused merge genesis state gen tool * Manually override nil transaction field. M2 works * Fix bad hex conversion * Change Gossip message size and Chunk SIze from 1 MB t0 10MB (#9860) * change gossip size and chunk size after merge * change ssz to accomodate both changes * gofmt config file * add testcase for merge MsgId * Update beacon-chain/p2p/message_id.go Change MB to Mib in comment Co-authored-by: terence tsao <terence@prysmaticlabs.com> * change function name from altairMsgID to postAltairMsgID Co-authored-by: terence tsao <terence@prysmaticlabs.com> * Sync with develop * Merge branch 'develop' of github.com:prysmaticlabs/prysm into kintsugi * Update state_trie.go * Clean up conflicts * Fix build * Update config to devnet1 * Fix state merge * Handle merge test case for update balance * Fix build * State pkg cleanup * Fix a bug with loading mainnet state * Fix transactions root * Add v2 endpoint for merge blocks (#9802) * Add V2 blocks endpoint for merge blocks * Update beacon-chain/rpc/apimiddleware/structs.go Co-authored-by: Radosław Kapka <rkapka@wp.pl> * go mod * fix transactions * Terence's comments * add missing file Co-authored-by: Radosław Kapka <rkapka@wp.pl> * Sync * Go mod tidy * change EP field names * latest kintusgi execution api * fix conflicts * converting base fee to big endian format (#10018) * ReverseByteOrder function does not mess the input * sync with develop * use merge gossip sizes * correct gossip sizes this time * visibility * clean ups * Sync with develop, fix payload nil check bug * Speed up syncing, hide cosmetic errors * Sync with develop * Clean up after sync * Update generate_keys.go * sync with develop * Update mainnet_config.go * Clean ups * Sync optimistically candidate blocks (#10193) * Revert "Sync optimistically candidate blocks (#10193)" This reverts commit f99a0419ef1efc4bda0be77f22165b8fe4377c0d. * Sync optimistically candidate blocks (#10193) * allow optimistic sync * Fix merge transition block validation * Update proposer.go * Sync with develop * delete deprecated client, update testnet flag * Change optimistic logic (#10194) * Logs and err handling * Fix build * Clean ups * Add back get payload * c * Done * Rm uncommented * Optimistic sync: prysm validator rpcs (#10200) * Logs to reproduce * Use pointers * Use pointers * Use pointers * Update json_marshal_unmarshal.go * Fix marshal * Update json_marshal_unmarshal.go * Log * string total diff * str * marshal un * set string * json * gaz * Comment out optimistic status * remove kiln flag here (#10269) * Sync with devleop * Sync with develop * clean ups * refactor engine calls * Update process_block.go * Fix deadlock, uncomment duty opt sync * Update proposer_execution_payload.go * Sync with develop * Rm post state check * Bypass eth1 data checks * Update proposer_execution_payload.go * Return early if ttd is not reached * Sync with devleop * Update process_block.go * Update receive_block.go * Update bzl * Revert "Update receive_block.go" This reverts commit 5b4a87c512325d9f26de4db7f941dcd7303cd0d8. * Fix run time * add in all the fixes * fix evaluator bugs * latest fixes * sum * fix to be configurable * Update go.mod * Fix AltairCompatible to account for future state version * Update proposer_execution_payload.go * fix broken conditional checks * fix all issues * Handle pre state Altair with valid payload * Handle pre state Altair with valid payload * Log bellatrix fields * Update log.go * Revert "fix broken conditional checks" This reverts commit e118db6c20172783a3bb573d2f78670f0207ec1e. * LH multiclient working * Friendly fee recipient log * Remove extra SetOptimisticToValid * fix race * fix test * Fix base fee per gas * Fix notifypayload headroot * tx fuzzer * clean up with develop branch * save progress * 200tx/block * add LH flags * Sync with devleop * cleanup * cleanup * hash * fix build * fix test * fix go check * fmt * gosec * add deps * cleanup * fix up * change gas price * remove flag * last fix * use new LH version * fix up * fix finalized block panic Co-authored-by: terence tsao <terence@prysmaticlabs.com> Co-authored-by: Zahoor Mohamed <zahoor@zahoor.in> Co-authored-by: kasey <489222+kasey@users.noreply.github.com> Co-authored-by: Potuz <potuz@prysmaticlabs.com> Co-authored-by: Radosław Kapka <rkapka@wp.pl> Co-authored-by: Zahoor Mohamed <zahoor@prysmaticlabs.com> Co-authored-by: Raul Jordan <raul@prysmaticlabs.com> Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2022-04-05 14:02:46 +00:00
if finalizedBlock == nil || finalizedBlock.IsNil() {
finalizedBlock = s.getInitSyncBlock(s.ensureRootNotZeros(finalizedRoot))
if finalizedBlock == nil || finalizedBlock.IsNil() {
return nil, errors.Errorf("finalized block with root %#x does not exist in the db or our cache", s.ensureRootNotZeros(finalizedRoot))
}
}
var finalizedHash []byte
if blocks.IsPreBellatrixVersion(finalizedBlock.Block().Version()) {
finalizedHash = params.BeaconConfig().ZeroHash[:]
} else {
payload, err := finalizedBlock.Block().Body().ExecutionPayload()
if err != nil {
return nil, errors.Wrap(err, "could not get finalized block execution payload")
}
finalizedHash = payload.BlockHash
}
fcs := &enginev1.ForkchoiceState{
HeadBlockHash: headPayload.BlockHash,
SafeBlockHash: headPayload.BlockHash,
FinalizedBlockHash: finalizedHash,
}
2022-04-06 23:36:52 +00:00
nextSlot := s.CurrentSlot() + 1 // Cache payload ID for next slot proposer.
hasAttr, attr, proposerId, err := s.getPayloadAttribute(ctx, headState, nextSlot)
if err != nil {
return nil, errors.Wrap(err, "could not get payload attribute")
}
payloadID, _, err := s.cfg.ExecutionEngineCaller.ForkchoiceUpdated(ctx, fcs, attr)
if err != nil {
switch err {
case powchain.ErrAcceptedSyncingPayloadStatus:
forkchoiceUpdatedOptimisticNodeCount.Inc()
log.WithFields(logrus.Fields{
2022-04-09 23:09:04 +00:00
"headSlot": headBlk.Slot(),
"headPayloadBlockHash": fmt.Sprintf("%#x", bytesutil.Trunc(headPayload.BlockHash)),
"finalizedPayloadBlockHash": fmt.Sprintf("%#x", bytesutil.Trunc(finalizedHash)),
}).Info("Called fork choice updated with optimistic block")
return payloadID, nil
default:
return nil, errors.Wrap(err, "could not notify forkchoice update from execution engine")
}
}
forkchoiceUpdatedValidNodeCount.Inc()
if err := s.cfg.ForkChoiceStore.SetOptimisticToValid(ctx, headRoot); err != nil {
return nil, errors.Wrap(err, "could not set block to valid")
}
2022-04-06 23:36:52 +00:00
if hasAttr { // If the forkchoice update call has an attribute, update the proposer payload ID cache.
var pId [8]byte
copy(pId[:], payloadID[:])
s.cfg.ProposerSlotIndexCache.SetProposerAndPayloadIDs(nextSlot, proposerId, pId)
}
return payloadID, nil
}
// notifyForkchoiceUpdate signals execution engine on a new payload.
// It returns true if the EL has returned VALID for the block
Use correct pre state to call new payload (#10416) * Update todo strings * Go fmt * add merge specific checks when receiving a block from gossip * Fix beacon chain build * Interop merge beacon state * fix finding Transactions size * Update go commit * Merge union debugging (#9751) * changes test cases per ssz changes * noisy commit, restoring pb field order codegen * get rid of codegen garbage * M2 works with Geth 🎉 * Fix bazel build //... * restoring generated pb field ordering * defensive nil check * separate ExecutionPayload/Header from codegen * tell bazel about this new file * Merge: support terminal difficulty override (#9769) * Fix finding terminal block hash calculation * Update mainnet_config.go * Update beacon_block.pb.go * Various fixes to pass all spec tests for Merge (#9777) * Proper upgrade altair to merge state * Use uint64 for ttd * Correctly upgrade to merge state + object mapping fixes * Use proper receive block path for initial syncing * Disable contract lookback * Disable deposit contract lookback * Go fmt * Merge: switch from go bindings to raw rpc calls (#9803) * Disable genesis ETH1.0 chain header logging * Update htrutils.go * all gossip tests passing * Remove gas validations * Update penalty params for Merge * Fix gossip and tx size limits for the merge part 1 * Remove extraneous p2p condition * Add and use * Add and use TBH_ACTIVATION_EPOCH * Update WORKSPACE * Update Kintsugi engine API (#9865) * Kintsugi ssz (#9867) * All spec tests pass * Update spec test shas * Update Kintsugi consensus implementations (#9872) * Remove secp256k1 * Remove unused merge genesis state gen tool * Manually override nil transaction field. M2 works * Fix bad hex conversion * Change Gossip message size and Chunk SIze from 1 MB t0 10MB (#9860) * change gossip size and chunk size after merge * change ssz to accomodate both changes * gofmt config file * add testcase for merge MsgId * Update beacon-chain/p2p/message_id.go Change MB to Mib in comment Co-authored-by: terence tsao <terence@prysmaticlabs.com> * change function name from altairMsgID to postAltairMsgID Co-authored-by: terence tsao <terence@prysmaticlabs.com> * Sync with develop * Merge branch 'develop' of github.com:prysmaticlabs/prysm into kintsugi * Update state_trie.go * Clean up conflicts * Fix build * Update config to devnet1 * Fix state merge * Handle merge test case for update balance * Fix build * State pkg cleanup * Fix a bug with loading mainnet state * Fix transactions root * Add v2 endpoint for merge blocks (#9802) * Add V2 blocks endpoint for merge blocks * Update beacon-chain/rpc/apimiddleware/structs.go Co-authored-by: Radosław Kapka <rkapka@wp.pl> * go mod * fix transactions * Terence's comments * add missing file Co-authored-by: Radosław Kapka <rkapka@wp.pl> * Sync * Go mod tidy * change EP field names * latest kintusgi execution api * fix conflicts * converting base fee to big endian format (#10018) * ReverseByteOrder function does not mess the input * sync with develop * use merge gossip sizes * correct gossip sizes this time * visibility * clean ups * Sync with develop, fix payload nil check bug * Speed up syncing, hide cosmetic errors * Sync with develop * Clean up after sync * Update generate_keys.go * sync with develop * Update mainnet_config.go * Clean ups * Sync optimistically candidate blocks (#10193) * Revert "Sync optimistically candidate blocks (#10193)" This reverts commit f99a0419ef1efc4bda0be77f22165b8fe4377c0d. * Sync optimistically candidate blocks (#10193) * allow optimistic sync * Fix merge transition block validation * Update proposer.go * Sync with develop * delete deprecated client, update testnet flag * Change optimistic logic (#10194) * Logs and err handling * Fix build * Clean ups * Add back get payload * c * Done * Rm uncommented * Optimistic sync: prysm validator rpcs (#10200) * Logs to reproduce * Use pointers * Use pointers * Use pointers * Update json_marshal_unmarshal.go * Fix marshal * Update json_marshal_unmarshal.go * Log * string total diff * str * marshal un * set string * json * gaz * Comment out optimistic status * remove kiln flag here (#10269) * Sync with devleop * Sync with develop * clean ups * refactor engine calls * Update process_block.go * Fix deadlock, uncomment duty opt sync * Update proposer_execution_payload.go * Sync with develop * Rm post state check * Bypass eth1 data checks * Update proposer_execution_payload.go * Return early if ttd is not reached * Sync with devleop * Update process_block.go * Update receive_block.go * Update bzl * Revert "Update receive_block.go" This reverts commit 5b4a87c512325d9f26de4db7f941dcd7303cd0d8. * Fix run time * Update go.mod * Fix AltairCompatible to account for future state version * Update proposer_execution_payload.go * Handle pre state Altair with valid payload * Handle pre state Altair with valid payload * Log bellatrix fields * Update log.go * Friendly fee recipient log * Remove extra SetOptimisticToValid * Fix base fee per gas * Fix notifypayload headroot * clean up with develop branch * Sync with devleop * Fix * Fix * fix * Fix * fix tests * revert some changes * fix tests * Update optimistic_sync_test.go * Simplify IsExecutionEnabledUsingHeader Co-authored-by: Zahoor Mohamed <zahoor@prysmaticlabs.com> Co-authored-by: Zahoor Mohamed <zahoor@zahoor.in> Co-authored-by: kasey <489222+kasey@users.noreply.github.com> Co-authored-by: Kasey Kirkham <kasey@users.noreply.github.com> Co-authored-by: Potuz <potuz@prysmaticlabs.com> Co-authored-by: Radosław Kapka <rkapka@wp.pl> Co-authored-by: Raul Jordan <raul@prysmaticlabs.com> Co-authored-by: Nishant Das <nishdas93@gmail.com> Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2022-03-25 16:03:15 +00:00
func (s *Service) notifyNewPayload(ctx context.Context, preStateVersion, postStateVersion int,
preStateHeader, postStateHeader *ethpb.ExecutionPayloadHeader, blk block.SignedBeaconBlock) (bool, error) {
ctx, span := trace.StartSpan(ctx, "blockChain.notifyNewPayload")
defer span.End()
// Execution payload is only supported in Bellatrix and beyond. Pre
// merge blocks are never optimistic
if blocks.IsPreBellatrixVersion(postStateVersion) {
return true, nil
}
if err := helpers.BeaconBlockIsNil(blk); err != nil {
return false, err
}
body := blk.Block().Body()
Use correct pre state to call new payload (#10416) * Update todo strings * Go fmt * add merge specific checks when receiving a block from gossip * Fix beacon chain build * Interop merge beacon state * fix finding Transactions size * Update go commit * Merge union debugging (#9751) * changes test cases per ssz changes * noisy commit, restoring pb field order codegen * get rid of codegen garbage * M2 works with Geth 🎉 * Fix bazel build //... * restoring generated pb field ordering * defensive nil check * separate ExecutionPayload/Header from codegen * tell bazel about this new file * Merge: support terminal difficulty override (#9769) * Fix finding terminal block hash calculation * Update mainnet_config.go * Update beacon_block.pb.go * Various fixes to pass all spec tests for Merge (#9777) * Proper upgrade altair to merge state * Use uint64 for ttd * Correctly upgrade to merge state + object mapping fixes * Use proper receive block path for initial syncing * Disable contract lookback * Disable deposit contract lookback * Go fmt * Merge: switch from go bindings to raw rpc calls (#9803) * Disable genesis ETH1.0 chain header logging * Update htrutils.go * all gossip tests passing * Remove gas validations * Update penalty params for Merge * Fix gossip and tx size limits for the merge part 1 * Remove extraneous p2p condition * Add and use * Add and use TBH_ACTIVATION_EPOCH * Update WORKSPACE * Update Kintsugi engine API (#9865) * Kintsugi ssz (#9867) * All spec tests pass * Update spec test shas * Update Kintsugi consensus implementations (#9872) * Remove secp256k1 * Remove unused merge genesis state gen tool * Manually override nil transaction field. M2 works * Fix bad hex conversion * Change Gossip message size and Chunk SIze from 1 MB t0 10MB (#9860) * change gossip size and chunk size after merge * change ssz to accomodate both changes * gofmt config file * add testcase for merge MsgId * Update beacon-chain/p2p/message_id.go Change MB to Mib in comment Co-authored-by: terence tsao <terence@prysmaticlabs.com> * change function name from altairMsgID to postAltairMsgID Co-authored-by: terence tsao <terence@prysmaticlabs.com> * Sync with develop * Merge branch 'develop' of github.com:prysmaticlabs/prysm into kintsugi * Update state_trie.go * Clean up conflicts * Fix build * Update config to devnet1 * Fix state merge * Handle merge test case for update balance * Fix build * State pkg cleanup * Fix a bug with loading mainnet state * Fix transactions root * Add v2 endpoint for merge blocks (#9802) * Add V2 blocks endpoint for merge blocks * Update beacon-chain/rpc/apimiddleware/structs.go Co-authored-by: Radosław Kapka <rkapka@wp.pl> * go mod * fix transactions * Terence's comments * add missing file Co-authored-by: Radosław Kapka <rkapka@wp.pl> * Sync * Go mod tidy * change EP field names * latest kintusgi execution api * fix conflicts * converting base fee to big endian format (#10018) * ReverseByteOrder function does not mess the input * sync with develop * use merge gossip sizes * correct gossip sizes this time * visibility * clean ups * Sync with develop, fix payload nil check bug * Speed up syncing, hide cosmetic errors * Sync with develop * Clean up after sync * Update generate_keys.go * sync with develop * Update mainnet_config.go * Clean ups * Sync optimistically candidate blocks (#10193) * Revert "Sync optimistically candidate blocks (#10193)" This reverts commit f99a0419ef1efc4bda0be77f22165b8fe4377c0d. * Sync optimistically candidate blocks (#10193) * allow optimistic sync * Fix merge transition block validation * Update proposer.go * Sync with develop * delete deprecated client, update testnet flag * Change optimistic logic (#10194) * Logs and err handling * Fix build * Clean ups * Add back get payload * c * Done * Rm uncommented * Optimistic sync: prysm validator rpcs (#10200) * Logs to reproduce * Use pointers * Use pointers * Use pointers * Update json_marshal_unmarshal.go * Fix marshal * Update json_marshal_unmarshal.go * Log * string total diff * str * marshal un * set string * json * gaz * Comment out optimistic status * remove kiln flag here (#10269) * Sync with devleop * Sync with develop * clean ups * refactor engine calls * Update process_block.go * Fix deadlock, uncomment duty opt sync * Update proposer_execution_payload.go * Sync with develop * Rm post state check * Bypass eth1 data checks * Update proposer_execution_payload.go * Return early if ttd is not reached * Sync with devleop * Update process_block.go * Update receive_block.go * Update bzl * Revert "Update receive_block.go" This reverts commit 5b4a87c512325d9f26de4db7f941dcd7303cd0d8. * Fix run time * Update go.mod * Fix AltairCompatible to account for future state version * Update proposer_execution_payload.go * Handle pre state Altair with valid payload * Handle pre state Altair with valid payload * Log bellatrix fields * Update log.go * Friendly fee recipient log * Remove extra SetOptimisticToValid * Fix base fee per gas * Fix notifypayload headroot * clean up with develop branch * Sync with devleop * Fix * Fix * fix * Fix * fix tests * revert some changes * fix tests * Update optimistic_sync_test.go * Simplify IsExecutionEnabledUsingHeader Co-authored-by: Zahoor Mohamed <zahoor@prysmaticlabs.com> Co-authored-by: Zahoor Mohamed <zahoor@zahoor.in> Co-authored-by: kasey <489222+kasey@users.noreply.github.com> Co-authored-by: Kasey Kirkham <kasey@users.noreply.github.com> Co-authored-by: Potuz <potuz@prysmaticlabs.com> Co-authored-by: Radosław Kapka <rkapka@wp.pl> Co-authored-by: Raul Jordan <raul@prysmaticlabs.com> Co-authored-by: Nishant Das <nishdas93@gmail.com> Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2022-03-25 16:03:15 +00:00
enabled, err := blocks.IsExecutionEnabledUsingHeader(postStateHeader, body)
if err != nil {
return false, errors.Wrap(err, "could not determine if execution is enabled")
}
if !enabled {
return true, nil
}
payload, err := body.ExecutionPayload()
if err != nil {
return false, errors.Wrap(err, "could not get execution payload")
}
2022-04-06 21:24:00 +00:00
lastValidHash, err := s.cfg.ExecutionEngineCaller.NewPayload(ctx, payload)
if err != nil {
switch err {
case powchain.ErrAcceptedSyncingPayloadStatus:
newPayloadOptimisticNodeCount.Inc()
log.WithFields(logrus.Fields{
2022-04-09 23:09:04 +00:00
"slot": blk.Block().Slot(),
"payloadBlockHash": fmt.Sprintf("%#x", bytesutil.Trunc(payload.BlockHash)),
}).Info("Called new payload with optimistic block")
return false, nil
2022-04-06 21:24:00 +00:00
case powchain.ErrInvalidPayloadStatus:
newPayloadInvalidNodeCount.Inc()
2022-04-06 21:24:00 +00:00
root, err := blk.Block().HashTreeRoot()
if err != nil {
return false, err
}
invalidRoots, err := s.ForkChoicer().SetOptimisticToInvalid(ctx, root, bytesutil.ToBytes32(lastValidHash))
if err != nil {
return false, err
}
if err := s.removeInvalidBlockAndState(ctx, invalidRoots); err != nil {
return false, err
}
return false, errors.New("could not validate an INVALID payload from execution engine")
default:
return false, errors.Wrap(err, "could not validate execution payload from execution engine")
}
}
newPayloadValidNodeCount.Inc()
// During the transition event, the transition block should be verified for sanity.
if blocks.IsPreBellatrixVersion(preStateVersion) {
// Handle case where pre-state is Altair but block contains payload.
// To reach here, the block must have contained a valid payload.
return true, s.validateMergeBlock(ctx, blk)
}
atTransition, err := blocks.IsMergeTransitionBlockUsingPreStatePayloadHeader(preStateHeader, body)
if err != nil {
return true, errors.Wrap(err, "could not check if merge block is terminal")
}
if !atTransition {
return true, nil
}
return true, s.validateMergeBlock(ctx, blk)
}
// optimisticCandidateBlock returns true if this block can be optimistically synced.
//
// Spec pseudocode definition:
// def is_optimistic_candidate_block(opt_store: OptimisticStore, current_slot: Slot, block: BeaconBlock) -> bool:
// if is_execution_block(opt_store.blocks[block.parent_root]):
// return True
//
// if block.slot + SAFE_SLOTS_TO_IMPORT_OPTIMISTICALLY <= current_slot:
// return True
//
// return False
func (s *Service) optimisticCandidateBlock(ctx context.Context, blk block.BeaconBlock) (bool, error) {
if blk.Slot()+params.BeaconConfig().SafeSlotsToImportOptimistically <= s.CurrentSlot() {
return true, nil
}
parent, err := s.cfg.BeaconDB.Block(ctx, bytesutil.ToBytes32(blk.ParentRoot()))
if err != nil {
return false, err
}
if parent == nil {
return false, errNilParentInDB
}
parentIsExecutionBlock, err := blocks.IsExecutionBlock(parent.Block().Body())
if err != nil {
return false, err
}
return parentIsExecutionBlock, nil
}
2022-04-06 21:24:00 +00:00
2022-04-06 23:36:52 +00:00
// getPayloadAttributes returns the payload attributes for the given state and slot.
// The attribute is required to initiate a payload build process in the context of an `engine_forkchoiceUpdated` call.
func (s *Service) getPayloadAttribute(ctx context.Context, st state.BeaconState, slot types.Slot) (bool, *enginev1.PayloadAttributes, types.ValidatorIndex, error) {
proposerID, _, ok := s.cfg.ProposerSlotIndexCache.GetProposerPayloadIDs(slot)
if !ok { // There's no need to build attribute if there is no proposer for slot.
return false, nil, 0, nil
}
// Get previous randao.
st = st.Copy()
st, err := transition.ProcessSlotsIfPossible(ctx, st, slot)
if err != nil {
return false, nil, 0, err
}
prevRando, err := helpers.RandaoMix(st, time.CurrentEpoch(st))
if err != nil {
return false, nil, 0, nil
}
// Get fee recipient.
feeRecipient := params.BeaconConfig().DefaultFeeRecipient
recipient, err := s.cfg.BeaconDB.FeeRecipientByValidatorID(ctx, proposerID)
switch {
case errors.Is(err, kv.ErrNotFoundFeeRecipient):
if feeRecipient.String() == fieldparams.EthBurnAddressHex {
logrus.WithFields(logrus.Fields{
"validatorIndex": proposerID,
"burnAddress": fieldparams.EthBurnAddressHex,
}).Error("Fee recipient not set. Using burn address")
}
case err != nil:
return false, nil, 0, errors.Wrap(err, "could not get fee recipient in db")
default:
feeRecipient = recipient
}
// Get timestamp.
t, err := slots.ToTime(uint64(s.genesisTime.Unix()), slot)
if err != nil {
return false, nil, 0, err
}
attr := &enginev1.PayloadAttributes{
Timestamp: uint64(t.Unix()),
PrevRandao: prevRando,
SuggestedFeeRecipient: feeRecipient.Bytes(),
}
return true, attr, proposerID, nil
}
2022-04-06 21:24:00 +00:00
// removeInvalidBlockAndState removes the invalid block and its corresponding state from the cache and DB.
func (s *Service) removeInvalidBlockAndState(ctx context.Context, blkRoots [][32]byte) error {
for _, root := range blkRoots {
if err := s.cfg.StateGen.DeleteStateFromCaches(ctx, root); err != nil {
return err
}
// Delete block also deletes the state as well.
if err := s.cfg.BeaconDB.DeleteBlock(ctx, root); err != nil {
// TODO(10487): If a caller requests to delete a root that's justified and finalized. We should gracefully shutdown.
// This is an irreparable condition, it would me a justified or finalized block has become invalid.
return err
}
}
return nil
}