314 lines
11 KiB
Go
Raw Normal View History

package merge
import (
"bytes"
"errors"
"fmt"
"math/big"
"github.com/holiman/uint256"
"github.com/ledgerwatch/erigon-lib/chain"
libcommon "github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon/consensus"
"github.com/ledgerwatch/erigon/consensus/aura"
"github.com/ledgerwatch/erigon/consensus/misc"
"github.com/ledgerwatch/erigon/core/state"
"github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/params"
"github.com/ledgerwatch/erigon/rpc"
"github.com/ledgerwatch/log/v3"
)
// Constants for The Merge as specified by EIP-3675: Upgrade consensus to Proof-of-Stake
var (
ProofOfStakeDifficulty = libcommon.Big0 // PoS block's difficulty is always 0
ProofOfStakeNonce = types.BlockNonce{} // PoS block's have all-zero nonces
)
var (
// errInvalidDifficulty is returned if the difficulty is non-zero.
errInvalidDifficulty = errors.New("invalid difficulty")
// errInvalidNonce is returned if the nonce is non-zero.
errInvalidNonce = errors.New("invalid nonce")
// errInvalidUncleHash is returned if a block contains an non-empty uncle list.
errInvalidUncleHash = errors.New("non empty uncle hash")
errOlderBlockTime = errors.New("timestamp older than parent")
)
// Merge Consensus Engine for the Execution Layer.
// Merge is a consensus engine that combines the eth1 consensus and proof-of-stake
// algorithm. The transition rule is described in the eth1/2 merge spec:
// https://eips.ethereum.org/EIPS/eip-3675
//
// Note: After the Merge the work is mostly done on the Consensus Layer, so nothing much is to be added on this side.
type Merge struct {
eth1Engine consensus.Engine // Original consensus engine used in eth1, e.g. ethash or clique
}
// New creates a new instance of the Merge Engine with the given embedded eth1 engine.
func New(eth1Engine consensus.Engine) *Merge {
if _, ok := eth1Engine.(*Merge); ok {
panic("nested consensus engine")
}
return &Merge{eth1Engine: eth1Engine}
}
// InnerEngine returns the embedded eth1 consensus engine.
func (s *Merge) InnerEngine() consensus.Engine {
return s.eth1Engine
}
// Type returns the type of the underlying consensus engine.
func (s *Merge) Type() chain.ConsensusName {
Merging Turbo bor into devel (#3372) * implemented bor consensus * add bor flags to default * change bucket into snapshot to clique * enable stateSync * bypass reciept checks * fix receipt calculation and bor logs * fix: contract call wrt bor * Update mumbai config * Add: bor-mainnet flag and config * Add bor consensus to integration * use header coinbase in block context * london fork mumbai changes * fix genesis error * Jaipur fork for mumbai * add sysCall to verifyHeader * added bor related rpc method implementation * added bor specific rpc extensions * fixes in snapshot implementation, major refactor for bor rpc * modify consensus specific db path for bor * fix: remove parallel compute for get root hash rpc method * Added bor-receipt flow * Use turbo-bor-lib and bor tables * Use bor table in RPC snapshot * Update README.md * Update README.md * Update README.md * Update README.md * update rpc readme * link rpc docs in readme * Update Readme * Update Readme * move erigon namespace rpc methods to eth * rm: erigon namespace * rm: erigon namespace, update list of available rpc methods, add example * fix: binary name in rpc readme * fix: max db size * Add london to bor-mainnet * updated node.go * add system req to readme * golang version fix readme * added networknames in correct place * nil * ran gofmt * erigon * fixed fake.go * dont need turbor-lib * old readme * fixing readme * half * other half * changed return * fixing return * fixed return * fixed flags * gofmt * merge with devel * latest erigon-lib * fixed context.coinbase * took out syscall * fixed params in hash * bor type now is consensus.Engine * parlia is consensus.Engine * missing arg and repeated importation * repeated importation * fixed eth_receipts.go * deleted duplicate issuance * part of consensus.Engine type * added eth_api issuance * networkname * added erigon_system file * fork struct taken out * added erigon block * getLogByHash for erigonImpl * gofmt * fixed lint * ops * gofmt * gofmt * added APIImple functions * fixed clique test * took out print * fixed state added balance * fixed README * fixed rpcDaemon README * fixed integration README * updated blockchain.go * lint * added bor back into blockchain.go * took out comment * lint * updated daemon * updated wtb * removed duplicate * removed VerifyHeaders * prevent use of wrong Transfer * fixed state_processor.go * fixed state_transition.go * fixed headers * returning err * error handling in bor read tx look up * put for txLookUp * dealing with error * lint * traces * more traces * fixed receipt in execution * getTrasanction receipt for bor or others * nil * lint * ops * deleted syscall * took out else * Merge branch 'devel * tests syscalls * changed borReceipt to receipt * reset header algos * arguments fix * took out prefixes * lint * erigon-named * borReceiptKey = blocknumber * reverts e3b60c2e159d03efcb855f7ab3da5a098dd60c33. * correct hashing tx * dont need it here * lint * added txlookup for bor * change to uint256 * outputs for isBor * wrapper * added isBor and isParlia * isBor * fixed BorTransfer * not readBody * correct prefix * added blockNum * added readStorageBody * readStorageBody * lint * got rid of unnecessary bor_receipt func * onlny if bor * use clone * append * writeToSlice * added isBor flag * fixed writeToSlice * normal sorting * lint * Reset erigon-snapshots * Move bor prefix into if Co-authored-by: Krishna Upadhyaya <krishnau1604@gmail.com> Co-authored-by: Manav Darji <manavdarji.india@gmail.com> Co-authored-by: Uttam Singh <uttamkhanduja@yahoo.in> Co-authored-by: Giulio Rebuffo <giulio.rebuffo@gmail.com> Co-authored-by: Alex Sharp <alexsharp@Alexs-MacBook-Pro.local>
2022-02-08 00:30:46 +03:00
return s.eth1Engine.Type()
}
// Author implements consensus.Engine, returning the header's coinbase as the
// proof-of-stake verified author of the block.
// This is thread-safe (only access the header.Coinbase or the underlying engine's thread-safe method)
func (s *Merge) Author(header *types.Header) (libcommon.Address, error) {
if !misc.IsPoSHeader(header) {
return s.eth1Engine.Author(header)
}
return header.Coinbase, nil
}
func (s *Merge) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error {
reached, err := IsTTDReached(chain, header.ParentHash, header.Number.Uint64()-1)
if err != nil {
return err
}
if !reached {
// Not verifying seals if the TTD is passed
return s.eth1Engine.VerifyHeader(chain, header, !chain.Config().TerminalTotalDifficultyPassed)
}
// Short circuit if the parent is not known
parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
if parent == nil {
return consensus.ErrUnknownAncestor
}
return s.verifyHeader(chain, header, parent)
}
// VerifyUncles implements consensus.Engine, always returning an error for any
// uncles as this consensus mechanism doesn't permit uncles.
func (s *Merge) VerifyUncles(chain consensus.ChainReader, header *types.Header, uncles []*types.Header) error {
if !misc.IsPoSHeader(header) {
return s.eth1Engine.VerifyUncles(chain, header, uncles)
}
if len(uncles) > 0 {
return errors.New("uncles not allowed")
}
return nil
}
// Prepare makes sure difficulty and nonce are correct
func (s *Merge) Prepare(chain consensus.ChainHeaderReader, header *types.Header, state *state.IntraBlockState) error {
reached, err := IsTTDReached(chain, header.ParentHash, header.Number.Uint64()-1)
if err != nil {
return err
}
if !reached {
Full BSC support with validator mode (#3233) * migrated consensus and chain config files for bsc support * migrated more files from bsc * fixed consensus crashing * updated erigon lib for parlia snapshot prefix * added staticpeers for bsc * [+] added system contracts [*] fixed bug with loading snapshot [+] enabled gas bailout [+] added fix to prevent syncing more than 1000 headers (for testing only) [*] fixed bug with crashing sender recover sometimes * migrated system contract calls * [*] fixed bug with returning mutable balance object [+] migrated lightclient contracts from bsc [*] fixed parlia consensus config param * [*] fixed tendermint deps * [+] added some logs * [+] enabled bsc forks [*] fixed syscalls from coinbase [*] more logging * Fix call sys contract gas calculation * [*] fixed executing system transactions * [*] enabled receipt hash, gas and bloom filter checks * [-] removed some logging scripts [*] set header checkpoint to 10 million blocks (for testing forks) * [*] fixed bug with commiting dirty inter block state state after system transaction execution [-] removed some extra logs and comments * [+] added chapel and rialto testnet support * [*] fixed chapel allocs * [-] removed 6 mil block limit for headers sync * Fix hardforks on chapel and other testnets * [*] fixed header sync issue after merge * [*] tiny code cleanup * [-] removed some comments * [*] increased mdbx map size to 4 TB * [*] increased max chaindata size to 6 tb * [*] bring more compatibility with origin erigon and some code cleanup * [+] added support of validator mode for BSC chain * [*] enable private key load for bsc, rialto and chapel chains * [*] fixed running BSC validator node * Fix the branch list * [*] tiny fixes for linter * [*] formatted imports for core and parlia packages * [*] fixed import rules in other files * Revert "[*] formatted imports for core and parlia packages" This reverts commit c764b58b34fedc2b14d69458583ba0dad114f227. * [*] changed import rules in more packages * [*] fixed type mismatch in hack command * [*] fixed crash on new epoch, enabled bootstrap flags * [*] fixed linter errors * [*] fixed missing err check for syscalls * [*] now BSC implementation is fully compatible with erigon original sources * Revert "Add chain config and CLI changes for Binance Smart Chain support (#3131)" This reverts commit 3d048b7f1a5e74ca318af96268472e2fb0262d3b. * Revert "Add Parlia consensus engine for Binance Smart Chain support (#3086)" This reverts commit ee99f17fbe0889483004f0ee113e37ad0c5c8283. * [*] fixed several issues after merge * [*] fixed integration compilation * Revert "Fix the branch list" This reverts commit 8150ca57e5f2707a84a9f6a1c5b809b7cc84547b. * [-] removed receipt repair migration * [*] fixed parlia fork numbers output * [*] bring more devel compatibility, fixed bsc address list for access list calculation * [*] fixed bug with commiting state transition for bad blocks in BSC * [*] fixed bsc changes apply for integration command and updated config print for parlia * [*] fixed bug with applying bsc forks for chapel and rialto testnet chains [*] let's use finalize and assemble for mining to let consensus know for what it's finalizing block * Fix compilation errors in hack.go * Fix lint * reset changes in erigon-snapshots to devel * Remove unrelated changes * Fix embed * Remove more unrelated changes * Remove more unrelated changes * Restore clique and aura miner config * Refactor interfaces not to use slice pointers * Refactor parlia functions to return tx and receipt instead of dealing with slices * Fix for header panic * Fix lint, restore system contract addresses * Remove more unrelated changes, unify GatherForks Co-authored-by: Dmitry Ivanov <convexman18@gmail.com> Co-authored-by: j75689 <j75689@gmail.com> Co-authored-by: Alexey Sharp <alexeysharp@Alexeys-iMac.local> Co-authored-by: Alex Sharp <alexsharp@Alexs-MacBook-Pro.local>
2022-01-14 22:06:35 +03:00
return s.eth1Engine.Prepare(chain, header, state)
}
header.Difficulty = ProofOfStakeDifficulty
header.Nonce = ProofOfStakeNonce
return nil
}
func (s *Merge) CalculateRewards(config *chain.Config, header *types.Header, uncles []*types.Header, syscall consensus.SystemCall,
) ([]consensus.Reward, error) {
_, isAura := s.eth1Engine.(*aura.AuRa)
if !misc.IsPoSHeader(header) || isAura {
return s.eth1Engine.CalculateRewards(config, header, uncles, syscall)
}
return []consensus.Reward{}, nil
}
func (s *Merge) Finalize(config *chain.Config, header *types.Header, state *state.IntraBlockState,
txs types.Transactions, uncles []*types.Header, r types.Receipts, withdrawals []*types.Withdrawal,
chain consensus.ChainHeaderReader, syscall consensus.SystemCall, logger log.Logger,
Full BSC support with validator mode (#3233) * migrated consensus and chain config files for bsc support * migrated more files from bsc * fixed consensus crashing * updated erigon lib for parlia snapshot prefix * added staticpeers for bsc * [+] added system contracts [*] fixed bug with loading snapshot [+] enabled gas bailout [+] added fix to prevent syncing more than 1000 headers (for testing only) [*] fixed bug with crashing sender recover sometimes * migrated system contract calls * [*] fixed bug with returning mutable balance object [+] migrated lightclient contracts from bsc [*] fixed parlia consensus config param * [*] fixed tendermint deps * [+] added some logs * [+] enabled bsc forks [*] fixed syscalls from coinbase [*] more logging * Fix call sys contract gas calculation * [*] fixed executing system transactions * [*] enabled receipt hash, gas and bloom filter checks * [-] removed some logging scripts [*] set header checkpoint to 10 million blocks (for testing forks) * [*] fixed bug with commiting dirty inter block state state after system transaction execution [-] removed some extra logs and comments * [+] added chapel and rialto testnet support * [*] fixed chapel allocs * [-] removed 6 mil block limit for headers sync * Fix hardforks on chapel and other testnets * [*] fixed header sync issue after merge * [*] tiny code cleanup * [-] removed some comments * [*] increased mdbx map size to 4 TB * [*] increased max chaindata size to 6 tb * [*] bring more compatibility with origin erigon and some code cleanup * [+] added support of validator mode for BSC chain * [*] enable private key load for bsc, rialto and chapel chains * [*] fixed running BSC validator node * Fix the branch list * [*] tiny fixes for linter * [*] formatted imports for core and parlia packages * [*] fixed import rules in other files * Revert "[*] formatted imports for core and parlia packages" This reverts commit c764b58b34fedc2b14d69458583ba0dad114f227. * [*] changed import rules in more packages * [*] fixed type mismatch in hack command * [*] fixed crash on new epoch, enabled bootstrap flags * [*] fixed linter errors * [*] fixed missing err check for syscalls * [*] now BSC implementation is fully compatible with erigon original sources * Revert "Add chain config and CLI changes for Binance Smart Chain support (#3131)" This reverts commit 3d048b7f1a5e74ca318af96268472e2fb0262d3b. * Revert "Add Parlia consensus engine for Binance Smart Chain support (#3086)" This reverts commit ee99f17fbe0889483004f0ee113e37ad0c5c8283. * [*] fixed several issues after merge * [*] fixed integration compilation * Revert "Fix the branch list" This reverts commit 8150ca57e5f2707a84a9f6a1c5b809b7cc84547b. * [-] removed receipt repair migration * [*] fixed parlia fork numbers output * [*] bring more devel compatibility, fixed bsc address list for access list calculation * [*] fixed bug with commiting state transition for bad blocks in BSC * [*] fixed bsc changes apply for integration command and updated config print for parlia * [*] fixed bug with applying bsc forks for chapel and rialto testnet chains [*] let's use finalize and assemble for mining to let consensus know for what it's finalizing block * Fix compilation errors in hack.go * Fix lint * reset changes in erigon-snapshots to devel * Remove unrelated changes * Fix embed * Remove more unrelated changes * Remove more unrelated changes * Restore clique and aura miner config * Refactor interfaces not to use slice pointers * Refactor parlia functions to return tx and receipt instead of dealing with slices * Fix for header panic * Fix lint, restore system contract addresses * Remove more unrelated changes, unify GatherForks Co-authored-by: Dmitry Ivanov <convexman18@gmail.com> Co-authored-by: j75689 <j75689@gmail.com> Co-authored-by: Alexey Sharp <alexeysharp@Alexeys-iMac.local> Co-authored-by: Alex Sharp <alexsharp@Alexs-MacBook-Pro.local>
2022-01-14 22:06:35 +03:00
) (types.Transactions, types.Receipts, error) {
if !misc.IsPoSHeader(header) {
return s.eth1Engine.Finalize(config, header, state, txs, uncles, r, withdrawals, chain, syscall, logger)
}
rewards, err := s.CalculateRewards(config, header, uncles, syscall)
if err != nil {
return nil, nil, err
}
for _, r := range rewards {
state.AddBalance(r.Beneficiary, &r.Amount)
}
if withdrawals != nil {
if auraEngine, ok := s.eth1Engine.(*aura.AuRa); ok {
if err := auraEngine.ExecuteSystemWithdrawals(withdrawals, syscall); err != nil {
return nil, nil, err
}
} else {
for _, w := range withdrawals {
amountInWei := new(uint256.Int).Mul(uint256.NewInt(w.Amount), uint256.NewInt(params.GWei))
state.AddBalance(w.Address, amountInWei)
}
}
}
Full BSC support with validator mode (#3233) * migrated consensus and chain config files for bsc support * migrated more files from bsc * fixed consensus crashing * updated erigon lib for parlia snapshot prefix * added staticpeers for bsc * [+] added system contracts [*] fixed bug with loading snapshot [+] enabled gas bailout [+] added fix to prevent syncing more than 1000 headers (for testing only) [*] fixed bug with crashing sender recover sometimes * migrated system contract calls * [*] fixed bug with returning mutable balance object [+] migrated lightclient contracts from bsc [*] fixed parlia consensus config param * [*] fixed tendermint deps * [+] added some logs * [+] enabled bsc forks [*] fixed syscalls from coinbase [*] more logging * Fix call sys contract gas calculation * [*] fixed executing system transactions * [*] enabled receipt hash, gas and bloom filter checks * [-] removed some logging scripts [*] set header checkpoint to 10 million blocks (for testing forks) * [*] fixed bug with commiting dirty inter block state state after system transaction execution [-] removed some extra logs and comments * [+] added chapel and rialto testnet support * [*] fixed chapel allocs * [-] removed 6 mil block limit for headers sync * Fix hardforks on chapel and other testnets * [*] fixed header sync issue after merge * [*] tiny code cleanup * [-] removed some comments * [*] increased mdbx map size to 4 TB * [*] increased max chaindata size to 6 tb * [*] bring more compatibility with origin erigon and some code cleanup * [+] added support of validator mode for BSC chain * [*] enable private key load for bsc, rialto and chapel chains * [*] fixed running BSC validator node * Fix the branch list * [*] tiny fixes for linter * [*] formatted imports for core and parlia packages * [*] fixed import rules in other files * Revert "[*] formatted imports for core and parlia packages" This reverts commit c764b58b34fedc2b14d69458583ba0dad114f227. * [*] changed import rules in more packages * [*] fixed type mismatch in hack command * [*] fixed crash on new epoch, enabled bootstrap flags * [*] fixed linter errors * [*] fixed missing err check for syscalls * [*] now BSC implementation is fully compatible with erigon original sources * Revert "Add chain config and CLI changes for Binance Smart Chain support (#3131)" This reverts commit 3d048b7f1a5e74ca318af96268472e2fb0262d3b. * Revert "Add Parlia consensus engine for Binance Smart Chain support (#3086)" This reverts commit ee99f17fbe0889483004f0ee113e37ad0c5c8283. * [*] fixed several issues after merge * [*] fixed integration compilation * Revert "Fix the branch list" This reverts commit 8150ca57e5f2707a84a9f6a1c5b809b7cc84547b. * [-] removed receipt repair migration * [*] fixed parlia fork numbers output * [*] bring more devel compatibility, fixed bsc address list for access list calculation * [*] fixed bug with commiting state transition for bad blocks in BSC * [*] fixed bsc changes apply for integration command and updated config print for parlia * [*] fixed bug with applying bsc forks for chapel and rialto testnet chains [*] let's use finalize and assemble for mining to let consensus know for what it's finalizing block * Fix compilation errors in hack.go * Fix lint * reset changes in erigon-snapshots to devel * Remove unrelated changes * Fix embed * Remove more unrelated changes * Remove more unrelated changes * Restore clique and aura miner config * Refactor interfaces not to use slice pointers * Refactor parlia functions to return tx and receipt instead of dealing with slices * Fix for header panic * Fix lint, restore system contract addresses * Remove more unrelated changes, unify GatherForks Co-authored-by: Dmitry Ivanov <convexman18@gmail.com> Co-authored-by: j75689 <j75689@gmail.com> Co-authored-by: Alexey Sharp <alexeysharp@Alexeys-iMac.local> Co-authored-by: Alex Sharp <alexsharp@Alexs-MacBook-Pro.local>
2022-01-14 22:06:35 +03:00
return txs, r, nil
}
func (s *Merge) FinalizeAndAssemble(config *chain.Config, header *types.Header, state *state.IntraBlockState,
txs types.Transactions, uncles []*types.Header, receipts types.Receipts, withdrawals []*types.Withdrawal,
chain consensus.ChainHeaderReader, syscall consensus.SystemCall, call consensus.Call, logger log.Logger,
Full BSC support with validator mode (#3233) * migrated consensus and chain config files for bsc support * migrated more files from bsc * fixed consensus crashing * updated erigon lib for parlia snapshot prefix * added staticpeers for bsc * [+] added system contracts [*] fixed bug with loading snapshot [+] enabled gas bailout [+] added fix to prevent syncing more than 1000 headers (for testing only) [*] fixed bug with crashing sender recover sometimes * migrated system contract calls * [*] fixed bug with returning mutable balance object [+] migrated lightclient contracts from bsc [*] fixed parlia consensus config param * [*] fixed tendermint deps * [+] added some logs * [+] enabled bsc forks [*] fixed syscalls from coinbase [*] more logging * Fix call sys contract gas calculation * [*] fixed executing system transactions * [*] enabled receipt hash, gas and bloom filter checks * [-] removed some logging scripts [*] set header checkpoint to 10 million blocks (for testing forks) * [*] fixed bug with commiting dirty inter block state state after system transaction execution [-] removed some extra logs and comments * [+] added chapel and rialto testnet support * [*] fixed chapel allocs * [-] removed 6 mil block limit for headers sync * Fix hardforks on chapel and other testnets * [*] fixed header sync issue after merge * [*] tiny code cleanup * [-] removed some comments * [*] increased mdbx map size to 4 TB * [*] increased max chaindata size to 6 tb * [*] bring more compatibility with origin erigon and some code cleanup * [+] added support of validator mode for BSC chain * [*] enable private key load for bsc, rialto and chapel chains * [*] fixed running BSC validator node * Fix the branch list * [*] tiny fixes for linter * [*] formatted imports for core and parlia packages * [*] fixed import rules in other files * Revert "[*] formatted imports for core and parlia packages" This reverts commit c764b58b34fedc2b14d69458583ba0dad114f227. * [*] changed import rules in more packages * [*] fixed type mismatch in hack command * [*] fixed crash on new epoch, enabled bootstrap flags * [*] fixed linter errors * [*] fixed missing err check for syscalls * [*] now BSC implementation is fully compatible with erigon original sources * Revert "Add chain config and CLI changes for Binance Smart Chain support (#3131)" This reverts commit 3d048b7f1a5e74ca318af96268472e2fb0262d3b. * Revert "Add Parlia consensus engine for Binance Smart Chain support (#3086)" This reverts commit ee99f17fbe0889483004f0ee113e37ad0c5c8283. * [*] fixed several issues after merge * [*] fixed integration compilation * Revert "Fix the branch list" This reverts commit 8150ca57e5f2707a84a9f6a1c5b809b7cc84547b. * [-] removed receipt repair migration * [*] fixed parlia fork numbers output * [*] bring more devel compatibility, fixed bsc address list for access list calculation * [*] fixed bug with commiting state transition for bad blocks in BSC * [*] fixed bsc changes apply for integration command and updated config print for parlia * [*] fixed bug with applying bsc forks for chapel and rialto testnet chains [*] let's use finalize and assemble for mining to let consensus know for what it's finalizing block * Fix compilation errors in hack.go * Fix lint * reset changes in erigon-snapshots to devel * Remove unrelated changes * Fix embed * Remove more unrelated changes * Remove more unrelated changes * Restore clique and aura miner config * Refactor interfaces not to use slice pointers * Refactor parlia functions to return tx and receipt instead of dealing with slices * Fix for header panic * Fix lint, restore system contract addresses * Remove more unrelated changes, unify GatherForks Co-authored-by: Dmitry Ivanov <convexman18@gmail.com> Co-authored-by: j75689 <j75689@gmail.com> Co-authored-by: Alexey Sharp <alexeysharp@Alexeys-iMac.local> Co-authored-by: Alex Sharp <alexsharp@Alexs-MacBook-Pro.local>
2022-01-14 22:06:35 +03:00
) (*types.Block, types.Transactions, types.Receipts, error) {
if !misc.IsPoSHeader(header) {
return s.eth1Engine.FinalizeAndAssemble(config, header, state, txs, uncles, receipts, withdrawals, chain, syscall, call, logger)
}
outTxs, outReceipts, err := s.Finalize(config, header, state, txs, uncles, receipts, withdrawals, chain, syscall, logger)
if err != nil {
return nil, nil, nil, err
}
return types.NewBlock(header, outTxs, uncles, outReceipts, withdrawals), outTxs, outReceipts, nil
}
func (s *Merge) SealHash(header *types.Header) (hash libcommon.Hash) {
return s.eth1Engine.SealHash(header)
}
func (s *Merge) CalcDifficulty(chain consensus.ChainHeaderReader, time, parentTime uint64, parentDifficulty *big.Int, parentNumber uint64, parentHash, parentUncleHash libcommon.Hash, parentAuRaStep uint64) *big.Int {
reached, err := IsTTDReached(chain, parentHash, parentNumber)
if err != nil {
return nil
}
if !reached {
return s.eth1Engine.CalcDifficulty(chain, time, parentTime, parentDifficulty, parentNumber, parentHash, parentUncleHash, parentAuRaStep)
}
return ProofOfStakeDifficulty
}
// verifyHeader checks whether a Proof-of-Stake header conforms to the consensus rules of the
// stock Ethereum consensus engine with EIP-3675 modifications.
func (s *Merge) verifyHeader(chain consensus.ChainHeaderReader, header, parent *types.Header) error {
if uint64(len(header.Extra)) > params.MaximumExtraDataSize {
return fmt.Errorf("extra-data longer than %d bytes (%d)", params.MaximumExtraDataSize, len(header.Extra))
}
if header.Time <= parent.Time {
return errOlderBlockTime
}
if header.Difficulty.Cmp(ProofOfStakeDifficulty) != 0 {
return errInvalidDifficulty
}
if !bytes.Equal(header.Nonce[:], ProofOfStakeNonce[:]) {
return errInvalidNonce
}
// Verify that the gas limit is within cap
if header.GasLimit > params.MaxGasLimit {
return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, params.MaxGasLimit)
}
// Verify that the gasUsed is <= gasLimit
if header.GasUsed > header.GasLimit {
return fmt.Errorf("invalid gasUsed: have %d, gasLimit %d", header.GasUsed, header.GasLimit)
}
// Verify that the block number is parent's +1
if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(libcommon.Big1) != 0 {
return consensus.ErrInvalidNumber
}
if header.UncleHash != types.EmptyUncleHash {
return errInvalidUncleHash
}
if err := misc.VerifyEip1559Header(chain.Config(), parent, header, false); err != nil {
return err
}
// Verify existence / non-existence of withdrawalsHash
shanghai := chain.Config().IsShanghai(header.Time)
if shanghai && header.WithdrawalsHash == nil {
return fmt.Errorf("missing withdrawalsHash")
}
if !shanghai && header.WithdrawalsHash != nil {
return consensus.ErrUnexpectedWithdrawals
}
cancun := chain.Config().IsCancun(header.Time)
if !cancun {
if header.BlobGasUsed != nil {
return fmt.Errorf("invalid blobGasUsed before fork: have %v, expected 'nil'", header.BlobGasUsed)
}
if header.ExcessBlobGas != nil {
return fmt.Errorf("invalid excessBlobGas before fork: have %v, expected 'nil'", header.ExcessBlobGas)
}
}
if cancun {
if err := misc.VerifyEip4844Header(chain.Config(), parent, header); err != nil {
// Verify the header's EIP-4844 attributes.
return err
}
if header.ParentBeaconBlockRoot == nil {
return fmt.Errorf("missing parentBeaconBlockRoot")
}
if header.ParentBeaconBlockRoot != chain.CurrentHeader().ParentBeaconBlockRoot {
return fmt.Errorf("parentBeaconBlockRoot mismatch")
}
}
return nil
}
func (s *Merge) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
if !misc.IsPoSHeader(block.Header()) {
return s.eth1Engine.Seal(chain, block, results, stop)
}
return nil
}
func (s *Merge) GenerateSeal(chain consensus.ChainHeaderReader, currnt, parent *types.Header, call consensus.Call) []byte {
return nil
}
func (s *Merge) IsServiceTransaction(sender libcommon.Address, syscall consensus.SystemCall) bool {
return s.eth1Engine.IsServiceTransaction(sender, syscall)
}
func (s *Merge) Initialize(config *chain.Config, chain consensus.ChainHeaderReader, header *types.Header, state *state.IntraBlockState, txs []types.Transaction, uncles []*types.Header, syscall consensus.SysCallCustom) {
s.eth1Engine.Initialize(config, chain, header, state, txs, uncles, syscall)
if chain.Config().IsCancun(header.Time) {
misc.ApplyBeaconRootEip4788(chain, header, state)
}
}
func (s *Merge) APIs(chain consensus.ChainHeaderReader) []rpc.API {
return s.eth1Engine.APIs(chain)
}
func (s *Merge) Close() error {
return s.eth1Engine.Close()
}
// IsTTDReached checks if the TotalTerminalDifficulty has been surpassed on the `parentHash` block.
// It depends on the parentHash already being stored in the database.
// If the total difficulty is not stored in the database a ErrUnknownAncestorTD error is returned.
func IsTTDReached(chain consensus.ChainHeaderReader, parentHash libcommon.Hash, number uint64) (bool, error) {
if chain.Config().TerminalTotalDifficulty == nil {
return false, nil
}
td := chain.GetTd(parentHash, number)
if td == nil {
return false, consensus.ErrUnknownAncestorTD
}
return td.Cmp(chain.Config().TerminalTotalDifficulty) >= 0, nil
}