merge shanghai tests

This commit is contained in:
Arpit Temani 2023-10-16 23:23:13 +05:30
commit 48f6200449
37 changed files with 910 additions and 819 deletions

File diff suppressed because one or more lines are too long

View file

@ -156,7 +156,7 @@ func Transaction(ctx *cli.Context) error {
}
// Check intrinsic gas
if gas, err := core.IntrinsicGas(tx.Data(), tx.AccessList(), tx.To() == nil,
chainConfig.IsHomestead(new(big.Int)), chainConfig.IsIstanbul(new(big.Int)), chainConfig.IsShanghai(new(big.Int), 0)); err != nil {
chainConfig.IsHomestead(new(big.Int)), chainConfig.IsIstanbul(new(big.Int)), chainConfig.IsShanghai(new(big.Int))); err != nil {
r.Error = err
results = append(results, r)
@ -189,9 +189,8 @@ func Transaction(ctx *cli.Context) error {
case new(big.Int).Mul(tx.GasFeeCap(), new(big.Int).SetUint64(tx.Gas())).BitLen() > 256:
r.Error = errors.New("gas * maxFeePerGas exceeds 256 bits")
}
// TODO marcello double check
// Check whether the init code size has been exceeded.
if chainConfig.IsShanghai(new(big.Int), 0) && tx.To() == nil && len(tx.Data()) > params.MaxInitCodeSize {
if chainConfig.IsShanghai(new(big.Int)) && tx.To() == nil && len(tx.Data()) > params.MaxInitCodeSize {
r.Error = errors.New("max initcode size exceeded")
}

View file

@ -285,7 +285,8 @@ func Transition(ctx *cli.Context) error {
return NewError(ErrorConfig, errors.New("EIP-1559 config but missing 'currentBaseFee' in env section"))
}
}
if chainConfig.IsShanghai(big.NewInt(int64(prestate.Env.Number)), prestate.Env.Timestamp) && prestate.Env.Withdrawals == nil {
if chainConfig.IsShanghai(big.NewInt(int64(prestate.Env.Number))) && prestate.Env.Withdrawals == nil {
return NewError(ErrorConfig, errors.New("Shanghai config but missing 'withdrawals' in env section"))
}

View file

@ -238,7 +238,6 @@ func TestT8n(t *testing.T) {
output: t8nOutput{result: true},
expOut: "exp.json",
},
// TODO marcello double check
{ // Test post-merge transition
base: "./testdata/24",
input: t8nInput{

View file

@ -18,6 +18,7 @@ package main
import (
"fmt"
"math/big"
"os"
"time"
@ -156,12 +157,12 @@ func makeConfigNode(ctx *cli.Context) (*node.Node, gethConfig) {
func makeFullNode(ctx *cli.Context) (*node.Node, ethapi.Backend) {
stack, cfg := makeConfigNode(ctx)
if ctx.IsSet(utils.OverrideCancun.Name) {
v := ctx.Uint64(utils.OverrideCancun.Name)
cfg.Eth.OverrideCancun = &v
v := ctx.Int64(utils.OverrideCancun.Name)
cfg.Eth.OverrideCancun = new(big.Int).SetInt64(v)
}
if ctx.IsSet(utils.OverrideVerkle.Name) {
v := ctx.Uint64(utils.OverrideVerkle.Name)
cfg.Eth.OverrideVerkle = &v
v := ctx.Int64(utils.OverrideVerkle.Name)
cfg.Eth.OverrideVerkle = new(big.Int).SetInt64(v)
}
backend, eth := utils.RegisterEthService(stack, &cfg.Eth)

View file

@ -263,7 +263,7 @@ func (beacon *Beacon) verifyHeader(chain consensus.ChainHeaderReader, header, pa
return err
}
// Verify existence / non-existence of withdrawalsHash.
shanghai := chain.Config().IsShanghai(header.Number, header.Time)
shanghai := chain.Config().IsShanghai(header.Number)
if shanghai && header.WithdrawalsHash == nil {
return errors.New("missing withdrawalsHash")
}
@ -271,7 +271,7 @@ func (beacon *Beacon) verifyHeader(chain consensus.ChainHeaderReader, header, pa
return fmt.Errorf("invalid withdrawalsHash: have %x, expected nil", header.WithdrawalsHash)
}
// Verify the existence / non-existence of excessBlobGas
cancun := chain.Config().IsCancun(header.Number, header.Time)
cancun := chain.Config().IsCancun(header.Number)
if !cancun && header.ExcessBlobGas != nil {
return fmt.Errorf("invalid excessBlobGas: have %d, expected nil", header.ExcessBlobGas)
}
@ -363,7 +363,8 @@ func (beacon *Beacon) FinalizeAndAssemble(ctx context.Context, chain consensus.C
if !beacon.IsPoSHeader(header) {
return beacon.ethone.FinalizeAndAssemble(ctx, chain, header, state, txs, uncles, receipts, nil)
}
shanghai := chain.Config().IsShanghai(header.Number, header.Time)
shanghai := chain.Config().IsShanghai(header.Number)
if shanghai {
// All blocks after Shanghai must include a withdrawals root.
if withdrawals == nil {

View file

@ -889,6 +889,10 @@ func (c *Bor) FinalizeAndAssemble(ctx context.Context, chain consensus.ChainHead
finalizeCtx, finalizeSpan := tracing.StartSpan(ctx, "bor.FinalizeAndAssemble")
defer tracing.EndSpan(finalizeSpan)
if len(withdrawals) > 0 {
return nil, errors.New("Bor does not support withdrawals")
}
stateSyncData := []*types.StateSyncData{}
headerNumber := header.Number.Uint64()

View file

@ -309,10 +309,12 @@ func (c *Clique) verifyHeader(chain consensus.ChainHeaderReader, header *types.H
if header.GasLimit > params.MaxGasLimit {
return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, params.MaxGasLimit)
}
if chain.Config().IsShanghai(header.Number, header.Time) {
if chain.Config().IsShanghai(header.Number) {
return errors.New("clique does not support shanghai fork")
}
if chain.Config().IsCancun(header.Number, header.Time) {
if chain.Config().IsCancun(header.Number) {
return errors.New("clique does not support cancun fork")
}
// All basic checks passed, verify cascading fields

View file

@ -264,10 +264,12 @@ func (ethash *Ethash) verifyHeader(chain consensus.ChainHeaderReader, header, pa
if diff := new(big.Int).Sub(header.Number, parent.Number); diff.Cmp(big.NewInt(1)) != 0 {
return consensus.ErrInvalidNumber
}
if chain.Config().IsShanghai(header.Number, header.Time) {
if chain.Config().IsShanghai(header.Number) {
return errors.New("ethash does not support shanghai fork")
}
if chain.Config().IsCancun(header.Number, header.Time) {
if chain.Config().IsCancun(header.Number) {
return errors.New("ethash does not support cancun fork")
}
// Add some fake checks for tests

View file

@ -4671,7 +4671,7 @@ func TestEIP3651(t *testing.T) {
gspec.Config.LondonBlock = common.Big0
gspec.Config.TerminalTotalDifficulty = common.Big0
gspec.Config.TerminalTotalDifficultyPassed = true
gspec.Config.ShanghaiTime = u64(0)
gspec.Config.ShanghaiBlock = common.Big0
signer := types.LatestSigner(gspec.Config)
_, blocks, _ := GenerateChainWithGenesis(gspec, engine, 1, func(i int, b *BlockGen) {

View file

@ -56,7 +56,7 @@ func TestGenerateWithdrawalChain(t *testing.T) {
config.TerminalTotalDifficultyPassed = true
config.TerminalTotalDifficulty = common.Big0
config.ShanghaiTime = u64(0)
config.ShanghaiBlock = common.Big0
// init 0xaa with some storage elements
storage := make(map[common.Hash]common.Hash)

View file

@ -45,34 +45,30 @@ func TestCreation(t *testing.T) {
params.MainnetChainConfig,
params.MainnetGenesisHash,
[]testcase{
{0, 0, ID{Hash: checksumToBytes(0xfc64ec04), Next: 1150000}}, // Unsynced
{1149999, 0, ID{Hash: checksumToBytes(0xfc64ec04), Next: 1150000}}, // Last Frontier block
{1150000, 0, ID{Hash: checksumToBytes(0x97c2c34c), Next: 1920000}}, // First Homestead block
{1919999, 0, ID{Hash: checksumToBytes(0x97c2c34c), Next: 1920000}}, // Last Homestead block
{1920000, 0, ID{Hash: checksumToBytes(0x91d1f948), Next: 2463000}}, // First DAO block
{2462999, 0, ID{Hash: checksumToBytes(0x91d1f948), Next: 2463000}}, // Last DAO block
{2463000, 0, ID{Hash: checksumToBytes(0x7a64da13), Next: 2675000}}, // First Tangerine block
{2674999, 0, ID{Hash: checksumToBytes(0x7a64da13), Next: 2675000}}, // Last Tangerine block
{2675000, 0, ID{Hash: checksumToBytes(0x3edd5b10), Next: 4370000}}, // First Spurious block
{4369999, 0, ID{Hash: checksumToBytes(0x3edd5b10), Next: 4370000}}, // Last Spurious block
{4370000, 0, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}}, // First Byzantium block
{7279999, 0, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}}, // Last Byzantium block
{7280000, 0, ID{Hash: checksumToBytes(0x668db0af), Next: 9069000}}, // First and last Constantinople, first Petersburg block
{9068999, 0, ID{Hash: checksumToBytes(0x668db0af), Next: 9069000}}, // Last Petersburg block
{9069000, 0, ID{Hash: checksumToBytes(0x879d6e30), Next: 9200000}}, // First Istanbul and first Muir Glacier block
{9199999, 0, ID{Hash: checksumToBytes(0x879d6e30), Next: 9200000}}, // Last Istanbul and first Muir Glacier block
{9200000, 0, ID{Hash: checksumToBytes(0xe029e991), Next: 12244000}}, // First Muir Glacier block
{12243999, 0, ID{Hash: checksumToBytes(0xe029e991), Next: 12244000}}, // Last Muir Glacier block
{12244000, 0, ID{Hash: checksumToBytes(0x0eb440f6), Next: 12965000}}, // First Berlin block
{12964999, 0, ID{Hash: checksumToBytes(0x0eb440f6), Next: 12965000}}, // Last Berlin block
{12965000, 0, ID{Hash: checksumToBytes(0xb715077d), Next: 13773000}}, // First London block
{13772999, 0, ID{Hash: checksumToBytes(0xb715077d), Next: 13773000}}, // Last London block
{13773000, 0, ID{Hash: checksumToBytes(0x20c327fc), Next: 15050000}}, // First Arrow Glacier block
{15049999, 0, ID{Hash: checksumToBytes(0x20c327fc), Next: 15050000}}, // Last Arrow Glacier block
{15050000, 0, ID{Hash: checksumToBytes(0xf0afd0e3), Next: 1681338455}}, // First Gray Glacier block
{20000000, 1681338454, ID{Hash: checksumToBytes(0xf0afd0e3), Next: 1681338455}}, // Last Gray Glacier block
{20000000, 1681338455, ID{Hash: checksumToBytes(0xdce96c2d), Next: 0}}, // First Shanghai block
{30000000, 2000000000, ID{Hash: checksumToBytes(0xdce96c2d), Next: 0}}, // Future Shanghai block
{0, 0, ID{Hash: checksumToBytes(0xfc64ec04), Next: 1150000}}, // Unsynced
{1149999, 0, ID{Hash: checksumToBytes(0xfc64ec04), Next: 1150000}}, // Last Frontier block
{1150000, 0, ID{Hash: checksumToBytes(0x97c2c34c), Next: 1920000}}, // First Homestead block
{1919999, 0, ID{Hash: checksumToBytes(0x97c2c34c), Next: 1920000}}, // Last Homestead block
{1920000, 0, ID{Hash: checksumToBytes(0x91d1f948), Next: 2463000}}, // First DAO block
{2462999, 0, ID{Hash: checksumToBytes(0x91d1f948), Next: 2463000}}, // Last DAO block
{2463000, 0, ID{Hash: checksumToBytes(0x7a64da13), Next: 2675000}}, // First Tangerine block
{2674999, 0, ID{Hash: checksumToBytes(0x7a64da13), Next: 2675000}}, // Last Tangerine block
{2675000, 0, ID{Hash: checksumToBytes(0x3edd5b10), Next: 4370000}}, // First Spurious block
{4369999, 0, ID{Hash: checksumToBytes(0x3edd5b10), Next: 4370000}}, // Last Spurious block
{4370000, 0, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}}, // First Byzantium block
{7279999, 0, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}}, // Last Byzantium block
{7280000, 0, ID{Hash: checksumToBytes(0x668db0af), Next: 9069000}}, // First and last Constantinople, first Petersburg block
{9068999, 0, ID{Hash: checksumToBytes(0x668db0af), Next: 9069000}}, // Last Petersburg block
{9069000, 0, ID{Hash: checksumToBytes(0x879d6e30), Next: 9200000}}, // First Istanbul and first Muir Glacier block
{9199999, 0, ID{Hash: checksumToBytes(0x879d6e30), Next: 9200000}}, // Last Istanbul and first Muir Glacier block
{9200000, 0, ID{Hash: checksumToBytes(0xe029e991), Next: 12244000}}, // First Muir Glacier block
{12243999, 0, ID{Hash: checksumToBytes(0xe029e991), Next: 12244000}}, // Last Muir Glacier block
{12244000, 0, ID{Hash: checksumToBytes(0x0eb440f6), Next: 12965000}}, // First Berlin block
{12964999, 0, ID{Hash: checksumToBytes(0x0eb440f6), Next: 12965000}}, // Last Berlin block
{12965000, 0, ID{Hash: checksumToBytes(0xb715077d), Next: 13773000}}, // First London block
{13772999, 0, ID{Hash: checksumToBytes(0xb715077d), Next: 13773000}}, // Last London block
{13773000, 0, ID{Hash: checksumToBytes(0x20c327fc), Next: 15050000}}, // First Arrow Glacier block
{15049999, 0, ID{Hash: checksumToBytes(0x20c327fc), Next: 15050000}}, // Last Arrow Glacier block
},
},
// Goerli test cases
@ -80,16 +76,12 @@ func TestCreation(t *testing.T) {
params.GoerliChainConfig,
params.GoerliGenesisHash,
[]testcase{
{0, 0, ID{Hash: checksumToBytes(0xa3f5ab08), Next: 1561651}}, // Unsynced, last Frontier, Homestead, Tangerine, Spurious, Byzantium, Constantinople and first Petersburg block
{1561650, 0, ID{Hash: checksumToBytes(0xa3f5ab08), Next: 1561651}}, // Last Petersburg block
{1561651, 0, ID{Hash: checksumToBytes(0xc25efa5c), Next: 4460644}}, // First Istanbul block
{4460643, 0, ID{Hash: checksumToBytes(0xc25efa5c), Next: 4460644}}, // Last Istanbul block
{4460644, 0, ID{Hash: checksumToBytes(0x757a1c47), Next: 5062605}}, // First Berlin block
{5000000, 0, ID{Hash: checksumToBytes(0x757a1c47), Next: 5062605}}, // Last Berlin block
{5062605, 0, ID{Hash: checksumToBytes(0xB8C6299D), Next: 1678832736}}, // First London block
{6000000, 1678832735, ID{Hash: checksumToBytes(0xB8C6299D), Next: 1678832736}}, // Last London block
{6000001, 1678832736, ID{Hash: checksumToBytes(0xf9843abf), Next: 0}}, // First Shanghai block
{6500000, 2678832736, ID{Hash: checksumToBytes(0xf9843abf), Next: 0}}, // Future Shanghai block
{0, 0, ID{Hash: checksumToBytes(0xa3f5ab08), Next: 1561651}}, // Unsynced, last Frontier, Homestead, Tangerine, Spurious, Byzantium, Constantinople and first Petersburg block
{1561650, 0, ID{Hash: checksumToBytes(0xa3f5ab08), Next: 1561651}}, // Last Petersburg block
{1561651, 0, ID{Hash: checksumToBytes(0xc25efa5c), Next: 4460644}}, // First Istanbul block
{4460643, 0, ID{Hash: checksumToBytes(0xc25efa5c), Next: 4460644}}, // Last Istanbul block
{4460644, 0, ID{Hash: checksumToBytes(0x757a1c47), Next: 5062605}}, // First Berlin block
{5000000, 0, ID{Hash: checksumToBytes(0x757a1c47), Next: 5062605}}, // Last Berlin block
},
},
// Sepolia test cases
@ -97,11 +89,8 @@ func TestCreation(t *testing.T) {
params.SepoliaChainConfig,
params.SepoliaGenesisHash,
[]testcase{
{0, 0, ID{Hash: checksumToBytes(0xfe3366e7), Next: 1735371}}, // Unsynced, last Frontier, Homestead, Tangerine, Spurious, Byzantium, Constantinople, Petersburg, Istanbul, Berlin and first London block
{1735370, 0, ID{Hash: checksumToBytes(0xfe3366e7), Next: 1735371}}, // Last London block
{1735371, 0, ID{Hash: checksumToBytes(0xb96cbd13), Next: 1677557088}}, // First MergeNetsplit block
{1735372, 1677557087, ID{Hash: checksumToBytes(0xb96cbd13), Next: 1677557088}}, // Last MergeNetsplit block
{1735372, 1677557088, ID{Hash: checksumToBytes(0xf7f9bc08), Next: 0}}, // First Shanghai block
{0, 0, ID{Hash: checksumToBytes(0xfe3366e7), Next: 1735371}}, // Unsynced, last Frontier, Homestead, Tangerine, Spurious, Byzantium, Constantinople, Petersburg, Istanbul, Berlin and first London block
{1735370, 0, ID{Hash: checksumToBytes(0xfe3366e7), Next: 1735371}}, // Last London block
},
},
}
@ -119,7 +108,7 @@ func TestCreation(t *testing.T) {
func TestValidation(t *testing.T) {
// Config that has not timestamp enabled
legacyConfig := *params.MainnetChainConfig
legacyConfig.ShanghaiTime = nil
legacyConfig.ShanghaiBlock = nil
tests := []struct {
config *params.ChainConfig
@ -221,29 +210,14 @@ func TestValidation(t *testing.T) {
// neither forks passed at neither nodes, they may mismatch, but we still connect for now.
{params.MainnetChainConfig, 15050000, 0, ID{Hash: checksumToBytes(0xf0afd0e3), Next: math.MaxUint64}, nil},
// Local is mainnet exactly on Shanghai, remote announces Gray Glacier + knowledge about Shanghai. Remote
// is simply out of sync, accept.
{params.MainnetChainConfig, 20000000, 1681338455, ID{Hash: checksumToBytes(0xf0afd0e3), Next: 1681338455}, nil},
// Local is mainnet Shanghai, remote announces Gray Glacier + knowledge about Shanghai. Remote
// is simply out of sync, accept.
{params.MainnetChainConfig, 20123456, 1681338456, ID{Hash: checksumToBytes(0xf0afd0e3), Next: 1681338455}, nil},
// Local is mainnet Shanghai, remote announces Arrow Glacier + knowledge about Gray Glacier. Remote
// is definitely out of sync. It may or may not need the Shanghai update, we don't know yet.
{params.MainnetChainConfig, 20000000, 1681338455, ID{Hash: checksumToBytes(0x20c327fc), Next: 15050000}, nil},
// Local is mainnet Gray Glacier, remote announces Shanghai. Local is out of sync, accept.
{params.MainnetChainConfig, 15050000, 0, ID{Hash: checksumToBytes(0xdce96c2d), Next: 0}, nil},
// Local is mainnet Arrow Glacier, remote announces Gray Glacier, but is not aware of Shanghai. Local
// out of sync. Local also knows about a future fork, but that is uncertain yet.
{params.MainnetChainConfig, 13773000, 0, ID{Hash: checksumToBytes(0xf0afd0e3), Next: 0}, nil},
// Local is mainnet Shanghai. remote announces Gray Glacier but is not aware of further forks.
// Remote needs software update.
{params.MainnetChainConfig, 20000000, 1681338455, ID{Hash: checksumToBytes(0xf0afd0e3), Next: 0}, ErrRemoteStale},
// Local is mainnet Gray Glacier, and isn't aware of more forks. Remote announces Gray Glacier +
// 0xffffffff. Local needs software update, reject.
{params.MainnetChainConfig, 15050000, 0, ID{Hash: checksumToBytes(checksumUpdate(0xf0afd0e3, math.MaxUint64)), Next: 0}, ErrLocalIncompatibleOrStale},
@ -266,13 +240,6 @@ func TestValidation(t *testing.T) {
// Timestamp based tests
//----------------------
// Local is mainnet Shanghai, remote announces the same. No future fork is announced.
{params.MainnetChainConfig, 20000000, 1681338455, ID{Hash: checksumToBytes(0xdce96c2d), Next: 0}, nil},
// Local is mainnet Shanghai, remote announces the same. Remote also announces a next fork
// at time 0xffffffff, but that is uncertain.
{params.MainnetChainConfig, 20000000, 1681338455, ID{Hash: checksumToBytes(0xdce96c2d), Next: math.MaxUint64}, nil},
// Local is mainnet currently in Shanghai only (so it's aware of Cancun), remote announces
// also Shanghai, but it's not yet aware of Cancun (e.g. non updated node before the fork).
// In this case we don't know if Cancun passed yet or not.

View file

@ -300,8 +300,8 @@ func (e *GenesisMismatchError) Error() string {
// ChainOverrides contains the changes to chain config.
type ChainOverrides struct {
OverrideCancun *uint64
OverrideVerkle *uint64
OverrideCancun *big.Int
OverrideVerkle *big.Int
}
// SetupGenesisBlock writes or updates the genesis block in db.
@ -330,10 +330,10 @@ func SetupGenesisBlockWithOverride(db ethdb.Database, triedb *trie.Database, gen
applyOverrides := func(config *params.ChainConfig) {
if config != nil {
if overrides != nil && overrides.OverrideCancun != nil {
config.CancunTime = overrides.OverrideCancun
config.CancunBlock = overrides.OverrideCancun
}
if overrides != nil && overrides.OverrideVerkle != nil {
config.VerkleTime = overrides.OverrideVerkle
config.VerkleBlock = overrides.OverrideVerkle
}
}
}
@ -526,11 +526,11 @@ func (g *Genesis) ToBlock() *types.Block {
var withdrawals []*types.Withdrawal
if conf := g.Config; conf != nil {
num := big.NewInt(int64(g.Number))
if conf.IsShanghai(num, g.Timestamp) {
if conf.IsShanghai(num) {
head.WithdrawalsHash = &types.EmptyWithdrawalsHash
withdrawals = make([]*types.Withdrawal, 0)
}
if conf.IsCancun(num, g.Timestamp) {
if conf.IsCancun(num) {
head.ExcessBlobGas = g.ExcessBlobGas
head.BlobGasUsed = g.BlobGasUsed
if head.ExcessBlobGas == nil {

View file

@ -1798,7 +1798,6 @@ func (s *StateDB) Prepare(rules params.Rules, sender, coinbase common.Address, d
al.AddSlot(el.Address, key)
}
}
// TODO marcello double check
if rules.IsShanghai { // EIP-3651: warm coinbase
al.AddAddress(coinbase)
}

View file

@ -103,7 +103,7 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
}
// Fail if Shanghai not enabled and len(withdrawals) is non-zero.
withdrawals := block.Withdrawals()
if len(withdrawals) > 0 && !p.config.IsShanghai(block.Number(), block.Time()) {
if len(withdrawals) > 0 && !p.config.IsShanghai(block.Number()) {
return nil, nil, 0, errors.New("withdrawals before shanghai")
}
// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)

View file

@ -63,8 +63,8 @@ func TestStateProcessorErrors(t *testing.T) {
Ethash: new(params.EthashConfig),
TerminalTotalDifficulty: big.NewInt(0),
TerminalTotalDifficultyPassed: true,
ShanghaiTime: new(uint64),
CancunTime: new(uint64),
ShanghaiBlock: big.NewInt(0),
CancunBlock: big.NewInt(0),
Bor: &params.BorConfig{BurntContract: map[string]string{"0": "0x000000000000000000000000000000000000dead"}},
}
signer = types.LatestSigner(config)
@ -378,10 +378,11 @@ func GenerateBadBlock(parent *types.Block, engine consensus.Engine, txs types.Tr
Time: parent.Time() + 10,
UncleHash: types.EmptyUncleHash,
}
if config.IsLondon(header.Number) {
header.BaseFee = eip1559.CalcBaseFee(config, parent.Header())
}
if config.IsShanghai(header.Number, header.Time) {
if config.IsShanghai(header.Number) {
header.WithdrawalsHash = &types.EmptyWithdrawalsHash
}
@ -406,7 +407,7 @@ func GenerateBadBlock(parent *types.Block, engine consensus.Engine, txs types.Tr
}
header.Root = common.BytesToHash(hasher.Sum(nil))
if config.IsCancun(header.Number, header.Time) {
if config.IsCancun(header.Number) {
var pExcess, pUsed = uint64(0), uint64(0)
if parent.ExcessBlobGas() != nil {
pExcess = *parent.ExcessBlobGas()
@ -418,7 +419,7 @@ func GenerateBadBlock(parent *types.Block, engine consensus.Engine, txs types.Tr
header.BlobGasUsed = &used
}
// Assemble and return the final block for sealing
if config.IsShanghai(header.Number, header.Time) {
if config.IsShanghai(header.Number) {
return types.NewBlockWithWithdrawals(header, txs, nil, receipts, []*types.Withdrawal{}, trie.NewStackTrie(nil))
}

View file

@ -271,7 +271,7 @@ func (st *StateTransition) buyGas() error {
balanceCheck = balanceCheck.Mul(balanceCheck, st.msg.GasFeeCap)
balanceCheck.Add(balanceCheck, st.msg.Value)
}
if st.evm.ChainConfig().IsCancun(st.evm.Context.BlockNumber, st.evm.Context.Time) {
if st.evm.ChainConfig().IsCancun(st.evm.Context.BlockNumber) {
if blobGas := st.blobGasUsed(); blobGas > 0 {
// Check that the user has enough funds to cover blobGasUsed * tx.BlobGasFeeCap
blobBalanceCheck := new(big.Int).SetUint64(blobGas)
@ -362,7 +362,7 @@ func (st *StateTransition) preCheck() error {
}
}
if st.evm.ChainConfig().IsCancun(st.evm.Context.BlockNumber, st.evm.Context.Time) {
if st.evm.ChainConfig().IsCancun(st.evm.Context.BlockNumber) {
if st.blobGasUsed() > 0 {
// Check that the user is paying at least the current blob fee
blobFee := eip4844.CalcBlobFee(*st.evm.Context.ExcessBlobGas)
@ -441,7 +441,6 @@ func (st *StateTransition) TransitionDb(interruptCtx context.Context) (*Executio
}
// Check whether the init code size has been exceeded.
// TODO marcello double check
if rules.IsShanghai && contractCreation && len(msg.Data) > params.MaxInitCodeSize {
return nil, fmt.Errorf("%w: code size %v limit %v", ErrMaxInitCodeSizeExceeded, len(msg.Data), params.MaxInitCodeSize)
}

View file

@ -768,7 +768,7 @@ func (p *BlobPool) Reset(oldHead, newHead *types.Header) {
}
}
// Flush out any blobs from limbo that are older than the latest finality
if p.chain.Config().IsCancun(p.head.Number, p.head.Time) {
if p.chain.Config().IsCancun(p.head.Number) {
p.limbo.finalize(p.chain.CurrentFinalBlock())
}
// Reset the price heap for the new set of basefee/blobfee pairs

View file

@ -27,7 +27,6 @@ import (
"path/filepath"
"sync"
"testing"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus/misc/eip1559"
@ -75,8 +74,8 @@ func init() {
testChainConfig = new(params.ChainConfig)
*testChainConfig = *params.TestChainConfig
testChainConfig.CancunTime = new(uint64)
*testChainConfig.CancunTime = uint64(time.Now().Unix())
testChainConfig.CancunBlock = big.NewInt(0)
*testChainConfig.CancunBlock = *big.NewInt(0)
}
// testBlockChain is a mock of the live chain for testing the pool.
@ -99,8 +98,9 @@ func (bc *testBlockChain) CurrentBlock() *types.Header {
// mainnet ether existence, use that as a cap for the tests.
var (
blockNumber = new(big.Int).Add(bc.config.LondonBlock, big.NewInt(1))
blockTime = *bc.config.CancunTime + 1
gasLimit = uint64(30_000_000)
blockTime = 1
// blockTime = *bc.config.CancunBlock + 1
gasLimit = uint64(30_000_000)
)
lo := new(big.Int)
hi := new(big.Int).Mul(big.NewInt(5714), new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
@ -141,7 +141,7 @@ func (bc *testBlockChain) CurrentBlock() *types.Header {
return &types.Header{
Number: blockNumber,
Time: blockTime,
Time: uint64(blockTime),
GasLimit: gasLimit,
BaseFee: baseFee,
ExcessBlobGas: &excessBlobGas,

View file

@ -63,11 +63,11 @@ func ValidateTransaction(tx *types.Transaction, blobs []kzg4844.Blob, commits []
if !opts.Config.IsLondon(head.Number) && tx.Type() == types.DynamicFeeTxType {
return fmt.Errorf("%w: type %d rejected, pool not yet in London", core.ErrTxTypeNotSupported, tx.Type())
}
if !opts.Config.IsCancun(head.Number, head.Time) && tx.Type() == types.BlobTxType {
if !opts.Config.IsCancun(head.Number) && tx.Type() == types.BlobTxType {
return fmt.Errorf("%w: type %d rejected, pool not yet in Cancun", core.ErrTxTypeNotSupported, tx.Type())
}
// Check whether the init code size has been exceeded
if opts.Config.IsShanghai(head.Number, head.Time) && tx.To() == nil && len(tx.Data()) > params.MaxInitCodeSize {
if opts.Config.IsShanghai(head.Number) && tx.To() == nil && len(tx.Data()) > params.MaxInitCodeSize {
return fmt.Errorf("%w: code size %v, limit %v", core.ErrMaxInitCodeSizeExceeded, len(tx.Data()), params.MaxInitCodeSize)
}
// Transactions can't be negative. This may never happen using RLP decoded
@ -96,7 +96,7 @@ func ValidateTransaction(tx *types.Transaction, blobs []kzg4844.Blob, commits []
}
// Ensure the transaction has more gas than the bare minimum needed to cover
// the transaction metadata
intrGas, err := core.IntrinsicGas(tx.Data(), tx.AccessList(), tx.To() == nil, true, opts.Config.IsIstanbul(head.Number), opts.Config.IsShanghai(head.Number, head.Time))
intrGas, err := core.IntrinsicGas(tx.Data(), tx.AccessList(), tx.To() == nil, true, opts.Config.IsIstanbul(head.Number), opts.Config.IsShanghai(head.Number))
if err != nil {
return err
}

View file

@ -40,7 +40,7 @@ type sigCache struct {
func MakeSigner(config *params.ChainConfig, blockNumber *big.Int, blockTime uint64) Signer {
var signer Signer
switch {
case config.IsCancun(blockNumber, blockTime):
case config.IsCancun(blockNumber):
signer = NewCancunSigner(config.ChainID)
case config.IsLondon(blockNumber):
signer = NewLondonSigner(config.ChainID)
@ -65,7 +65,7 @@ func MakeSigner(config *params.ChainConfig, blockNumber *big.Int, blockTime uint
// have the current block number available, use MakeSigner instead.
func LatestSigner(config *params.ChainConfig) Signer {
if config.ChainID != nil {
if config.CancunTime != nil {
if config.CancunBlock != nil {
return NewCancunSigner(config.ChainID)
}
if config.LondonBlock != nil {

View file

@ -135,8 +135,7 @@ func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb StateDB, chainConfig
StateDB: statedb,
Config: config,
chainConfig: chainConfig,
// TODO marcello double check
chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time),
chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time),
}
evm.interpreter = NewEVMInterpreter(evm)

View file

@ -47,7 +47,6 @@ func Register(stack *node.Node, backend *eth.Ethereum) error {
Authenticated: true,
},
})
return nil
}
@ -139,7 +138,6 @@ func NewConsensusAPI(eth *eth.Ethereum) *ConsensusAPI {
if eth.BlockChain().Config().TerminalTotalDifficulty == nil {
log.Warn("Engine API started but chain not configured for merge yet")
}
api := &ConsensusAPI{
eth: eth,
remoteBlocks: newHeaderQueue(),
@ -148,7 +146,6 @@ func NewConsensusAPI(eth *eth.Ethereum) *ConsensusAPI {
invalidTipsets: make(map[common.Hash]*types.Header),
}
eth.Downloader().SetBadBlockCallback(api.setInvalidAncestor)
go api.heartbeat()
return api
@ -173,11 +170,10 @@ func (api *ConsensusAPI) ForkchoiceUpdatedV1(update engine.ForkchoiceStateV1, pa
if payloadAttributes.Withdrawals != nil {
return engine.STATUS_INVALID, engine.InvalidParams.With(errors.New("withdrawals not supported in V1"))
}
if api.eth.BlockChain().Config().IsShanghai(api.eth.BlockChain().Config().LondonBlock, payloadAttributes.Timestamp) {
if api.eth.BlockChain().Config().IsShanghai(api.eth.BlockChain().Config().LondonBlock) {
return engine.STATUS_INVALID, engine.InvalidParams.With(errors.New("forkChoiceUpdateV1 called post-shanghai"))
}
}
return api.forkchoiceUpdated(update, payloadAttributes)
}
@ -188,12 +184,11 @@ func (api *ConsensusAPI) ForkchoiceUpdatedV2(update engine.ForkchoiceStateV1, pa
return engine.STATUS_INVALID, engine.InvalidParams.With(err)
}
}
return api.forkchoiceUpdated(update, payloadAttributes)
}
func (api *ConsensusAPI) verifyPayloadAttributes(attr *engine.PayloadAttributes) error {
if !api.eth.BlockChain().Config().IsShanghai(api.eth.BlockChain().Config().LondonBlock, attr.Timestamp) {
if !api.eth.BlockChain().Config().IsShanghai(api.eth.BlockChain().Config().LondonBlock) {
// Reject payload attributes with withdrawals before shanghai
if attr.Withdrawals != nil {
return errors.New("withdrawals before shanghai")
@ -204,17 +199,14 @@ func (api *ConsensusAPI) verifyPayloadAttributes(attr *engine.PayloadAttributes)
return errors.New("missing withdrawals list")
}
}
return nil
}
// nolint:gocognit
func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payloadAttributes *engine.PayloadAttributes) (engine.ForkChoiceResponse, error) {
api.forkchoiceLock.Lock()
defer api.forkchoiceLock.Unlock()
log.Trace("Engine API request received", "method", "ForkchoiceUpdated", "head", update.HeadBlockHash, "finalized", update.FinalizedBlockHash, "safe", update.SafeBlockHash)
if update.HeadBlockHash == (common.Hash{}) {
log.Warn("Forkchoice requested update to zero hash")
return engine.STATUS_INVALID, nil // TODO(karalabe): Why does someone send us this?
@ -253,9 +245,7 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl
merger.ReachTTD()
api.eth.Downloader().Cancel()
}
context := []interface{}{"number", header.Number, "hash", header.Hash()}
if update.FinalizedBlockHash != (common.Hash{}) {
if finalized == nil {
context = append(context, []interface{}{"finalized", "unknown"}...)
@ -263,13 +253,10 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl
context = append(context, []interface{}{"finalized", finalized.Number}...)
}
}
log.Info("Forkchoice requested sync to new head", context...)
if err := api.eth.Downloader().BeaconSync(api.eth.SyncMode(), header, finalized); err != nil {
return engine.STATUS_SYNCING, err
}
return engine.STATUS_SYNCING, nil
}
// Block is known locally, just sanity check that the beacon client does not
@ -280,30 +267,25 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl
ptd = api.eth.BlockChain().GetTd(block.ParentHash(), block.NumberU64()-1)
ttd = api.eth.BlockChain().Config().TerminalTotalDifficulty
)
if td == nil || (block.NumberU64() > 0 && ptd == nil) {
log.Error("TDs unavailable for TTD check", "number", block.NumberU64(), "hash", update.HeadBlockHash, "td", td, "parent", block.ParentHash(), "ptd", ptd)
return engine.STATUS_INVALID, errors.New("TDs unavailable for TDD check")
}
if td.Cmp(ttd) < 0 {
log.Error("Refusing beacon update to pre-merge", "number", block.NumberU64(), "hash", update.HeadBlockHash, "diff", block.Difficulty(), "age", common.PrettyAge(time.Unix(int64(block.Time()), 0)))
return engine.ForkChoiceResponse{PayloadStatus: engine.INVALID_TERMINAL_BLOCK, PayloadID: nil}, nil
}
if block.NumberU64() > 0 && ptd.Cmp(ttd) >= 0 {
log.Error("Parent block is already post-ttd", "number", block.NumberU64(), "hash", update.HeadBlockHash, "diff", block.Difficulty(), "age", common.PrettyAge(time.Unix(int64(block.Time()), 0)))
return engine.ForkChoiceResponse{PayloadStatus: engine.INVALID_TERMINAL_BLOCK, PayloadID: nil}, nil
}
}
valid := func(id *engine.PayloadID) engine.ForkChoiceResponse {
return engine.ForkChoiceResponse{
PayloadStatus: engine.PayloadStatusV1{Status: engine.VALID, LatestValidHash: &update.HeadBlockHash},
PayloadID: id,
}
}
if rawdb.ReadCanonicalHash(api.eth.ChainDb(), block.NumberU64()) != update.HeadBlockHash {
// Block is not canonical, set head.
if latestValid, err := api.eth.BlockChain().SetCanonical(block); err != nil {
@ -319,7 +301,6 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl
log.Info("Ignoring beacon update to old head", "number", block.NumberU64(), "hash", update.HeadBlockHash, "age", common.PrettyAge(time.Unix(int64(block.Time()), 0)), "have", api.eth.BlockChain().CurrentBlock().Number)
return valid(nil), nil
}
api.eth.SetSynced()
// If the beacon client also advertised a finalized block, mark the local
@ -347,7 +328,6 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl
log.Warn("Safe block not available in database")
return engine.STATUS_INVALID, engine.InvalidForkChoiceState.With(errors.New("safe block not available in database"))
}
if rawdb.ReadCanonicalHash(api.eth.ChainDb(), safeBlock.NumberU64()) != update.SafeBlockHash {
log.Warn("Safe block not in canonical chain")
return engine.STATUS_INVALID, engine.InvalidForkChoiceState.With(errors.New("safe block not in canonical chain"))
@ -372,18 +352,14 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl
if api.localBlocks.has(id) {
return valid(&id), nil
}
payload, err := api.eth.Miner().BuildPayload(args)
if err != nil {
log.Error("Failed to build payload", "err", err)
return valid(nil), engine.InvalidPayloadAttributes.With(err)
}
api.localBlocks.put(id, payload)
return valid(&id), nil
}
return valid(nil), nil
}
@ -391,7 +367,6 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl
// the configuration of the node.
func (api *ConsensusAPI) ExchangeTransitionConfigurationV1(config engine.TransitionConfigurationV1) (*engine.TransitionConfigurationV1, error) {
log.Trace("Engine API request received", "method", "ExchangeTransitionConfiguration", "ttd", config.TerminalTotalDifficulty)
if config.TerminalTotalDifficulty == nil {
return nil, errors.New("invalid terminal total difficulty")
}
@ -405,7 +380,6 @@ func (api *ConsensusAPI) ExchangeTransitionConfigurationV1(config engine.Transit
log.Warn("Invalid TTD configured", "geth", ttd, "beacon", config.TerminalTotalDifficulty)
return nil, fmt.Errorf("invalid ttd: execution %v consensus %v", ttd, config.TerminalTotalDifficulty)
}
if config.TerminalBlockHash != (common.Hash{}) {
if hash := api.eth.BlockChain().GetCanonicalHash(uint64(config.TerminalBlockNumber)); hash == config.TerminalBlockHash {
return &engine.TransitionConfigurationV1{
@ -416,7 +390,6 @@ func (api *ConsensusAPI) ExchangeTransitionConfigurationV1(config engine.Transit
}
return nil, errors.New("invalid terminal block hash")
}
return &engine.TransitionConfigurationV1{TerminalTotalDifficulty: (*hexutil.Big)(ttd)}, nil
}
@ -426,7 +399,6 @@ func (api *ConsensusAPI) GetPayloadV1(payloadID engine.PayloadID) (*engine.Execu
if err != nil {
return nil, err
}
return data.ExecutionPayload, nil
}
@ -446,7 +418,6 @@ func (api *ConsensusAPI) getPayload(payloadID engine.PayloadID) (*engine.Executi
if data == nil {
return nil, engine.UnknownPayload
}
return data, nil
}
@ -460,14 +431,14 @@ func (api *ConsensusAPI) NewPayloadV1(params engine.ExecutableData) (engine.Payl
// NewPayloadV2 creates an Eth1 block, inserts it in the chain, and returns the status of the chain.
func (api *ConsensusAPI) NewPayloadV2(params engine.ExecutableData) (engine.PayloadStatusV1, error) {
if api.eth.BlockChain().Config().IsShanghai(new(big.Int).SetUint64(params.Number), params.Timestamp) {
if api.eth.BlockChain().Config().IsShanghai(new(big.Int).SetUint64(params.Number)) {
if params.Withdrawals == nil {
return engine.PayloadStatusV1{Status: engine.INVALID}, engine.InvalidParams.With(errors.New("nil withdrawals post-shanghai"))
}
} else if params.Withdrawals != nil {
return engine.PayloadStatusV1{Status: engine.INVALID}, engine.InvalidParams.With(errors.New("non-nil withdrawals pre-shanghai"))
}
if api.eth.BlockChain().Config().IsCancun(new(big.Int).SetUint64(params.Number), params.Timestamp) {
if api.eth.BlockChain().Config().IsCancun(new(big.Int).SetUint64(params.Number)) {
return engine.PayloadStatusV1{Status: engine.INVALID}, engine.InvalidParams.With(errors.New("newPayloadV2 called post-cancun"))
}
return api.newPayload(params, nil)
@ -475,7 +446,7 @@ func (api *ConsensusAPI) NewPayloadV2(params engine.ExecutableData) (engine.Payl
// NewPayloadV3 creates an Eth1 block, inserts it in the chain, and returns the status of the chain.
func (api *ConsensusAPI) NewPayloadV3(params engine.ExecutableData, versionedHashes *[]common.Hash) (engine.PayloadStatusV1, error) {
if !api.eth.BlockChain().Config().IsCancun(new(big.Int).SetUint64(params.Number), params.Timestamp) {
if !api.eth.BlockChain().Config().IsCancun(new(big.Int).SetUint64(params.Number)) {
return engine.PayloadStatusV1{Status: engine.INVALID}, engine.InvalidParams.With(errors.New("newPayloadV3 called pre-cancun"))
}
@ -522,7 +493,6 @@ func (api *ConsensusAPI) newPayload(params engine.ExecutableData, versionedHashe
if block := api.eth.BlockChain().GetBlockByHash(params.BlockHash); block != nil {
log.Warn("Ignoring already known beacon payload", "number", params.Number, "hash", params.BlockHash, "age", common.PrettyAge(time.Unix(int64(block.Time()), 0)))
hash := block.Hash()
return engine.PayloadStatusV1{Status: engine.VALID, LatestValidHash: &hash}, nil
}
// If this block was rejected previously, keep rejecting it
@ -546,17 +516,14 @@ func (api *ConsensusAPI) newPayload(params engine.ExecutableData, versionedHashe
ttd = api.eth.BlockChain().Config().TerminalTotalDifficulty
gptd = api.eth.BlockChain().GetTd(parent.ParentHash(), parent.NumberU64()-1)
)
if ptd.Cmp(ttd) < 0 {
log.Warn("Ignoring pre-merge payload", "number", params.Number, "hash", params.BlockHash, "td", ptd, "ttd", ttd)
return engine.INVALID_TERMINAL_BLOCK, nil
}
if parent.Difficulty().BitLen() > 0 && gptd != nil && gptd.Cmp(ttd) >= 0 {
log.Error("Ignoring pre-merge parent block", "number", params.Number, "hash", params.BlockHash, "td", ptd, "ttd", ttd)
return engine.INVALID_TERMINAL_BLOCK, nil
}
if block.Time() <= parent.Time() {
log.Warn("Invalid timestamp", "parent", block.Time(), "block", block.Time())
return api.invalid(errors.New("invalid timestamp"), parent.Header()), nil
@ -568,16 +535,12 @@ func (api *ConsensusAPI) newPayload(params engine.ExecutableData, versionedHashe
if api.eth.SyncMode() != downloader.FullSync {
return api.delayPayloadImport(block)
}
if !api.eth.BlockChain().HasBlockAndState(block.ParentHash(), block.NumberU64()-1) {
api.remoteBlocks.put(block.Hash(), block.Header())
log.Warn("State not available, ignoring new payload")
return engine.PayloadStatusV1{Status: engine.ACCEPTED}, nil
}
log.Trace("Inserting block without sethead", "hash", block.Hash(), "number", block.Number)
if err := api.eth.BlockChain().InsertBlockWithoutSetHead(block); err != nil {
log.Warn("NewPayloadV1: inserting block failed", "error", err)
@ -595,9 +558,7 @@ func (api *ConsensusAPI) newPayload(params engine.ExecutableData, versionedHashe
merger.ReachTTD()
api.eth.Downloader().Cancel()
}
hash := block.Hash()
return engine.PayloadStatusV1{Status: engine.VALID, LatestValidHash: &hash}, nil
}
@ -637,7 +598,6 @@ func (api *ConsensusAPI) delayPayloadImport(block *types.Block) (engine.PayloadS
// and cannot afford concurrent out-if-band modifications via imports.
log.Warn("Ignoring payload while snap syncing", "number", block.NumberU64(), "hash", block.Hash())
}
return engine.PayloadStatusV1{Status: engine.SYNCING}, nil
}
@ -676,20 +636,17 @@ func (api *ConsensusAPI) checkInvalidAncestor(check common.Hash, head common.Has
delete(api.invalidTipsets, descendant)
}
}
return nil
}
// Not too many failures yet, mark the head of the invalid chain as invalid
if check != head {
log.Warn("Marked new chain head as invalid", "hash", head, "badnumber", invalid.Number, "badhash", badHash)
for len(api.invalidTipsets) >= invalidTipsetsCap {
for key := range api.invalidTipsets {
delete(api.invalidTipsets, key)
break
}
}
api.invalidTipsets[head] = invalid
}
// If the last valid hash is the terminal pow block, return 0x0 for latest valid hash
@ -697,9 +654,7 @@ func (api *ConsensusAPI) checkInvalidAncestor(check common.Hash, head common.Has
if header := api.eth.BlockChain().GetHeader(invalid.ParentHash, invalid.Number.Uint64()-1); header != nil && header.Difficulty.Sign() != 0 {
lastValid = &common.Hash{}
}
failure := "links to previously rejected block"
return &engine.PayloadStatusV1{
Status: engine.INVALID,
LatestValidHash: lastValid,
@ -719,9 +674,7 @@ func (api *ConsensusAPI) invalid(err error, latestValid *types.Header) engine.Pa
currentHash = latestValid.Hash()
}
}
errorMsg := err.Error()
return engine.PayloadStatusV1{Status: engine.INVALID, LatestValidHash: &currentHash, ValidationError: &errorMsg}
}
@ -760,7 +713,6 @@ func (api *ConsensusAPI) heartbeat() {
// If there have been no updates for the past while, warn the user
// that the beacon client is probably offline
// nolint:nestif
if api.eth.BlockChain().Config().TerminalTotalDifficultyPassed || api.eth.Merger().TDDReached() {
if time.Since(lastForkchoiceUpdate) <= beaconUpdateConsensusTimeout || time.Since(lastNewPayloadUpdate) <= beaconUpdateConsensusTimeout {
offlineLogged = time.Time{}
@ -777,10 +729,8 @@ func (api *ConsensusAPI) heartbeat() {
} else {
log.Warn("Beacon client online, but no consensus updates received in a while. Please fix your beacon client to follow the chain!")
}
offlineLogged = time.Now()
}
continue
}
}
@ -795,12 +745,10 @@ func (api *ConsensusAPI) ExchangeCapabilities([]string) []string {
// of block bodies by the engine api.
func (api *ConsensusAPI) GetPayloadBodiesByHashV1(hashes []common.Hash) []*engine.ExecutionPayloadBodyV1 {
var bodies = make([]*engine.ExecutionPayloadBodyV1, len(hashes))
for i, hash := range hashes {
block := api.eth.BlockChain().GetBlockByHash(hash)
bodies[i] = getBody(block)
}
return bodies
}
@ -810,25 +758,20 @@ func (api *ConsensusAPI) GetPayloadBodiesByRangeV1(start, count hexutil.Uint64)
if start == 0 || count == 0 {
return nil, engine.InvalidParams.With(fmt.Errorf("invalid start or count, start: %v count: %v", start, count))
}
if count > 1024 {
return nil, engine.TooLargeRequest.With(fmt.Errorf("requested count too large: %v", count))
}
// limit count up until current
current := api.eth.BlockChain().CurrentBlock().Number.Uint64()
last := uint64(start) + uint64(count) - 1
if last > current {
last = current
}
bodies := make([]*engine.ExecutionPayloadBodyV1, 0, uint64(count))
for i := uint64(start); i <= last; i++ {
block := api.eth.BlockChain().GetBlockByNumber(i)
bodies = append(bodies, getBody(block))
}
return bodies, nil
}

File diff suppressed because it is too large Load diff

View file

@ -19,6 +19,7 @@ package ethconfig
import (
"errors"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
@ -172,7 +173,7 @@ type Config struct {
RPCTxFeeCap float64
// OverrideCancun (TODO: remove after the fork)
OverrideCancun *uint64 `toml:",omitempty"`
OverrideCancun *big.Int `toml:",omitempty"`
// URL to connect to Heimdall node
HeimdallURL string
@ -202,7 +203,7 @@ type Config struct {
DevFakeAuthor bool `hcl:"devfakeauthor,optional" toml:"devfakeauthor,optional"`
// OverrideVerkle (TODO: remove after the fork)
OverrideVerkle *uint64 `toml:",omitempty"`
OverrideVerkle *big.Int `toml:",omitempty"`
}
// CreateConsensusEngine creates a consensus engine for the given chain configuration.

View file

@ -3,6 +3,7 @@
package ethconfig
import (
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
@ -17,44 +18,58 @@ import (
// MarshalTOML marshals as TOML.
func (c Config) MarshalTOML() (interface{}, error) {
type Config struct {
Genesis *core.Genesis `toml:",omitempty"`
NetworkId uint64
SyncMode downloader.SyncMode
EthDiscoveryURLs []string
SnapDiscoveryURLs []string
NoPruning bool
NoPrefetch bool
TxLookupLimit uint64 `toml:",omitempty"`
RequiredBlocks map[uint64]common.Hash `toml:"-"`
LightServ int `toml:",omitempty"`
LightIngress int `toml:",omitempty"`
LightEgress int `toml:",omitempty"`
LightPeers int `toml:",omitempty"`
LightNoPrune bool `toml:",omitempty"`
LightNoSyncServe bool `toml:",omitempty"`
SkipBcVersionCheck bool `toml:"-"`
DatabaseHandles int `toml:"-"`
DatabaseCache int
DatabaseFreezer string
TrieCleanCache int
TrieDirtyCache int
TrieTimeout time.Duration
SnapshotCache int
Preimages bool
FilterLogCacheSize int
Miner miner.Config
TxPool legacypool.Config
BlobPool blobpool.Config
GPO gasprice.Config
EnablePreimageRecording bool
DocRoot string `toml:"-"`
RPCGasCap uint64
RPCEVMTimeout time.Duration
RPCTxFeeCap float64
OverrideCancun *uint64 `toml:",omitempty"`
OverrideVerkle *uint64 `toml:",omitempty"`
Genesis *core.Genesis `toml:",omitempty"`
NetworkId uint64
SyncMode downloader.SyncMode
EthDiscoveryURLs []string
SnapDiscoveryURLs []string
NoPruning bool
NoPrefetch bool
TxLookupLimit uint64 `toml:",omitempty"`
RequiredBlocks map[uint64]common.Hash `toml:"-"`
LightServ int `toml:",omitempty"`
LightIngress int `toml:",omitempty"`
LightEgress int `toml:",omitempty"`
LightPeers int `toml:",omitempty"`
LightNoPrune bool `toml:",omitempty"`
LightNoSyncServe bool `toml:",omitempty"`
SkipBcVersionCheck bool `toml:"-"`
DatabaseHandles int `toml:"-"`
DatabaseCache int
DatabaseFreezer string
LevelDbCompactionTableSize uint64
LevelDbCompactionTableSizeMultiplier float64
LevelDbCompactionTotalSize uint64
LevelDbCompactionTotalSizeMultiplier float64
TrieCleanCache int
TrieDirtyCache int
TrieTimeout time.Duration
SnapshotCache int
Preimages bool
TriesInMemory uint64
FilterLogCacheSize int
Miner miner.Config
TxPool legacypool.Config
BlobPool blobpool.Config
GPO gasprice.Config
EnablePreimageRecording bool
DocRoot string `toml:"-"`
RPCGasCap uint64
RPCReturnDataLimit uint64
RPCEVMTimeout time.Duration
RPCTxFeeCap float64
OverrideCancun *big.Int `toml:",omitempty"`
HeimdallURL string
WithoutHeimdall bool
HeimdallgRPCAddress string
RunHeimdall bool
RunHeimdallArgs string
UseHeimdallApp bool
BorLogs bool
ParallelEVM core.ParallelEVMConfig `toml:",omitempty"`
DevFakeAuthor bool `hcl:"devfakeauthor,optional" toml:"devfakeauthor,optional"`
OverrideVerkle *big.Int `toml:",omitempty"`
}
var enc Config
enc.Genesis = c.Genesis
enc.NetworkId = c.NetworkId
@ -75,11 +90,16 @@ func (c Config) MarshalTOML() (interface{}, error) {
enc.DatabaseHandles = c.DatabaseHandles
enc.DatabaseCache = c.DatabaseCache
enc.DatabaseFreezer = c.DatabaseFreezer
enc.LevelDbCompactionTableSize = c.LevelDbCompactionTableSize
enc.LevelDbCompactionTableSizeMultiplier = c.LevelDbCompactionTableSizeMultiplier
enc.LevelDbCompactionTotalSize = c.LevelDbCompactionTotalSize
enc.LevelDbCompactionTotalSizeMultiplier = c.LevelDbCompactionTotalSizeMultiplier
enc.TrieCleanCache = c.TrieCleanCache
enc.TrieDirtyCache = c.TrieDirtyCache
enc.TrieTimeout = c.TrieTimeout
enc.SnapshotCache = c.SnapshotCache
enc.Preimages = c.Preimages
enc.TriesInMemory = c.TriesInMemory
enc.FilterLogCacheSize = c.FilterLogCacheSize
enc.Miner = c.Miner
enc.TxPool = c.TxPool
@ -88,9 +108,19 @@ func (c Config) MarshalTOML() (interface{}, error) {
enc.EnablePreimageRecording = c.EnablePreimageRecording
enc.DocRoot = c.DocRoot
enc.RPCGasCap = c.RPCGasCap
enc.RPCReturnDataLimit = c.RPCReturnDataLimit
enc.RPCEVMTimeout = c.RPCEVMTimeout
enc.RPCTxFeeCap = c.RPCTxFeeCap
enc.OverrideCancun = c.OverrideCancun
enc.HeimdallURL = c.HeimdallURL
enc.WithoutHeimdall = c.WithoutHeimdall
enc.HeimdallgRPCAddress = c.HeimdallgRPCAddress
enc.RunHeimdall = c.RunHeimdall
enc.RunHeimdallArgs = c.RunHeimdallArgs
enc.UseHeimdallApp = c.UseHeimdallApp
enc.BorLogs = c.BorLogs
enc.ParallelEVM = c.ParallelEVM
enc.DevFakeAuthor = c.DevFakeAuthor
enc.OverrideVerkle = c.OverrideVerkle
return &enc, nil
}
@ -98,147 +128,152 @@ func (c Config) MarshalTOML() (interface{}, error) {
// UnmarshalTOML unmarshals from TOML.
func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error {
type Config struct {
Genesis *core.Genesis `toml:",omitempty"`
NetworkId *uint64
SyncMode *downloader.SyncMode
EthDiscoveryURLs []string
SnapDiscoveryURLs []string
NoPruning *bool
NoPrefetch *bool
TxLookupLimit *uint64 `toml:",omitempty"`
RequiredBlocks map[uint64]common.Hash `toml:"-"`
LightServ *int `toml:",omitempty"`
LightIngress *int `toml:",omitempty"`
LightEgress *int `toml:",omitempty"`
LightPeers *int `toml:",omitempty"`
LightNoPrune *bool `toml:",omitempty"`
LightNoSyncServe *bool `toml:",omitempty"`
SkipBcVersionCheck *bool `toml:"-"`
DatabaseHandles *int `toml:"-"`
DatabaseCache *int
DatabaseFreezer *string
TrieCleanCache *int
TrieDirtyCache *int
TrieTimeout *time.Duration
SnapshotCache *int
Preimages *bool
FilterLogCacheSize *int
Miner *miner.Config
TxPool *legacypool.Config
BlobPool *blobpool.Config
GPO *gasprice.Config
EnablePreimageRecording *bool
DocRoot *string `toml:"-"`
RPCGasCap *uint64
RPCEVMTimeout *time.Duration
RPCTxFeeCap *float64
OverrideCancun *uint64 `toml:",omitempty"`
OverrideVerkle *uint64 `toml:",omitempty"`
Genesis *core.Genesis `toml:",omitempty"`
NetworkId *uint64
SyncMode *downloader.SyncMode
EthDiscoveryURLs []string
SnapDiscoveryURLs []string
NoPruning *bool
NoPrefetch *bool
TxLookupLimit *uint64 `toml:",omitempty"`
RequiredBlocks map[uint64]common.Hash `toml:"-"`
LightServ *int `toml:",omitempty"`
LightIngress *int `toml:",omitempty"`
LightEgress *int `toml:",omitempty"`
LightPeers *int `toml:",omitempty"`
LightNoPrune *bool `toml:",omitempty"`
LightNoSyncServe *bool `toml:",omitempty"`
SkipBcVersionCheck *bool `toml:"-"`
DatabaseHandles *int `toml:"-"`
DatabaseCache *int
DatabaseFreezer *string
LevelDbCompactionTableSize *uint64
LevelDbCompactionTableSizeMultiplier *float64
LevelDbCompactionTotalSize *uint64
LevelDbCompactionTotalSizeMultiplier *float64
TrieCleanCache *int
TrieDirtyCache *int
TrieTimeout *time.Duration
SnapshotCache *int
Preimages *bool
TriesInMemory *uint64
FilterLogCacheSize *int
Miner *miner.Config
TxPool *legacypool.Config
BlobPool *blobpool.Config
GPO *gasprice.Config
EnablePreimageRecording *bool
DocRoot *string `toml:"-"`
RPCGasCap *uint64
RPCReturnDataLimit *uint64
RPCEVMTimeout *time.Duration
RPCTxFeeCap *float64
OverrideCancun *big.Int `toml:",omitempty"`
HeimdallURL *string
WithoutHeimdall *bool
HeimdallgRPCAddress *string
RunHeimdall *bool
RunHeimdallArgs *string
UseHeimdallApp *bool
BorLogs *bool
ParallelEVM *core.ParallelEVMConfig `toml:",omitempty"`
DevFakeAuthor *bool `hcl:"devfakeauthor,optional" toml:"devfakeauthor,optional"`
OverrideVerkle *big.Int `toml:",omitempty"`
}
var dec Config
if err := unmarshal(&dec); err != nil {
return err
}
if dec.Genesis != nil {
c.Genesis = dec.Genesis
}
if dec.NetworkId != nil {
c.NetworkId = *dec.NetworkId
}
if dec.SyncMode != nil {
c.SyncMode = *dec.SyncMode
}
if dec.EthDiscoveryURLs != nil {
c.EthDiscoveryURLs = dec.EthDiscoveryURLs
}
if dec.SnapDiscoveryURLs != nil {
c.SnapDiscoveryURLs = dec.SnapDiscoveryURLs
}
if dec.NoPruning != nil {
c.NoPruning = *dec.NoPruning
}
if dec.NoPrefetch != nil {
c.NoPrefetch = *dec.NoPrefetch
}
if dec.TxLookupLimit != nil {
c.TxLookupLimit = *dec.TxLookupLimit
}
if dec.RequiredBlocks != nil {
c.RequiredBlocks = dec.RequiredBlocks
}
if dec.LightServ != nil {
c.LightServ = *dec.LightServ
}
if dec.LightIngress != nil {
c.LightIngress = *dec.LightIngress
}
if dec.LightEgress != nil {
c.LightEgress = *dec.LightEgress
}
if dec.LightPeers != nil {
c.LightPeers = *dec.LightPeers
}
if dec.LightNoPrune != nil {
c.LightNoPrune = *dec.LightNoPrune
}
if dec.LightNoSyncServe != nil {
c.LightNoSyncServe = *dec.LightNoSyncServe
}
if dec.SkipBcVersionCheck != nil {
c.SkipBcVersionCheck = *dec.SkipBcVersionCheck
}
if dec.DatabaseHandles != nil {
c.DatabaseHandles = *dec.DatabaseHandles
}
if dec.DatabaseCache != nil {
c.DatabaseCache = *dec.DatabaseCache
}
if dec.DatabaseFreezer != nil {
c.DatabaseFreezer = *dec.DatabaseFreezer
}
if dec.LevelDbCompactionTableSize != nil {
c.LevelDbCompactionTableSize = *dec.LevelDbCompactionTableSize
}
if dec.LevelDbCompactionTableSizeMultiplier != nil {
c.LevelDbCompactionTableSizeMultiplier = *dec.LevelDbCompactionTableSizeMultiplier
}
if dec.LevelDbCompactionTotalSize != nil {
c.LevelDbCompactionTotalSize = *dec.LevelDbCompactionTotalSize
}
if dec.LevelDbCompactionTotalSizeMultiplier != nil {
c.LevelDbCompactionTotalSizeMultiplier = *dec.LevelDbCompactionTotalSizeMultiplier
}
if dec.TrieCleanCache != nil {
c.TrieCleanCache = *dec.TrieCleanCache
}
if dec.TrieDirtyCache != nil {
c.TrieDirtyCache = *dec.TrieDirtyCache
}
if dec.TrieTimeout != nil {
c.TrieTimeout = *dec.TrieTimeout
}
if dec.SnapshotCache != nil {
c.SnapshotCache = *dec.SnapshotCache
}
if dec.Preimages != nil {
c.Preimages = *dec.Preimages
}
if dec.TriesInMemory != nil {
c.TriesInMemory = *dec.TriesInMemory
}
if dec.FilterLogCacheSize != nil {
c.FilterLogCacheSize = *dec.FilterLogCacheSize
}
if dec.Miner != nil {
c.Miner = *dec.Miner
}
@ -251,32 +286,56 @@ func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error {
if dec.GPO != nil {
c.GPO = *dec.GPO
}
if dec.EnablePreimageRecording != nil {
c.EnablePreimageRecording = *dec.EnablePreimageRecording
}
if dec.DocRoot != nil {
c.DocRoot = *dec.DocRoot
}
if dec.RPCGasCap != nil {
c.RPCGasCap = *dec.RPCGasCap
}
if dec.RPCReturnDataLimit != nil {
c.RPCReturnDataLimit = *dec.RPCReturnDataLimit
}
if dec.RPCEVMTimeout != nil {
c.RPCEVMTimeout = *dec.RPCEVMTimeout
}
if dec.RPCTxFeeCap != nil {
c.RPCTxFeeCap = *dec.RPCTxFeeCap
}
if dec.OverrideCancun != nil {
c.OverrideCancun = dec.OverrideCancun
}
if dec.HeimdallURL != nil {
c.HeimdallURL = *dec.HeimdallURL
}
if dec.WithoutHeimdall != nil {
c.WithoutHeimdall = *dec.WithoutHeimdall
}
if dec.HeimdallgRPCAddress != nil {
c.HeimdallgRPCAddress = *dec.HeimdallgRPCAddress
}
if dec.RunHeimdall != nil {
c.RunHeimdall = *dec.RunHeimdall
}
if dec.RunHeimdallArgs != nil {
c.RunHeimdallArgs = *dec.RunHeimdallArgs
}
if dec.UseHeimdallApp != nil {
c.UseHeimdallApp = *dec.UseHeimdallApp
}
if dec.BorLogs != nil {
c.BorLogs = *dec.BorLogs
}
if dec.ParallelEVM != nil {
c.ParallelEVM = *dec.ParallelEVM
}
if dec.DevFakeAuthor != nil {
c.DevFakeAuthor = *dec.DevFakeAuthor
}
if dec.OverrideVerkle != nil {
c.OverrideVerkle = dec.OverrideVerkle
}
return nil
}

View file

@ -75,7 +75,6 @@ func newTestBackendWithGenerator(blocks int, shanghai bool, generator func(int,
engine consensus.Engine = ethash.NewFaker()
)
// TODO marcello double check
if shanghai {
config = &params.ChainConfig{
ChainID: big.NewInt(1),
@ -95,7 +94,7 @@ func newTestBackendWithGenerator(blocks int, shanghai bool, generator func(int,
ArrowGlacierBlock: big.NewInt(0),
GrayGlacierBlock: big.NewInt(0),
MergeNetsplitBlock: big.NewInt(0),
ShanghaiTime: u64(0),
ShanghaiBlock: big.NewInt(0),
TerminalTotalDifficulty: big.NewInt(0),
TerminalTotalDifficultyPassed: true,
Ethash: new(params.EthashConfig),

View file

@ -1376,8 +1376,8 @@ func overrideConfig(original *params.ChainConfig, override *params.ChainConfig)
chainConfigCopy.BerlinBlock = block
canon = false
}
if timestamp := override.VerkleTime; timestamp != nil {
chainConfigCopy.VerkleTime = timestamp
if timestamp := override.VerkleBlock; timestamp != nil {
chainConfigCopy.VerkleBlock = timestamp
canon = false
}
@ -1401,18 +1401,18 @@ func overrideConfig(original *params.ChainConfig, override *params.ChainConfig)
canon = false
}
if timestamp := override.ShanghaiTime; timestamp != nil {
chainConfigCopy.ShanghaiTime = timestamp
if timestamp := override.ShanghaiBlock; timestamp != nil {
chainConfigCopy.ShanghaiBlock = timestamp
canon = false
}
if timestamp := override.CancunTime; timestamp != nil {
chainConfigCopy.CancunTime = timestamp
if timestamp := override.CancunBlock; timestamp != nil {
chainConfigCopy.CancunBlock = timestamp
canon = false
}
if timestamp := override.PragueTime; timestamp != nil {
chainConfigCopy.PragueTime = timestamp
if timestamp := override.PragueBlock; timestamp != nil {
chainConfigCopy.PragueBlock = timestamp
canon = false
}

View file

@ -462,8 +462,8 @@ func newGQLService(t *testing.T, stack *node.Node, shanghai bool, gspec *core.Ge
chainCfg.TerminalTotalDifficulty = common.Big0
// GenerateChain will increment timestamps by 10.
// Shanghai upgrade at block 1.
shanghaiTime := uint64(5)
chainCfg.ShanghaiTime = &shanghaiTime
ShanghaiBlock := big.NewInt(5)
chainCfg.ShanghaiBlock = ShanghaiBlock
}
ethBackend, err := eth.New(stack, ethConf)
if err != nil {

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -318,7 +318,7 @@ func (pool *TxPool) setNewHead(head *types.Header) {
next := new(big.Int).Add(head.Number, big.NewInt(1))
pool.istanbul = pool.config.IsIstanbul(next)
pool.eip2718 = pool.config.IsBerlin(next)
pool.shanghai = pool.config.IsShanghai(next, uint64(time.Now().Unix()))
pool.shanghai = pool.config.IsShanghai(next)
}
// Stop stops the light transaction pool

File diff suppressed because one or more lines are too long

View file

@ -94,22 +94,11 @@ func TestCheckCompatible(t *testing.T) {
},
},
{
stored: &ChainConfig{ShanghaiTime: newUint64(10)},
new: &ChainConfig{ShanghaiTime: newUint64(20)},
stored: &ChainConfig{ShanghaiBlock: big.NewInt(30)},
new: &ChainConfig{ShanghaiBlock: big.NewInt(30)},
headTimestamp: 9,
wantErr: nil,
},
{
stored: &ChainConfig{ShanghaiTime: newUint64(10)},
new: &ChainConfig{ShanghaiTime: newUint64(20)},
headTimestamp: 25,
wantErr: &ConfigCompatError{
What: "Shanghai fork timestamp",
StoredTime: newUint64(10),
NewTime: newUint64(20),
RewindToTime: 9,
},
},
}
for _, test := range tests {
@ -124,25 +113,25 @@ func TestConfigRules(t *testing.T) {
t.Parallel()
c := &ChainConfig{
LondonBlock: new(big.Int),
ShanghaiTime: newUint64(500),
LondonBlock: new(big.Int),
ShanghaiBlock: big.NewInt(10),
}
var stamp uint64
block := new(big.Int)
if r := c.Rules(big.NewInt(0), true, stamp); r.IsShanghai {
t.Errorf("expected %v to not be shanghai", stamp)
if r := c.Rules(block, true, 0); r.IsShanghai {
t.Errorf("expected %v to not be shanghai", 0)
}
stamp = 500
block.SetInt64(10)
if r := c.Rules(big.NewInt(0), true, stamp); !r.IsShanghai {
t.Errorf("expected %v to be shanghai", stamp)
if r := c.Rules(block, true, 0); !r.IsShanghai {
t.Errorf("expected %v to be shanghai", 0)
}
stamp = math.MaxInt64
block = block.SetInt64(math.MaxInt64)
if r := c.Rules(big.NewInt(0), true, stamp); !r.IsShanghai {
t.Errorf("expected %v to be shanghai", stamp)
if r := c.Rules(block, true, 0); !r.IsShanghai {
t.Errorf("expected %v to be shanghai", 0)
}
}

View file

@ -969,6 +969,290 @@ func TestEIP1559Transition(t *testing.T) {
}
}
func TestBurnContract(t *testing.T) {
var (
aa = common.HexToAddress("0x000000000000000000000000000000000000aaaa")
// Generate a canonical chain to act as the main dataset
db = rawdb.NewMemoryDatabase()
engine = ethash.NewFaker()
// A sender who makes transactions, has some funds
key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
key3, _ = crypto.HexToECDSA("225171aed3793cba1c029832886d69785b7e77a54a44211226b447aa2d16b058")
addr1 = crypto.PubkeyToAddress(key1.PublicKey)
addr2 = crypto.PubkeyToAddress(key2.PublicKey)
addr3 = crypto.PubkeyToAddress(key3.PublicKey)
funds = new(big.Int).Mul(common.Big1, big.NewInt(params.Ether))
gspec = &core.Genesis{
Config: params.BorUnittestChainConfig,
Alloc: core.GenesisAlloc{
addr1: {Balance: funds},
addr2: {Balance: funds},
addr3: {Balance: funds},
// The address 0xAAAA sloads 0x00 and 0x01
aa: {
Code: []byte{
byte(vm.PC),
byte(vm.PC),
byte(vm.SLOAD),
byte(vm.SLOAD),
},
Nonce: 0,
Balance: big.NewInt(0),
},
},
}
)
gspec.Config.BerlinBlock = common.Big0
gspec.Config.LondonBlock = common.Big0
gspec.Config.Bor.BurntContract = map[string]string{
"0": "0x000000000000000000000000000000000000aaab",
"1": "0x000000000000000000000000000000000000aaac",
"2": "0x000000000000000000000000000000000000aaad",
"3": "0x000000000000000000000000000000000000aaae",
}
genesis := gspec.MustCommit(db)
signer := types.LatestSigner(gspec.Config)
blocks, _ := core.GenerateChain(gspec.Config, genesis, engine, db, 1, func(i int, b *core.BlockGen) {
b.SetCoinbase(common.Address{1})
// One transaction to 0xAAAA
accesses := types.AccessList{types.AccessTuple{
Address: aa,
StorageKeys: []common.Hash{{0}},
}}
txdata := &types.DynamicFeeTx{
ChainID: gspec.Config.ChainID,
Nonce: 0,
To: &aa,
Gas: 30000,
GasFeeCap: newGwei(5),
GasTipCap: big.NewInt(2),
AccessList: accesses,
Data: []byte{},
}
tx := types.NewTx(txdata)
tx, _ = types.SignTx(tx, signer, key1)
b.AddTx(tx)
})
diskdb := rawdb.NewMemoryDatabase()
gspec.MustCommit(diskdb)
chain, err := core.NewBlockChain(diskdb, nil, gspec, nil, engine, vm.Config{}, nil, nil, nil)
if err != nil {
t.Fatalf("failed to create tester chain: %v", err)
}
if n, err := chain.InsertChain(blocks); err != nil {
t.Fatalf("block %d: failed to insert into chain: %v", n, err)
}
block := chain.GetBlockByNumber(1)
// 1+2: Ensure EIP-1559 access lists are accounted for via gas usage.
expectedGas := params.TxGas + params.TxAccessListAddressGas + params.TxAccessListStorageKeyGas +
vm.GasQuickStep*2 + params.WarmStorageReadCostEIP2929 + params.ColdSloadCostEIP2929
if block.GasUsed() != expectedGas {
t.Fatalf("incorrect amount of gas spent: expected %d, got %d", expectedGas, block.GasUsed())
}
state, _ := chain.State()
// 3: Ensure that miner received only the tx's tip.
actual := state.GetBalance(block.Coinbase())
expected := new(big.Int).Add(
new(big.Int).SetUint64(block.GasUsed()*block.Transactions()[0].GasTipCap().Uint64()),
ethash.ConstantinopleBlockReward,
)
if actual.Cmp(expected) != 0 {
t.Fatalf("miner balance incorrect: expected %d, got %d", expected, actual)
}
// check burnt contract balance
actual = state.GetBalance(common.HexToAddress(gspec.Config.Bor.CalculateBurntContract(block.NumberU64())))
expected = new(big.Int).Mul(new(big.Int).SetUint64(block.GasUsed()), block.BaseFee())
if actual.Cmp(expected) != 0 {
t.Fatalf("burnt contract balance incorrect: expected %d, got %d", expected, actual)
}
// 4: Ensure the tx sender paid for the gasUsed * (tip + block baseFee).
actual = new(big.Int).Sub(funds, state.GetBalance(addr1))
expected = new(big.Int).SetUint64(block.GasUsed() * (block.Transactions()[0].GasTipCap().Uint64() + block.BaseFee().Uint64()))
if actual.Cmp(expected) != 0 {
t.Fatalf("sender balance incorrect: expected %d, got %d", expected, actual)
}
blocks, _ = core.GenerateChain(gspec.Config, block, engine, db, 1, func(i int, b *core.BlockGen) {
b.SetCoinbase(common.Address{2})
txdata := &types.LegacyTx{
Nonce: 0,
To: &aa,
Gas: 30000,
GasPrice: newGwei(5),
}
tx := types.NewTx(txdata)
tx, _ = types.SignTx(tx, signer, key2)
b.AddTx(tx)
})
if n, err := chain.InsertChain(blocks); err != nil {
t.Fatalf("block %d: failed to insert into chain: %v", n, err)
}
block = chain.GetBlockByNumber(2)
state, _ = chain.State()
effectiveTip := block.Transactions()[0].GasTipCap().Uint64() - block.BaseFee().Uint64()
// 6+5: Ensure that miner received only the tx's effective tip.
actual = state.GetBalance(block.Coinbase())
expected = new(big.Int).Add(
new(big.Int).SetUint64(block.GasUsed()*effectiveTip),
ethash.ConstantinopleBlockReward,
)
if actual.Cmp(expected) != 0 {
t.Fatalf("miner balance incorrect: expected %d, got %d", expected, actual)
}
// check burnt contract balance
actual = state.GetBalance(common.HexToAddress(gspec.Config.Bor.CalculateBurntContract(block.NumberU64())))
expected = new(big.Int).Mul(new(big.Int).SetUint64(block.GasUsed()), block.BaseFee())
if actual.Cmp(expected) != 0 {
t.Fatalf("burnt contract balance incorrect: expected %d, got %d", expected, actual)
}
// 4: Ensure the tx sender paid for the gasUsed * (effectiveTip + block baseFee).
actual = new(big.Int).Sub(funds, state.GetBalance(addr2))
expected = new(big.Int).SetUint64(block.GasUsed() * (effectiveTip + block.BaseFee().Uint64()))
if actual.Cmp(expected) != 0 {
t.Fatalf("sender balance incorrect: expected %d, got %d", expected, actual)
}
blocks, _ = core.GenerateChain(gspec.Config, block, engine, db, 1, func(i int, b *core.BlockGen) {
b.SetCoinbase(common.Address{3})
txdata := &types.LegacyTx{
Nonce: 0,
To: &aa,
Gas: 30000,
GasPrice: newGwei(5),
}
tx := types.NewTx(txdata)
tx, _ = types.SignTx(tx, signer, key3)
b.AddTx(tx)
})
if n, err := chain.InsertChain(blocks); err != nil {
t.Fatalf("block %d: failed to insert into chain: %v", n, err)
}
block = chain.GetBlockByNumber(3)
state, _ = chain.State()
effectiveTip = block.Transactions()[0].GasTipCap().Uint64() - block.BaseFee().Uint64()
// 6+5: Ensure that miner received only the tx's effective tip.
actual = state.GetBalance(block.Coinbase())
expected = new(big.Int).Add(
new(big.Int).SetUint64(block.GasUsed()*effectiveTip),
ethash.ConstantinopleBlockReward,
)
if actual.Cmp(expected) != 0 {
t.Fatalf("miner balance incorrect: expected %d, got %d", expected, actual)
}
// check burnt contract balance
actual = state.GetBalance(common.HexToAddress(gspec.Config.Bor.CalculateBurntContract(block.NumberU64())))
expected = new(big.Int).Mul(new(big.Int).SetUint64(block.GasUsed()), block.BaseFee())
if actual.Cmp(expected) != 0 {
t.Fatalf("burnt contract balance incorrect: expected %d, got %d", expected, actual)
}
// 4: Ensure the tx sender paid for the gasUsed * (effectiveTip + block baseFee).
actual = new(big.Int).Sub(funds, state.GetBalance(addr3))
expected = new(big.Int).SetUint64(block.GasUsed() * (effectiveTip + block.BaseFee().Uint64()))
if actual.Cmp(expected) != 0 {
t.Fatalf("sender balance incorrect: expected %d, got %d", expected, actual)
}
}
func TestBurnContractContractFetch(t *testing.T) {
config := params.BorUnittestChainConfig
config.Bor.BurntContract = map[string]string{
"10": "0x000000000000000000000000000000000000aaab",
"100": "0x000000000000000000000000000000000000aaad",
}
burnContractAddr10 := config.Bor.CalculateBurntContract(10)
burnContractAddr11 := config.Bor.CalculateBurntContract(11)
burnContractAddr99 := config.Bor.CalculateBurntContract(99)
burnContractAddr100 := config.Bor.CalculateBurntContract(100)
burnContractAddr101 := config.Bor.CalculateBurntContract(101)
if burnContractAddr10 != "0x000000000000000000000000000000000000aaab" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaab", burnContractAddr10)
}
if burnContractAddr11 != "0x000000000000000000000000000000000000aaab" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaab", burnContractAddr11)
}
if burnContractAddr99 != "0x000000000000000000000000000000000000aaab" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaab", burnContractAddr99)
}
if burnContractAddr100 != "0x000000000000000000000000000000000000aaad" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaad", burnContractAddr100)
}
if burnContractAddr101 != "0x000000000000000000000000000000000000aaad" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaad", burnContractAddr101)
}
config.Bor.BurntContract = map[string]string{
"10": "0x000000000000000000000000000000000000aaab",
"100": "0x000000000000000000000000000000000000aaad",
"1000": "0x000000000000000000000000000000000000aaae",
}
burnContractAddr10 = config.Bor.CalculateBurntContract(10)
burnContractAddr11 = config.Bor.CalculateBurntContract(11)
burnContractAddr99 = config.Bor.CalculateBurntContract(99)
burnContractAddr100 = config.Bor.CalculateBurntContract(100)
burnContractAddr101 = config.Bor.CalculateBurntContract(101)
burnContractAddr999 := config.Bor.CalculateBurntContract(999)
burnContractAddr1000 := config.Bor.CalculateBurntContract(1000)
burnContractAddr1001 := config.Bor.CalculateBurntContract(1001)
if burnContractAddr10 != "0x000000000000000000000000000000000000aaab" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaab", burnContractAddr10)
}
if burnContractAddr11 != "0x000000000000000000000000000000000000aaab" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaab", burnContractAddr11)
}
if burnContractAddr99 != "0x000000000000000000000000000000000000aaab" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaab", burnContractAddr99)
}
if burnContractAddr100 != "0x000000000000000000000000000000000000aaad" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaad", burnContractAddr100)
}
if burnContractAddr101 != "0x000000000000000000000000000000000000aaad" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaad", burnContractAddr101)
}
if burnContractAddr999 != "0x000000000000000000000000000000000000aaad" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaad", burnContractAddr999)
}
if burnContractAddr1000 != "0x000000000000000000000000000000000000aaae" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaae", burnContractAddr1000)
}
if burnContractAddr1001 != "0x000000000000000000000000000000000000aaae" {
t.Fatalf("incorrect burnt contract address: expected %s, got %s", "0x000000000000000000000000000000000000aaae", burnContractAddr1001)
}
}
// EIP1559 is not supported without EIP155. An error is expected
func TestEIP1559TransitionWithEIP155(t *testing.T) {
var (

View file

@ -302,7 +302,7 @@ var Forks = map[string]*params.ChainConfig{
ArrowGlacierBlock: big.NewInt(0),
MergeNetsplitBlock: big.NewInt(0),
TerminalTotalDifficulty: big.NewInt(0),
ShanghaiTime: u64(0),
ShanghaiBlock: big.NewInt(0),
Bor: params.BorUnittestChainConfig.Bor,
},
"MergeToShanghaiAtTime15k": {
@ -321,7 +321,7 @@ var Forks = map[string]*params.ChainConfig{
ArrowGlacierBlock: big.NewInt(0),
MergeNetsplitBlock: big.NewInt(0),
TerminalTotalDifficulty: big.NewInt(0),
ShanghaiTime: u64(15_000),
ShanghaiBlock: big.NewInt(0),
Bor: params.BorUnittestChainConfig.Bor,
},
"Cancun": {
@ -340,8 +340,8 @@ var Forks = map[string]*params.ChainConfig{
ArrowGlacierBlock: big.NewInt(0),
MergeNetsplitBlock: big.NewInt(0),
TerminalTotalDifficulty: big.NewInt(0),
ShanghaiTime: u64(0),
CancunTime: u64(0),
ShanghaiBlock: big.NewInt(0),
CancunBlock: big.NewInt(0),
},
}