diff --git a/cmd/evm/internal/t8ntool/transaction.go b/cmd/evm/internal/t8ntool/transaction.go
index 02e9db1bf6..5860ae7504 100644
--- a/cmd/evm/internal/t8ntool/transaction.go
+++ b/cmd/evm/internal/t8ntool/transaction.go
@@ -157,7 +157,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(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)
@@ -192,7 +192,7 @@ func Transaction(ctx *cli.Context) error {
}
// TODO marcello double check
// Check whether the init code size has been exceeded.
- if chainConfig.IsShanghai(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")
}
diff --git a/cmd/evm/internal/t8ntool/transition.go b/cmd/evm/internal/t8ntool/transition.go
index 952b30f08a..4ec3c7a081 100644
--- a/cmd/evm/internal/t8ntool/transition.go
+++ b/cmd/evm/internal/t8ntool/transition.go
@@ -286,7 +286,7 @@ func Transition(ctx *cli.Context) error {
}
}
// TODO marcello double check
- if chainConfig.IsShanghai(prestate.Env.Number) && 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"))
}
diff --git a/cmd/geth/config.go b/cmd/geth/config.go
index 5e2cf95642..62017dfe14 100644
--- a/cmd/geth/config.go
+++ b/cmd/geth/config.go
@@ -18,6 +18,7 @@ package main
import (
"fmt"
+ "math/big"
"os"
"time"
@@ -149,8 +150,8 @@ func makeFullNode(ctx *cli.Context) (*node.Node, ethapi.Backend) {
stack, cfg := makeConfigNode(ctx)
// TODO marcello double check
if ctx.IsSet(utils.OverrideShanghai.Name) {
- v := ctx.Uint64(utils.OverrideShanghai.Name)
- cfg.Eth.OverrideShanghai = &v
+ v := ctx.Int64(utils.OverrideShanghai.Name)
+ cfg.Eth.OverrideShanghai = new(big.Int).SetInt64(v)
}
backend, eth := utils.RegisterEthService(stack, &cfg.Eth)
diff --git a/consensus/beacon/consensus.go b/consensus/beacon/consensus.go
index dd09723800..4728527678 100644
--- a/consensus/beacon/consensus.go
+++ b/consensus/beacon/consensus.go
@@ -284,7 +284,7 @@ func (beacon *Beacon) verifyHeader(chain consensus.ChainHeaderReader, header, pa
}
// Verify existence / non-existence of withdrawalsHash.
// TODO marcello double check
- shanghai := chain.Config().IsShanghai(header.Time)
+ shanghai := chain.Config().IsShanghai(header.Number)
if shanghai && header.WithdrawalsHash == nil {
return errors.New("missing withdrawalsHash")
}
@@ -293,7 +293,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 excessDataGas
- cancun := chain.Config().IsCancun(header.Time)
+ cancun := chain.Config().IsCancun(header.Number)
if cancun && header.ExcessDataGas == nil {
return errors.New("missing excessDataGas")
}
@@ -392,7 +392,7 @@ func (beacon *Beacon) FinalizeAndAssemble(ctx context.Context, chain consensus.C
return beacon.ethone.FinalizeAndAssemble(ctx, chain, header, state, txs, uncles, receipts, nil)
}
// TODO marcello double check
- shanghai := chain.Config().IsShanghai(header.Time)
+ shanghai := chain.Config().IsShanghai(header.Number)
if shanghai {
// All blocks after Shanghai must include a withdrawals root.
if withdrawals == nil {
diff --git a/consensus/clique/clique.go b/consensus/clique/clique.go
index 1db06e121c..440d1073ab 100644
--- a/consensus/clique/clique.go
+++ b/consensus/clique/clique.go
@@ -309,11 +309,11 @@ func (c *Clique) verifyHeader(chain consensus.ChainHeaderReader, header *types.H
return fmt.Errorf("invalid gasLimit: have %v, max %v", header.GasLimit, params.MaxGasLimit)
}
// TODO marcello double check
- if chain.Config().IsShanghai(header.Time) {
+ if chain.Config().IsShanghai(header.Number) {
return fmt.Errorf("clique does not support shanghai fork")
}
- if chain.Config().IsCancun(header.Time) {
+ if chain.Config().IsCancun(header.Number) {
return fmt.Errorf("clique does not support cancun fork")
}
// All basic checks passed, verify cascading fields
diff --git a/consensus/ethash/consensus.go b/consensus/ethash/consensus.go
index 3a1b65984a..b61e35b59d 100644
--- a/consensus/ethash/consensus.go
+++ b/consensus/ethash/consensus.go
@@ -334,11 +334,11 @@ func (ethash *Ethash) verifyHeader(chain consensus.ChainHeaderReader, header, pa
return consensus.ErrInvalidNumber
}
// TODO marcello double check
- if chain.Config().IsShanghai(header.Time) {
+ if chain.Config().IsShanghai(header.Number) {
return fmt.Errorf("ethash does not support shanghai fork")
}
- if chain.Config().IsCancun(header.Time) {
+ if chain.Config().IsCancun(header.Number) {
return fmt.Errorf("ethash does not support cancun fork")
}
// Verify the engine specific seal securing the block
diff --git a/core/blockchain_test.go b/core/blockchain_test.go
index 09d15e1150..65e3bfde03 100644
--- a/core/blockchain_test.go
+++ b/core/blockchain_test.go
@@ -4680,7 +4680,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) {
diff --git a/core/chain_makers_test.go b/core/chain_makers_test.go
index cdbe86cca6..5202c23f24 100644
--- a/core/chain_makers_test.go
+++ b/core/chain_makers_test.go
@@ -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)
diff --git a/core/forkid/forkid_test.go b/core/forkid/forkid_test.go
index 2c2fbb2910..389c66e95b 100644
--- a/core/forkid/forkid_test.go
+++ b/core/forkid/forkid_test.go
@@ -119,7 +119,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
diff --git a/core/genesis.go b/core/genesis.go
index a6b2360983..4dec3e741d 100644
--- a/core/genesis.go
+++ b/core/genesis.go
@@ -298,7 +298,7 @@ func (e *GenesisMismatchError) Error() string {
// ChainOverrides contains the changes to chain config.
type ChainOverrides struct {
- OverrideShanghai *uint64
+ OverrideShanghai *big.Int
}
// SetupGenesisBlock writes or updates the genesis block in db.
@@ -328,7 +328,7 @@ func SetupGenesisBlockWithOverride(db ethdb.Database, triedb *trie.Database, gen
if config != nil {
// TODO marcello double check
if overrides != nil && overrides.OverrideShanghai != nil {
- config.ShanghaiTime = overrides.OverrideShanghai
+ config.ShanghaiBlock = overrides.OverrideShanghai
}
}
}
@@ -529,7 +529,7 @@ func (g *Genesis) ToBlock() *types.Block {
var withdrawals []*types.Withdrawal
- if g.Config != nil && g.Config.IsShanghai(g.Timestamp) {
+ if g.Config != nil && g.Config.IsShanghai(new(big.Int).SetUint64(g.Number)) {
head.WithdrawalsHash = &types.EmptyWithdrawalsHash
withdrawals = make([]*types.Withdrawal, 0)
}
diff --git a/core/state_processor.go b/core/state_processor.go
index 019849e867..a844870437 100644
--- a/core/state_processor.go
+++ b/core/state_processor.go
@@ -102,7 +102,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()
// TODO marcello double check
- if len(withdrawals) > 0 && !p.config.IsShanghai(block.Time()) {
+ if len(withdrawals) > 0 && !p.config.IsShanghai(block.Number()) {
return nil, nil, 0, fmt.Errorf("withdrawals before shanghai")
}
// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
diff --git a/core/state_processor_test.go b/core/state_processor_test.go
index 16dc09dedf..443af82525 100644
--- a/core/state_processor_test.go
+++ b/core/state_processor_test.go
@@ -365,8 +365,8 @@ func TestStateProcessorErrors(t *testing.T) {
TerminalTotalDifficulty: big.NewInt(0),
TerminalTotalDifficultyPassed: true,
// TODO marcello double check
- ShanghaiTime: u64(0),
- Bor: ¶ms.BorConfig{BurntContract: map[string]string{"0": "0x000000000000000000000000000000000000dead"}},
+ ShanghaiBlock: big.NewInt(0),
+ Bor: ¶ms.BorConfig{BurntContract: map[string]string{"0": "0x000000000000000000000000000000000000dead"}},
},
Alloc: GenesisAlloc{
common.HexToAddress("0x71562b71999873DB5b286dF957af199Ec94617F7"): GenesisAccount{
@@ -446,7 +446,7 @@ func GenerateBadBlock(parent *types.Block, engine consensus.Engine, txs types.Tr
header.BaseFee = misc.CalcBaseFee(config, parent.Header())
}
// TODO marcello double check
- if config.IsShanghai(header.Time) {
+ if config.IsShanghai(header.Number) {
header.WithdrawalsHash = &types.EmptyWithdrawalsHash
}
@@ -472,7 +472,7 @@ func GenerateBadBlock(parent *types.Block, engine consensus.Engine, txs types.Tr
header.Root = common.BytesToHash(hasher.Sum(nil))
// Assemble and return the final block for sealing
// TODO marcello double check
- if config.IsShanghai(header.Time) {
+ if config.IsShanghai(header.Number) {
return types.NewBlockWithWithdrawals(header, txs, nil, receipts, []*types.Withdrawal{}, trie.NewStackTrie(nil))
}
diff --git a/core/txpool/txpool.go b/core/txpool/txpool.go
index 9ced7c630d..d4638bbd47 100644
--- a/core/txpool/txpool.go
+++ b/core/txpool/txpool.go
@@ -1897,7 +1897,7 @@ func (pool *TxPool) reset(oldHead, newHead *types.Header) {
pool.istanbul.Store(pool.chainconfig.IsIstanbul(next))
pool.eip2718.Store(pool.chainconfig.IsBerlin(next))
pool.eip1559.Store(pool.chainconfig.IsLondon(next))
- pool.shanghai.Store(pool.chainconfig.IsShanghai(uint64(time.Now().Unix())))
+ pool.shanghai.Store(pool.chainconfig.IsShanghai(next))
}
// promoteExecutables moves transactions that have become processable from the
diff --git a/eth/catalyst/api.go b/eth/catalyst/api.go
index a6a0a08d2e..e667fc0cf0 100644
--- a/eth/catalyst/api.go
+++ b/eth/catalyst/api.go
@@ -165,46 +165,46 @@ func NewConsensusAPI(eth *eth.Ethereum) *ConsensusAPI {
//
// If there are payloadAttributes: we try to assemble a block with the payloadAttributes
// and return its payloadID.
-func (api *ConsensusAPI) ForkchoiceUpdatedV1(update engine.ForkchoiceStateV1, payloadAttributes *engine.PayloadAttributes) (engine.ForkChoiceResponse, error) {
- if payloadAttributes != nil {
- if payloadAttributes.Withdrawals != nil {
- return engine.STATUS_INVALID, engine.InvalidParams.With(fmt.Errorf("withdrawals not supported in V1"))
- }
+// func (api *ConsensusAPI) ForkchoiceUpdatedV1(update engine.ForkchoiceStateV1, payloadAttributes *engine.PayloadAttributes) (engine.ForkChoiceResponse, error) {
+// if payloadAttributes != nil {
+// if payloadAttributes.Withdrawals != nil {
+// return engine.STATUS_INVALID, engine.InvalidParams.With(fmt.Errorf("withdrawals not supported in V1"))
+// }
- if api.eth.BlockChain().Config().IsShanghai(payloadAttributes.Timestamp) {
- return engine.STATUS_INVALID, engine.InvalidParams.With(fmt.Errorf("forkChoiceUpdateV1 called post-shanghai"))
- }
- }
+// if api.eth.BlockChain().Config().IsShanghai(payloadAttributes.Timestamp) {
+// return engine.STATUS_INVALID, engine.InvalidParams.With(fmt.Errorf("forkChoiceUpdateV1 called post-shanghai"))
+// }
+// }
- return api.forkchoiceUpdated(update, payloadAttributes)
-}
+// return api.forkchoiceUpdated(update, payloadAttributes)
+// }
// ForkchoiceUpdatedV2 is equivalent to V1 with the addition of withdrawals in the payload attributes.
-func (api *ConsensusAPI) ForkchoiceUpdatedV2(update engine.ForkchoiceStateV1, payloadAttributes *engine.PayloadAttributes) (engine.ForkChoiceResponse, error) {
- if payloadAttributes != nil {
- if err := api.verifyPayloadAttributes(payloadAttributes); err != nil {
- return engine.STATUS_INVALID, engine.InvalidParams.With(err)
- }
- }
+// func (api *ConsensusAPI) ForkchoiceUpdatedV2(update engine.ForkchoiceStateV1, payloadAttributes *engine.PayloadAttributes) (engine.ForkChoiceResponse, error) {
+// if payloadAttributes != nil {
+// if err := api.verifyPayloadAttributes(payloadAttributes); err != nil {
+// return engine.STATUS_INVALID, engine.InvalidParams.With(err)
+// }
+// }
- return api.forkchoiceUpdated(update, payloadAttributes)
-}
+// return api.forkchoiceUpdated(update, payloadAttributes)
+// }
-func (api *ConsensusAPI) verifyPayloadAttributes(attr *engine.PayloadAttributes) error {
- if !api.eth.BlockChain().Config().IsShanghai(attr.Timestamp) {
- // Reject payload attributes with withdrawals before shanghai
- if attr.Withdrawals != nil {
- return errors.New("withdrawals before shanghai")
- }
- } else {
- // Reject payload attributes with nil withdrawals after shanghai
- if attr.Withdrawals == nil {
- return errors.New("missing withdrawals list")
- }
- }
+// func (api *ConsensusAPI) verifyPayloadAttributes(attr *engine.PayloadAttributes) error {
+// if !api.eth.BlockChain().Config().IsShanghai(attr.Timestamp) {
+// // Reject payload attributes with withdrawals before shanghai
+// if attr.Withdrawals != nil {
+// return errors.New("withdrawals before shanghai")
+// }
+// } else {
+// // Reject payload attributes with nil withdrawals after shanghai
+// if attr.Withdrawals == nil {
+// return errors.New("missing withdrawals list")
+// }
+// }
- return nil
-}
+// return nil
+// }
// nolint:gocognit
func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payloadAttributes *engine.PayloadAttributes) (engine.ForkChoiceResponse, error) {
@@ -454,18 +454,18 @@ func (api *ConsensusAPI) NewPayloadV1(params engine.ExecutableData) (engine.Payl
return api.newPayload(params)
}
-// 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(params.Timestamp) {
- if params.Withdrawals == nil {
- return engine.PayloadStatusV1{Status: engine.INVALID}, engine.InvalidParams.With(fmt.Errorf("nil withdrawals post-shanghai"))
- }
- } else if params.Withdrawals != nil {
- return engine.PayloadStatusV1{Status: engine.INVALID}, engine.InvalidParams.With(fmt.Errorf("non-nil withdrawals pre-shanghai"))
- }
+// // 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(params.Timestamp) {
+// if params.Withdrawals == nil {
+// return engine.PayloadStatusV1{Status: engine.INVALID}, engine.InvalidParams.With(fmt.Errorf("nil withdrawals post-shanghai"))
+// }
+// } else if params.Withdrawals != nil {
+// return engine.PayloadStatusV1{Status: engine.INVALID}, engine.InvalidParams.With(fmt.Errorf("non-nil withdrawals pre-shanghai"))
+// }
- return api.newPayload(params)
-}
+// return api.newPayload(params)
+// }
func (api *ConsensusAPI) newPayload(params engine.ExecutableData) (engine.PayloadStatusV1, error) {
// The locking here is, strictly, not required. Without these locks, this can happen:
diff --git a/eth/catalyst/api_test.go b/eth/catalyst/api_test.go
index 72be8ed121..b39ec115b1 100644
--- a/eth/catalyst/api_test.go
+++ b/eth/catalyst/api_test.go
@@ -17,22 +17,13 @@
package catalyst
import (
- "bytes"
- "context"
- crand "crypto/rand"
"fmt"
"math/big"
- "math/rand"
- "reflect"
- "sync"
"testing"
"time"
"github.com/ethereum/go-ethereum/beacon/engine"
"github.com/ethereum/go-ethereum/common"
- "github.com/ethereum/go-ethereum/common/hexutil"
- "github.com/ethereum/go-ethereum/consensus"
- beaconConsensus "github.com/ethereum/go-ethereum/consensus/beacon"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
@@ -40,11 +31,8 @@ import (
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/eth/downloader"
"github.com/ethereum/go-ethereum/eth/ethconfig"
- "github.com/ethereum/go-ethereum/miner"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p"
- "github.com/ethereum/go-ethereum/params"
- "github.com/ethereum/go-ethereum/rpc"
"github.com/ethereum/go-ethereum/trie"
)
@@ -58,194 +46,194 @@ var (
testBalance = big.NewInt(2e18)
)
-func generateMergeChain(n int, merged bool) (*core.Genesis, []*types.Block) {
- config := *params.AllEthashProtocolChanges
- engine := consensus.Engine(beaconConsensus.New(ethash.NewFaker()))
+// func generateMergeChain(n int, merged bool) (*core.Genesis, []*types.Block) {
+// config := *params.AllEthashProtocolChanges
+// engine := consensus.Engine(beaconConsensus.New(ethash.NewFaker()))
- if merged {
- config.TerminalTotalDifficulty = common.Big0
- config.TerminalTotalDifficultyPassed = true
- engine = beaconConsensus.NewFaker()
- }
+// if merged {
+// config.TerminalTotalDifficulty = common.Big0
+// config.TerminalTotalDifficultyPassed = true
+// engine = beaconConsensus.NewFaker()
+// }
- genesis := &core.Genesis{
- Config: &config,
- Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}},
- ExtraData: []byte("test genesis"),
- Timestamp: 9000,
- BaseFee: big.NewInt(params.InitialBaseFee),
- Difficulty: big.NewInt(0),
- }
- testNonce := uint64(0)
- generate := func(i int, g *core.BlockGen) {
- g.OffsetTime(5)
- g.SetExtra([]byte("test"))
+// genesis := &core.Genesis{
+// Config: &config,
+// Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}},
+// ExtraData: []byte("test genesis"),
+// Timestamp: 9000,
+// BaseFee: big.NewInt(params.InitialBaseFee),
+// Difficulty: big.NewInt(0),
+// }
+// testNonce := uint64(0)
+// generate := func(i int, g *core.BlockGen) {
+// g.OffsetTime(5)
+// g.SetExtra([]byte("test"))
- tx, _ := types.SignTx(types.NewTransaction(testNonce, common.HexToAddress("0x9a9070028361F7AAbeB3f2F2Dc07F82C4a98A02a"), big.NewInt(1), params.TxGas, big.NewInt(params.InitialBaseFee*2), nil), types.LatestSigner(&config), testKey)
- g.AddTx(tx)
+// tx, _ := types.SignTx(types.NewTransaction(testNonce, common.HexToAddress("0x9a9070028361F7AAbeB3f2F2Dc07F82C4a98A02a"), big.NewInt(1), params.TxGas, big.NewInt(params.InitialBaseFee*2), nil), types.LatestSigner(&config), testKey)
+// g.AddTx(tx)
- testNonce++
- }
- _, blocks, _ := core.GenerateChainWithGenesis(genesis, engine, n, generate)
+// testNonce++
+// }
+// _, blocks, _ := core.GenerateChainWithGenesis(genesis, engine, n, generate)
- if !merged {
- totalDifficulty := big.NewInt(0)
- for _, b := range blocks {
- totalDifficulty.Add(totalDifficulty, b.Difficulty())
- }
+// if !merged {
+// totalDifficulty := big.NewInt(0)
+// for _, b := range blocks {
+// totalDifficulty.Add(totalDifficulty, b.Difficulty())
+// }
- config.TerminalTotalDifficulty = totalDifficulty
- }
+// config.TerminalTotalDifficulty = totalDifficulty
+// }
- return genesis, blocks
-}
+// return genesis, blocks
+// }
-func TestEth2AssembleBlock(t *testing.T) {
- t.Skip("bor due to burn contract")
+// func TestEth2AssembleBlock(t *testing.T) {
+// t.Skip("bor due to burn contract")
- genesis, blocks := generateMergeChain(10, false)
+// genesis, blocks := generateMergeChain(10, false)
- n, ethservice := startEthService(t, genesis, blocks)
- defer n.Close()
+// n, ethservice := startEthService(t, genesis, blocks)
+// defer n.Close()
- api := NewConsensusAPI(ethservice)
- signer := types.NewEIP155Signer(ethservice.BlockChain().Config().ChainID)
+// api := NewConsensusAPI(ethservice)
+// signer := types.NewEIP155Signer(ethservice.BlockChain().Config().ChainID)
- tx, err := types.SignTx(types.NewTransaction(uint64(10), blocks[9].Coinbase(), big.NewInt(1000), params.TxGas, big.NewInt(params.InitialBaseFee), nil), signer, testKey)
- if err != nil {
- t.Fatalf("error signing transaction, err=%v", err)
- }
+// tx, err := types.SignTx(types.NewTransaction(uint64(10), blocks[9].Coinbase(), big.NewInt(1000), params.TxGas, big.NewInt(params.InitialBaseFee), nil), signer, testKey)
+// if err != nil {
+// t.Fatalf("error signing transaction, err=%v", err)
+// }
- ethservice.TxPool().AddLocal(tx)
+// ethservice.TxPool().AddLocal(tx)
- blockParams := engine.PayloadAttributes{
- Timestamp: blocks[9].Time() + 5,
- }
- // The miner needs to pick up on the txs in the pool, so a few retries might be
- // needed.
- if _, testErr := assembleWithTransactions(api, blocks[9].Hash(), &blockParams, 1); testErr != nil {
- t.Fatal(testErr)
- }
-}
+// blockParams := engine.PayloadAttributes{
+// Timestamp: blocks[9].Time() + 5,
+// }
+// // The miner needs to pick up on the txs in the pool, so a few retries might be
+// // needed.
+// if _, testErr := assembleWithTransactions(api, blocks[9].Hash(), &blockParams, 1); testErr != nil {
+// t.Fatal(testErr)
+// }
+// }
-// assembleWithTransactions tries to assemble a block, retrying until it has 'want',
-// number of transactions in it, or it has retried three times.
-func assembleWithTransactions(api *ConsensusAPI, parentHash common.Hash, params *engine.PayloadAttributes, want int) (execData *engine.ExecutableData, err error) {
- for retries := 3; retries > 0; retries-- {
- execData, err = assembleBlock(api, parentHash, params)
- if err != nil {
- return nil, err
- }
+// // assembleWithTransactions tries to assemble a block, retrying until it has 'want',
+// // number of transactions in it, or it has retried three times.
+// func assembleWithTransactions(api *ConsensusAPI, parentHash common.Hash, params *engine.PayloadAttributes, want int) (execData *engine.ExecutableData, err error) {
+// for retries := 3; retries > 0; retries-- {
+// execData, err = assembleBlock(api, parentHash, params)
+// if err != nil {
+// return nil, err
+// }
- if have, want := len(execData.Transactions), want; have != want {
- err = fmt.Errorf("invalid number of transactions, have %d want %d", have, want)
- continue
- }
+// if have, want := len(execData.Transactions), want; have != want {
+// err = fmt.Errorf("invalid number of transactions, have %d want %d", have, want)
+// continue
+// }
- return execData, nil
- }
+// return execData, nil
+// }
- return nil, err
-}
+// return nil, err
+// }
-func TestEth2AssembleBlockWithAnotherBlocksTxs(t *testing.T) {
- t.Skip("bor due to burn contract")
+// func TestEth2AssembleBlockWithAnotherBlocksTxs(t *testing.T) {
+// t.Skip("bor due to burn contract")
- genesis, blocks := generateMergeChain(10, false)
+// genesis, blocks := generateMergeChain(10, false)
- n, ethservice := startEthService(t, genesis, blocks[:9])
- defer n.Close()
+// n, ethservice := startEthService(t, genesis, blocks[:9])
+// defer n.Close()
- api := NewConsensusAPI(ethservice)
+// api := NewConsensusAPI(ethservice)
- // Put the 10th block's tx in the pool and produce a new block
- api.eth.TxPool().AddRemotesSync(blocks[9].Transactions())
+// // Put the 10th block's tx in the pool and produce a new block
+// api.eth.TxPool().AddRemotesSync(blocks[9].Transactions())
- blockParams := engine.PayloadAttributes{
- Timestamp: blocks[8].Time() + 5,
- }
- // The miner needs to pick up on the txs in the pool, so a few retries might be
- // needed.
- if _, err := assembleWithTransactions(api, blocks[8].Hash(), &blockParams, blocks[9].Transactions().Len()); err != nil {
- t.Fatal(err)
- }
-}
+// blockParams := engine.PayloadAttributes{
+// Timestamp: blocks[8].Time() + 5,
+// }
+// // The miner needs to pick up on the txs in the pool, so a few retries might be
+// // needed.
+// if _, err := assembleWithTransactions(api, blocks[8].Hash(), &blockParams, blocks[9].Transactions().Len()); err != nil {
+// t.Fatal(err)
+// }
+// }
-func TestSetHeadBeforeTotalDifficulty(t *testing.T) {
- genesis, blocks := generateMergeChain(10, false)
+// func TestSetHeadBeforeTotalDifficulty(t *testing.T) {
+// genesis, blocks := generateMergeChain(10, false)
- n, ethservice := startEthService(t, genesis, blocks)
- defer n.Close()
+// n, ethservice := startEthService(t, genesis, blocks)
+// defer n.Close()
- api := NewConsensusAPI(ethservice)
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: blocks[5].Hash(),
- SafeBlockHash: common.Hash{},
- FinalizedBlockHash: common.Hash{},
- }
+// api := NewConsensusAPI(ethservice)
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: blocks[5].Hash(),
+// SafeBlockHash: common.Hash{},
+// FinalizedBlockHash: common.Hash{},
+// }
- if resp, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
- t.Errorf("fork choice updated should not error: %v", err)
- } else if resp.PayloadStatus.Status != engine.INVALID_TERMINAL_BLOCK.Status {
- t.Errorf("fork choice updated before total terminal difficulty should be INVALID")
- }
-}
+// if resp, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
+// t.Errorf("fork choice updated should not error: %v", err)
+// } else if resp.PayloadStatus.Status != engine.INVALID_TERMINAL_BLOCK.Status {
+// t.Errorf("fork choice updated before total terminal difficulty should be INVALID")
+// }
+// }
-func TestEth2PrepareAndGetPayload(t *testing.T) {
- genesis, blocks := generateMergeChain(10, false)
- // We need to properly set the terminal total difficulty
- genesis.Config.TerminalTotalDifficulty.Sub(genesis.Config.TerminalTotalDifficulty, blocks[9].Difficulty())
- n, ethservice := startEthService(t, genesis, blocks[:9])
+// func TestEth2PrepareAndGetPayload(t *testing.T) {
+// genesis, blocks := generateMergeChain(10, false)
+// // We need to properly set the terminal total difficulty
+// genesis.Config.TerminalTotalDifficulty.Sub(genesis.Config.TerminalTotalDifficulty, blocks[9].Difficulty())
+// n, ethservice := startEthService(t, genesis, blocks[:9])
- defer n.Close()
+// defer n.Close()
- api := NewConsensusAPI(ethservice)
+// api := NewConsensusAPI(ethservice)
- // Put the 10th block's tx in the pool and produce a new block
- ethservice.TxPool().AddLocals(blocks[9].Transactions())
+// // Put the 10th block's tx in the pool and produce a new block
+// ethservice.TxPool().AddLocals(blocks[9].Transactions())
- blockParams := engine.PayloadAttributes{
- Timestamp: blocks[8].Time() + 5,
- }
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: blocks[8].Hash(),
- SafeBlockHash: common.Hash{},
- FinalizedBlockHash: common.Hash{},
- }
- _, err := api.ForkchoiceUpdatedV1(fcState, &blockParams)
+// blockParams := engine.PayloadAttributes{
+// Timestamp: blocks[8].Time() + 5,
+// }
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: blocks[8].Hash(),
+// SafeBlockHash: common.Hash{},
+// FinalizedBlockHash: common.Hash{},
+// }
+// _, err := api.ForkchoiceUpdatedV1(fcState, &blockParams)
- if err != nil {
- t.Fatalf("error preparing payload, err=%v", err)
- }
- // give the payload some time to be built
- time.Sleep(100 * time.Millisecond)
+// if err != nil {
+// t.Fatalf("error preparing payload, err=%v", err)
+// }
+// // give the payload some time to be built
+// time.Sleep(100 * time.Millisecond)
- payloadID := (&miner.BuildPayloadArgs{
- Parent: fcState.HeadBlockHash,
- Timestamp: blockParams.Timestamp,
- FeeRecipient: blockParams.SuggestedFeeRecipient,
- Random: blockParams.Random,
- }).Id()
- execData, err := api.GetPayloadV1(payloadID)
+// payloadID := (&miner.BuildPayloadArgs{
+// Parent: fcState.HeadBlockHash,
+// Timestamp: blockParams.Timestamp,
+// FeeRecipient: blockParams.SuggestedFeeRecipient,
+// Random: blockParams.Random,
+// }).Id()
+// execData, err := api.GetPayloadV1(payloadID)
- if err != nil {
- t.Fatalf("error getting payload, err=%v", err)
- }
+// if err != nil {
+// t.Fatalf("error getting payload, err=%v", err)
+// }
- if len(execData.Transactions) != blocks[9].Transactions().Len() {
- t.Fatalf("invalid number of transactions %d != 1", len(execData.Transactions))
- }
- // Test invalid payloadID
- var invPayload engine.PayloadID
+// if len(execData.Transactions) != blocks[9].Transactions().Len() {
+// t.Fatalf("invalid number of transactions %d != 1", len(execData.Transactions))
+// }
+// // Test invalid payloadID
+// var invPayload engine.PayloadID
- copy(invPayload[:], payloadID[:])
- invPayload[0] = ^invPayload[0]
- _, err = api.GetPayloadV1(invPayload)
+// copy(invPayload[:], payloadID[:])
+// invPayload[0] = ^invPayload[0]
+// _, err = api.GetPayloadV1(invPayload)
- if err == nil {
- t.Fatal("expected error retrieving invalid payload")
- }
-}
+// if err == nil {
+// t.Fatal("expected error retrieving invalid payload")
+// }
+// }
func checkLogEvents(t *testing.T, logsCh <-chan []*types.Log, rmLogsCh <-chan core.RemovedLogsEvent, wantNew, wantRemoved int) {
t.Helper()
@@ -267,174 +255,174 @@ func checkLogEvents(t *testing.T, logsCh <-chan []*types.Log, rmLogsCh <-chan co
}
}
-func TestInvalidPayloadTimestamp(t *testing.T) {
- genesis, preMergeBlocks := generateMergeChain(10, false)
+// func TestInvalidPayloadTimestamp(t *testing.T) {
+// genesis, preMergeBlocks := generateMergeChain(10, false)
- n, ethservice := startEthService(t, genesis, preMergeBlocks)
- defer n.Close()
+// n, ethservice := startEthService(t, genesis, preMergeBlocks)
+// defer n.Close()
- var (
- api = NewConsensusAPI(ethservice)
- parent = ethservice.BlockChain().CurrentBlock()
- )
+// var (
+// api = NewConsensusAPI(ethservice)
+// parent = ethservice.BlockChain().CurrentBlock()
+// )
- tests := []struct {
- time uint64
- shouldErr bool
- }{
- {0, true},
- {parent.Time, true},
- {parent.Time - 1, true},
+// tests := []struct {
+// time uint64
+// shouldErr bool
+// }{
+// {0, true},
+// {parent.Time, true},
+// {parent.Time - 1, true},
- // TODO (MariusVanDerWijden) following tests are currently broken,
- // fixed in upcoming merge-kiln-v2 pr
- //{parent.Time() + 1, false},
- //{uint64(time.Now().Unix()) + uint64(time.Minute), false},
- }
+// // TODO (MariusVanDerWijden) following tests are currently broken,
+// // fixed in upcoming merge-kiln-v2 pr
+// //{parent.Time() + 1, false},
+// //{uint64(time.Now().Unix()) + uint64(time.Minute), false},
+// }
- for i, test := range tests {
- t.Run(fmt.Sprintf("Timestamp test: %v", i), func(t *testing.T) {
- params := engine.PayloadAttributes{
- Timestamp: test.time,
- Random: crypto.Keccak256Hash([]byte{byte(123)}),
- SuggestedFeeRecipient: parent.Coinbase,
- }
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: parent.Hash(),
- SafeBlockHash: common.Hash{},
- FinalizedBlockHash: common.Hash{},
- }
+// for i, test := range tests {
+// t.Run(fmt.Sprintf("Timestamp test: %v", i), func(t *testing.T) {
+// params := engine.PayloadAttributes{
+// Timestamp: test.time,
+// Random: crypto.Keccak256Hash([]byte{byte(123)}),
+// SuggestedFeeRecipient: parent.Coinbase,
+// }
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: parent.Hash(),
+// SafeBlockHash: common.Hash{},
+// FinalizedBlockHash: common.Hash{},
+// }
- _, err := api.ForkchoiceUpdatedV1(fcState, ¶ms)
- if test.shouldErr && err == nil {
- t.Fatalf("expected error preparing payload with invalid timestamp, err=%v", err)
- } else if !test.shouldErr && err != nil {
- t.Fatalf("error preparing payload with valid timestamp, err=%v", err)
- }
- })
- }
-}
+// _, err := api.ForkchoiceUpdatedV1(fcState, ¶ms)
+// if test.shouldErr && err == nil {
+// t.Fatalf("expected error preparing payload with invalid timestamp, err=%v", err)
+// } else if !test.shouldErr && err != nil {
+// t.Fatalf("error preparing payload with valid timestamp, err=%v", err)
+// }
+// })
+// }
+// }
// nolint:goconst
-func TestEth2NewBlock(t *testing.T) {
- t.Skip("ETH2 in Bor")
+// func TestEth2NewBlock(t *testing.T) {
+// t.Skip("ETH2 in Bor")
- genesis, preMergeBlocks := generateMergeChain(10, false)
+// genesis, preMergeBlocks := generateMergeChain(10, false)
- n, ethservice := startEthService(t, genesis, preMergeBlocks)
- defer n.Close()
+// n, ethservice := startEthService(t, genesis, preMergeBlocks)
+// defer n.Close()
- var (
- api = NewConsensusAPI(ethservice)
- parent = preMergeBlocks[len(preMergeBlocks)-1]
+// var (
+// api = NewConsensusAPI(ethservice)
+// parent = preMergeBlocks[len(preMergeBlocks)-1]
- // This EVM code generates a log when the contract is created.
- logCode = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
- )
- // The event channels.
- newLogCh := make(chan []*types.Log, 10)
- rmLogsCh := make(chan core.RemovedLogsEvent, 10)
+// // This EVM code generates a log when the contract is created.
+// logCode = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
+// )
+// // The event channels.
+// newLogCh := make(chan []*types.Log, 10)
+// rmLogsCh := make(chan core.RemovedLogsEvent, 10)
- ethservice.BlockChain().SubscribeLogsEvent(newLogCh)
- ethservice.BlockChain().SubscribeRemovedLogsEvent(rmLogsCh)
+// ethservice.BlockChain().SubscribeLogsEvent(newLogCh)
+// ethservice.BlockChain().SubscribeRemovedLogsEvent(rmLogsCh)
- for i := 0; i < 10; i++ {
- statedb, _ := ethservice.BlockChain().StateAt(parent.Root())
- nonce := statedb.GetNonce(testAddr)
- tx, _ := types.SignTx(types.NewContractCreation(nonce, new(big.Int), 1000000, big.NewInt(2*params.InitialBaseFee), logCode), types.LatestSigner(ethservice.BlockChain().Config()), testKey)
- ethservice.TxPool().AddLocal(tx)
+// for i := 0; i < 10; i++ {
+// statedb, _ := ethservice.BlockChain().StateAt(parent.Root())
+// nonce := statedb.GetNonce(testAddr)
+// tx, _ := types.SignTx(types.NewContractCreation(nonce, new(big.Int), 1000000, big.NewInt(2*params.InitialBaseFee), logCode), types.LatestSigner(ethservice.BlockChain().Config()), testKey)
+// ethservice.TxPool().AddLocal(tx)
- execData, err := assembleWithTransactions(api, parent.Hash(), &engine.PayloadAttributes{
- Timestamp: parent.Time() + 5,
- }, 1)
- if err != nil {
- t.Fatalf("Failed to create the executable data %v", err)
- }
+// execData, err := assembleWithTransactions(api, parent.Hash(), &engine.PayloadAttributes{
+// Timestamp: parent.Time() + 5,
+// }, 1)
+// if err != nil {
+// t.Fatalf("Failed to create the executable data %v", err)
+// }
- block, err := engine.ExecutableDataToBlock(*execData)
- if err != nil {
- t.Fatalf("Failed to convert executable data to block %v", err)
- }
+// block, err := engine.ExecutableDataToBlock(*execData)
+// if err != nil {
+// t.Fatalf("Failed to convert executable data to block %v", err)
+// }
- newResp, err := api.NewPayloadV1(*execData)
+// newResp, err := api.NewPayloadV1(*execData)
- switch {
- case err != nil:
- t.Fatalf("Failed to insert block: %v", err)
- case newResp.Status != "VALID":
- t.Fatalf("Failed to insert block: %v", newResp.Status)
- case ethservice.BlockChain().CurrentBlock().Number.Uint64() != block.NumberU64()-1:
- t.Fatalf("Chain head shouldn't be updated")
- }
+// switch {
+// case err != nil:
+// t.Fatalf("Failed to insert block: %v", err)
+// case newResp.Status != "VALID":
+// t.Fatalf("Failed to insert block: %v", newResp.Status)
+// case ethservice.BlockChain().CurrentBlock().Number.Uint64() != block.NumberU64()-1:
+// t.Fatalf("Chain head shouldn't be updated")
+// }
- checkLogEvents(t, newLogCh, rmLogsCh, 0, 0)
+// checkLogEvents(t, newLogCh, rmLogsCh, 0, 0)
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: block.Hash(),
- SafeBlockHash: block.Hash(),
- FinalizedBlockHash: block.Hash(),
- }
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: block.Hash(),
+// SafeBlockHash: block.Hash(),
+// FinalizedBlockHash: block.Hash(),
+// }
- if _, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
- t.Fatalf("Failed to insert block: %v", err)
- }
+// if _, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
+// t.Fatalf("Failed to insert block: %v", err)
+// }
- if have, want := ethservice.BlockChain().CurrentBlock().Number.Uint64(), block.NumberU64(); have != want {
- t.Fatalf("Chain head should be updated, have %d want %d", have, want)
- }
+// if have, want := ethservice.BlockChain().CurrentBlock().Number.Uint64(), block.NumberU64(); have != want {
+// t.Fatalf("Chain head should be updated, have %d want %d", have, want)
+// }
- checkLogEvents(t, newLogCh, rmLogsCh, 1, 0)
+// checkLogEvents(t, newLogCh, rmLogsCh, 1, 0)
- parent = block
- }
+// parent = block
+// }
- // Introduce fork chain
- var (
- head = ethservice.BlockChain().CurrentBlock().Number.Uint64()
- )
+// // Introduce fork chain
+// var (
+// head = ethservice.BlockChain().CurrentBlock().Number.Uint64()
+// )
- parent = preMergeBlocks[len(preMergeBlocks)-1]
- for i := 0; i < 10; i++ {
- execData, err := assembleBlock(api, parent.Hash(), &engine.PayloadAttributes{
- Timestamp: parent.Time() + 6,
- })
+// parent = preMergeBlocks[len(preMergeBlocks)-1]
+// for i := 0; i < 10; i++ {
+// execData, err := assembleBlock(api, parent.Hash(), &engine.PayloadAttributes{
+// Timestamp: parent.Time() + 6,
+// })
- if err != nil {
- t.Fatalf("Failed to create the executable data %v", err)
- }
+// if err != nil {
+// t.Fatalf("Failed to create the executable data %v", err)
+// }
- block, err := engine.ExecutableDataToBlock(*execData)
+// block, err := engine.ExecutableDataToBlock(*execData)
- if err != nil {
- t.Fatalf("Failed to convert executable data to block %v", err)
- }
+// if err != nil {
+// t.Fatalf("Failed to convert executable data to block %v", err)
+// }
- newResp, err := api.NewPayloadV1(*execData)
- if err != nil || newResp.Status != "VALID" {
- t.Fatalf("Failed to insert block: %v", err)
- }
+// newResp, err := api.NewPayloadV1(*execData)
+// if err != nil || newResp.Status != "VALID" {
+// t.Fatalf("Failed to insert block: %v", err)
+// }
- if ethservice.BlockChain().CurrentBlock().Number.Uint64() != head {
- t.Fatalf("Chain head shouldn't be updated")
- }
+// if ethservice.BlockChain().CurrentBlock().Number.Uint64() != head {
+// t.Fatalf("Chain head shouldn't be updated")
+// }
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: block.Hash(),
- SafeBlockHash: block.Hash(),
- FinalizedBlockHash: block.Hash(),
- }
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: block.Hash(),
+// SafeBlockHash: block.Hash(),
+// FinalizedBlockHash: block.Hash(),
+// }
- if _, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
- t.Fatalf("Failed to insert block: %v", err)
- }
+// if _, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
+// t.Fatalf("Failed to insert block: %v", err)
+// }
- if ethservice.BlockChain().CurrentBlock().Number.Uint64() != block.NumberU64() {
- t.Fatalf("Chain head should be updated")
- }
+// if ethservice.BlockChain().CurrentBlock().Number.Uint64() != block.NumberU64() {
+// t.Fatalf("Chain head should be updated")
+// }
- parent, head = block, block.NumberU64()
- }
-}
+// parent, head = block, block.NumberU64()
+// }
+// }
func TestEth2DeepReorg(t *testing.T) {
// TODO (MariusVanDerWijden) TestEth2DeepReorg is currently broken, because it tries to reorg
@@ -518,126 +506,126 @@ func startEthService(t *testing.T, genesis *core.Genesis, blocks []*types.Block)
return n, ethservice
}
-func TestFullAPI(t *testing.T) {
- genesis, preMergeBlocks := generateMergeChain(10, false)
+// func TestFullAPI(t *testing.T) {
+// genesis, preMergeBlocks := generateMergeChain(10, false)
- n, ethservice := startEthService(t, genesis, preMergeBlocks)
- defer n.Close()
+// n, ethservice := startEthService(t, genesis, preMergeBlocks)
+// defer n.Close()
- var (
- parent = ethservice.BlockChain().CurrentBlock()
- // This EVM code generates a log when the contract is created.
- logCode = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
- )
+// var (
+// parent = ethservice.BlockChain().CurrentBlock()
+// // This EVM code generates a log when the contract is created.
+// logCode = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
+// )
- callback := func(parent *types.Header) {
- statedb, _ := ethservice.BlockChain().StateAt(parent.Root)
- nonce := statedb.GetNonce(testAddr)
- tx, _ := types.SignTx(types.NewContractCreation(nonce, new(big.Int), 1000000, big.NewInt(2*params.InitialBaseFee), logCode), types.LatestSigner(ethservice.BlockChain().Config()), testKey)
- ethservice.TxPool().AddLocal(tx)
- }
+// callback := func(parent *types.Header) {
+// statedb, _ := ethservice.BlockChain().StateAt(parent.Root)
+// nonce := statedb.GetNonce(testAddr)
+// tx, _ := types.SignTx(types.NewContractCreation(nonce, new(big.Int), 1000000, big.NewInt(2*params.InitialBaseFee), logCode), types.LatestSigner(ethservice.BlockChain().Config()), testKey)
+// ethservice.TxPool().AddLocal(tx)
+// }
- setupBlocks(t, ethservice, 10, parent, callback, nil)
-}
+// setupBlocks(t, ethservice, 10, parent, callback, nil)
+// }
// nolint:unparam,prealloc
-func setupBlocks(t *testing.T, ethservice *eth.Ethereum, n int, parent *types.Header, callback func(parent *types.Header), withdrawals [][]*types.Withdrawal) []*types.Header {
- t.Helper()
+// func setupBlocks(t *testing.T, ethservice *eth.Ethereum, n int, parent *types.Header, callback func(parent *types.Header), withdrawals [][]*types.Withdrawal) []*types.Header {
+// t.Helper()
- api := NewConsensusAPI(ethservice)
+// api := NewConsensusAPI(ethservice)
- var blocks []*types.Header
+// var blocks []*types.Header
- for i := 0; i < n; i++ {
- callback(parent)
+// for i := 0; i < n; i++ {
+// callback(parent)
- var w []*types.Withdrawal
+// var w []*types.Withdrawal
- if withdrawals != nil {
- w = withdrawals[i]
- }
+// if withdrawals != nil {
+// w = withdrawals[i]
+// }
- payload := getNewPayload(t, api, parent, w)
- execResp, err := api.NewPayloadV2(*payload)
+// payload := getNewPayload(t, api, parent, w)
+// execResp, err := api.NewPayloadV2(*payload)
- if err != nil {
- t.Fatalf("can't execute payload: %v", err)
- }
+// if err != nil {
+// t.Fatalf("can't execute payload: %v", err)
+// }
- if execResp.Status != engine.VALID {
- t.Fatalf("invalid status: %v", execResp.Status)
- }
+// if execResp.Status != engine.VALID {
+// t.Fatalf("invalid status: %v", execResp.Status)
+// }
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: payload.BlockHash,
- SafeBlockHash: payload.ParentHash,
- FinalizedBlockHash: payload.ParentHash,
- }
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: payload.BlockHash,
+// SafeBlockHash: payload.ParentHash,
+// FinalizedBlockHash: payload.ParentHash,
+// }
- if _, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
- t.Fatalf("Failed to insert block: %v", err)
- }
+// if _, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
+// t.Fatalf("Failed to insert block: %v", err)
+// }
- if ethservice.BlockChain().CurrentBlock().Number.Uint64() != payload.Number {
- t.Fatal("Chain head should be updated")
- }
+// if ethservice.BlockChain().CurrentBlock().Number.Uint64() != payload.Number {
+// t.Fatal("Chain head should be updated")
+// }
- if ethservice.BlockChain().CurrentFinalBlock().Number.Uint64() != payload.Number-1 {
- t.Fatal("Finalized block should be updated")
- }
+// if ethservice.BlockChain().CurrentFinalBlock().Number.Uint64() != payload.Number-1 {
+// t.Fatal("Finalized block should be updated")
+// }
- parent = ethservice.BlockChain().CurrentBlock()
- blocks = append(blocks, parent)
- }
+// parent = ethservice.BlockChain().CurrentBlock()
+// blocks = append(blocks, parent)
+// }
- return blocks
-}
+// return blocks
+// }
-func TestExchangeTransitionConfig(t *testing.T) {
- genesis, preMergeBlocks := generateMergeChain(10, false)
+// func TestExchangeTransitionConfig(t *testing.T) {
+// genesis, preMergeBlocks := generateMergeChain(10, false)
- n, ethservice := startEthService(t, genesis, preMergeBlocks)
- defer n.Close()
+// n, ethservice := startEthService(t, genesis, preMergeBlocks)
+// defer n.Close()
- // invalid ttd
- api := NewConsensusAPI(ethservice)
- config := engine.TransitionConfigurationV1{
- TerminalTotalDifficulty: (*hexutil.Big)(big.NewInt(0)),
- TerminalBlockHash: common.Hash{},
- TerminalBlockNumber: 0,
- }
+// // invalid ttd
+// api := NewConsensusAPI(ethservice)
+// config := engine.TransitionConfigurationV1{
+// TerminalTotalDifficulty: (*hexutil.Big)(big.NewInt(0)),
+// TerminalBlockHash: common.Hash{},
+// TerminalBlockNumber: 0,
+// }
- if _, err := api.ExchangeTransitionConfigurationV1(config); err == nil {
- t.Fatal("expected error on invalid config, invalid ttd")
- }
- // invalid terminal block hash
- config = engine.TransitionConfigurationV1{
- TerminalTotalDifficulty: (*hexutil.Big)(genesis.Config.TerminalTotalDifficulty),
- TerminalBlockHash: common.Hash{1},
- TerminalBlockNumber: 0,
- }
- if _, err := api.ExchangeTransitionConfigurationV1(config); err == nil {
- t.Fatal("expected error on invalid config, invalid hash")
- }
- // valid config
- config = engine.TransitionConfigurationV1{
- TerminalTotalDifficulty: (*hexutil.Big)(genesis.Config.TerminalTotalDifficulty),
- TerminalBlockHash: common.Hash{},
- TerminalBlockNumber: 0,
- }
- if _, err := api.ExchangeTransitionConfigurationV1(config); err != nil {
- t.Fatalf("expected no error on valid config, got %v", err)
- }
- // valid config
- config = engine.TransitionConfigurationV1{
- TerminalTotalDifficulty: (*hexutil.Big)(genesis.Config.TerminalTotalDifficulty),
- TerminalBlockHash: preMergeBlocks[5].Hash(),
- TerminalBlockNumber: 6,
- }
- if _, err := api.ExchangeTransitionConfigurationV1(config); err != nil {
- t.Fatalf("expected no error on valid config, got %v", err)
- }
-}
+// if _, err := api.ExchangeTransitionConfigurationV1(config); err == nil {
+// t.Fatal("expected error on invalid config, invalid ttd")
+// }
+// // invalid terminal block hash
+// config = engine.TransitionConfigurationV1{
+// TerminalTotalDifficulty: (*hexutil.Big)(genesis.Config.TerminalTotalDifficulty),
+// TerminalBlockHash: common.Hash{1},
+// TerminalBlockNumber: 0,
+// }
+// if _, err := api.ExchangeTransitionConfigurationV1(config); err == nil {
+// t.Fatal("expected error on invalid config, invalid hash")
+// }
+// // valid config
+// config = engine.TransitionConfigurationV1{
+// TerminalTotalDifficulty: (*hexutil.Big)(genesis.Config.TerminalTotalDifficulty),
+// TerminalBlockHash: common.Hash{},
+// TerminalBlockNumber: 0,
+// }
+// if _, err := api.ExchangeTransitionConfigurationV1(config); err != nil {
+// t.Fatalf("expected no error on valid config, got %v", err)
+// }
+// // valid config
+// config = engine.TransitionConfigurationV1{
+// TerminalTotalDifficulty: (*hexutil.Big)(genesis.Config.TerminalTotalDifficulty),
+// TerminalBlockHash: preMergeBlocks[5].Hash(),
+// TerminalBlockNumber: 6,
+// }
+// if _, err := api.ExchangeTransitionConfigurationV1(config); err != nil {
+// t.Fatalf("expected no error on valid config, got %v", err)
+// }
+// }
/*
TestNewPayloadOnInvalidChain sets up a valid chain and tries to feed blocks
@@ -656,207 +644,207 @@ We expect
│
└── P1''
*/
-func TestNewPayloadOnInvalidChain(t *testing.T) {
- t.Parallel()
+// func TestNewPayloadOnInvalidChain(t *testing.T) {
+// t.Parallel()
- genesis, preMergeBlocks := generateMergeChain(10, false)
- n, ethservice := startEthService(t, genesis, preMergeBlocks)
+// genesis, preMergeBlocks := generateMergeChain(10, false)
+// n, ethservice := startEthService(t, genesis, preMergeBlocks)
- defer n.Close()
+// defer n.Close()
- var (
- api = NewConsensusAPI(ethservice)
- parent = ethservice.BlockChain().CurrentBlock()
- signer = types.LatestSigner(ethservice.BlockChain().Config())
- // This EVM code generates a log when the contract is created.
- logCode = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
- )
+// var (
+// api = NewConsensusAPI(ethservice)
+// parent = ethservice.BlockChain().CurrentBlock()
+// signer = types.LatestSigner(ethservice.BlockChain().Config())
+// // This EVM code generates a log when the contract is created.
+// logCode = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
+// )
- for i := 0; i < 10; i++ {
- statedb, _ := ethservice.BlockChain().StateAt(parent.Root)
- tx := types.MustSignNewTx(testKey, signer, &types.LegacyTx{
- Nonce: statedb.GetNonce(testAddr),
- Value: new(big.Int),
- Gas: 1000000,
- GasPrice: big.NewInt(2 * params.InitialBaseFee),
- Data: logCode,
- })
- ethservice.TxPool().AddRemotesSync([]*types.Transaction{tx})
+// for i := 0; i < 10; i++ {
+// statedb, _ := ethservice.BlockChain().StateAt(parent.Root)
+// tx := types.MustSignNewTx(testKey, signer, &types.LegacyTx{
+// Nonce: statedb.GetNonce(testAddr),
+// Value: new(big.Int),
+// Gas: 1000000,
+// GasPrice: big.NewInt(2 * params.InitialBaseFee),
+// Data: logCode,
+// })
+// ethservice.TxPool().AddRemotesSync([]*types.Transaction{tx})
- var (
- params = engine.PayloadAttributes{
- Timestamp: parent.Time + 1,
- Random: crypto.Keccak256Hash([]byte{byte(i)}),
- SuggestedFeeRecipient: parent.Coinbase,
- }
- fcState = engine.ForkchoiceStateV1{
- HeadBlockHash: parent.Hash(),
- SafeBlockHash: common.Hash{},
- FinalizedBlockHash: common.Hash{},
- }
- payload *engine.ExecutableData
- resp engine.ForkChoiceResponse
- err error
- )
+// var (
+// params = engine.PayloadAttributes{
+// Timestamp: parent.Time + 1,
+// Random: crypto.Keccak256Hash([]byte{byte(i)}),
+// SuggestedFeeRecipient: parent.Coinbase,
+// }
+// fcState = engine.ForkchoiceStateV1{
+// HeadBlockHash: parent.Hash(),
+// SafeBlockHash: common.Hash{},
+// FinalizedBlockHash: common.Hash{},
+// }
+// payload *engine.ExecutableData
+// resp engine.ForkChoiceResponse
+// err error
+// )
- for i := 0; ; i++ {
- if resp, err = api.ForkchoiceUpdatedV1(fcState, ¶ms); err != nil {
- t.Fatalf("error preparing payload, err=%v", err)
- }
+// for i := 0; ; i++ {
+// if resp, err = api.ForkchoiceUpdatedV1(fcState, ¶ms); err != nil {
+// t.Fatalf("error preparing payload, err=%v", err)
+// }
- if resp.PayloadStatus.Status != engine.VALID {
- t.Fatalf("error preparing payload, invalid status: %v", resp.PayloadStatus.Status)
- }
+// if resp.PayloadStatus.Status != engine.VALID {
+// t.Fatalf("error preparing payload, invalid status: %v", resp.PayloadStatus.Status)
+// }
- // give the payload some time to be built
- time.Sleep(50 * time.Millisecond)
+// // give the payload some time to be built
+// time.Sleep(50 * time.Millisecond)
- if payload, err = api.GetPayloadV1(*resp.PayloadID); err != nil {
- t.Fatalf("can't get payload: %v", err)
- }
+// if payload, err = api.GetPayloadV1(*resp.PayloadID); err != nil {
+// t.Fatalf("can't get payload: %v", err)
+// }
- if len(payload.Transactions) > 0 {
- break
- }
+// if len(payload.Transactions) > 0 {
+// break
+// }
- // No luck this time we need to update the params and try again.
- params.Timestamp = params.Timestamp + 1
+// // No luck this time we need to update the params and try again.
+// params.Timestamp = params.Timestamp + 1
- if i > 10 {
- t.Fatalf("payload should not be empty")
- }
- }
+// if i > 10 {
+// t.Fatalf("payload should not be empty")
+// }
+// }
- execResp, err := api.NewPayloadV1(*payload)
+// execResp, err := api.NewPayloadV1(*payload)
- if err != nil {
- t.Fatalf("can't execute payload: %v", err)
- }
+// if err != nil {
+// t.Fatalf("can't execute payload: %v", err)
+// }
- if execResp.Status != engine.VALID {
- t.Fatalf("invalid status: %v", execResp.Status)
- }
+// if execResp.Status != engine.VALID {
+// t.Fatalf("invalid status: %v", execResp.Status)
+// }
- fcState = engine.ForkchoiceStateV1{
- HeadBlockHash: payload.BlockHash,
- SafeBlockHash: payload.ParentHash,
- FinalizedBlockHash: payload.ParentHash,
- }
+// fcState = engine.ForkchoiceStateV1{
+// HeadBlockHash: payload.BlockHash,
+// SafeBlockHash: payload.ParentHash,
+// FinalizedBlockHash: payload.ParentHash,
+// }
- if _, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
- t.Fatalf("Failed to insert block: %v", err)
- }
+// if _, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
+// t.Fatalf("Failed to insert block: %v", err)
+// }
- if ethservice.BlockChain().CurrentBlock().Number.Uint64() != payload.Number {
- t.Fatalf("Chain head should be updated")
- }
+// if ethservice.BlockChain().CurrentBlock().Number.Uint64() != payload.Number {
+// t.Fatalf("Chain head should be updated")
+// }
- parent = ethservice.BlockChain().CurrentBlock()
- }
-}
+// parent = ethservice.BlockChain().CurrentBlock()
+// }
+// }
-func assembleBlock(api *ConsensusAPI, parentHash common.Hash, params *engine.PayloadAttributes) (*engine.ExecutableData, error) {
- args := &miner.BuildPayloadArgs{
- Parent: parentHash,
- Timestamp: params.Timestamp,
- FeeRecipient: params.SuggestedFeeRecipient,
- Random: params.Random,
- Withdrawals: params.Withdrawals,
- }
- payload, err := api.eth.Miner().BuildPayload(args)
+// func assembleBlock(api *ConsensusAPI, parentHash common.Hash, params *engine.PayloadAttributes) (*engine.ExecutableData, error) {
+// args := &miner.BuildPayloadArgs{
+// Parent: parentHash,
+// Timestamp: params.Timestamp,
+// FeeRecipient: params.SuggestedFeeRecipient,
+// Random: params.Random,
+// Withdrawals: params.Withdrawals,
+// }
+// payload, err := api.eth.Miner().BuildPayload(args)
- if err != nil {
- return nil, err
- }
+// if err != nil {
+// return nil, err
+// }
- return payload.ResolveFull().ExecutionPayload, nil
-}
+// return payload.ResolveFull().ExecutionPayload, nil
+// }
-func TestEmptyBlocks(t *testing.T) {
- t.Parallel()
+// func TestEmptyBlocks(t *testing.T) {
+// t.Parallel()
- genesis, preMergeBlocks := generateMergeChain(10, false)
- n, ethservice := startEthService(t, genesis, preMergeBlocks)
+// genesis, preMergeBlocks := generateMergeChain(10, false)
+// n, ethservice := startEthService(t, genesis, preMergeBlocks)
- defer n.Close()
+// defer n.Close()
- commonAncestor := ethservice.BlockChain().CurrentBlock()
- api := NewConsensusAPI(ethservice)
+// commonAncestor := ethservice.BlockChain().CurrentBlock()
+// api := NewConsensusAPI(ethservice)
- // Setup 10 blocks on the canonical chain
- setupBlocks(t, ethservice, 10, commonAncestor, func(parent *types.Header) {}, nil)
+// // Setup 10 blocks on the canonical chain
+// setupBlocks(t, ethservice, 10, commonAncestor, func(parent *types.Header) {}, nil)
- // (1) check LatestValidHash by sending a normal payload (P1'')
- payload := getNewPayload(t, api, commonAncestor, nil)
+// // (1) check LatestValidHash by sending a normal payload (P1'')
+// payload := getNewPayload(t, api, commonAncestor, nil)
- status, err := api.NewPayloadV1(*payload)
- if err != nil {
- t.Fatal(err)
- }
+// status, err := api.NewPayloadV1(*payload)
+// if err != nil {
+// t.Fatal(err)
+// }
- if status.Status != engine.VALID {
- t.Errorf("invalid status: expected VALID got: %v", status.Status)
- }
+// if status.Status != engine.VALID {
+// t.Errorf("invalid status: expected VALID got: %v", status.Status)
+// }
- if !bytes.Equal(status.LatestValidHash[:], payload.BlockHash[:]) {
- t.Fatalf("invalid LVH: got %v want %v", status.LatestValidHash, payload.BlockHash)
- }
+// if !bytes.Equal(status.LatestValidHash[:], payload.BlockHash[:]) {
+// t.Fatalf("invalid LVH: got %v want %v", status.LatestValidHash, payload.BlockHash)
+// }
- // (2) Now send P1' which is invalid
- payload = getNewPayload(t, api, commonAncestor, nil)
- payload.GasUsed += 1
- payload = setBlockhash(payload)
- // Now latestValidHash should be the common ancestor
- status, err = api.NewPayloadV1(*payload)
- if err != nil {
- t.Fatal(err)
- }
+// // (2) Now send P1' which is invalid
+// payload = getNewPayload(t, api, commonAncestor, nil)
+// payload.GasUsed += 1
+// payload = setBlockhash(payload)
+// // Now latestValidHash should be the common ancestor
+// status, err = api.NewPayloadV1(*payload)
+// if err != nil {
+// t.Fatal(err)
+// }
- if status.Status != engine.INVALID {
- t.Errorf("invalid status: expected INVALID got: %v", status.Status)
- }
- // Expect 0x0 on INVALID block on top of PoW block
- expected := common.Hash{}
- if !bytes.Equal(status.LatestValidHash[:], expected[:]) {
- t.Fatalf("invalid LVH: got %v want %v", status.LatestValidHash, expected)
- }
+// if status.Status != engine.INVALID {
+// t.Errorf("invalid status: expected INVALID got: %v", status.Status)
+// }
+// // Expect 0x0 on INVALID block on top of PoW block
+// expected := common.Hash{}
+// if !bytes.Equal(status.LatestValidHash[:], expected[:]) {
+// t.Fatalf("invalid LVH: got %v want %v", status.LatestValidHash, expected)
+// }
- // (3) Now send a payload with unknown parent
- payload = getNewPayload(t, api, commonAncestor, nil)
- payload.ParentHash = common.Hash{1}
- payload = setBlockhash(payload)
- // Now latestValidHash should be the common ancestor
- status, err = api.NewPayloadV1(*payload)
- if err != nil {
- t.Fatal(err)
- }
+// // (3) Now send a payload with unknown parent
+// payload = getNewPayload(t, api, commonAncestor, nil)
+// payload.ParentHash = common.Hash{1}
+// payload = setBlockhash(payload)
+// // Now latestValidHash should be the common ancestor
+// status, err = api.NewPayloadV1(*payload)
+// if err != nil {
+// t.Fatal(err)
+// }
- if status.Status != engine.SYNCING {
- t.Errorf("invalid status: expected SYNCING got: %v", status.Status)
- }
+// if status.Status != engine.SYNCING {
+// t.Errorf("invalid status: expected SYNCING got: %v", status.Status)
+// }
- if status.LatestValidHash != nil {
- t.Fatalf("invalid LVH: got %v wanted nil", status.LatestValidHash)
- }
-}
+// if status.LatestValidHash != nil {
+// t.Fatalf("invalid LVH: got %v wanted nil", status.LatestValidHash)
+// }
+// }
-func getNewPayload(t *testing.T, api *ConsensusAPI, parent *types.Header, withdrawals []*types.Withdrawal) *engine.ExecutableData {
- t.Helper()
+// func getNewPayload(t *testing.T, api *ConsensusAPI, parent *types.Header, withdrawals []*types.Withdrawal) *engine.ExecutableData {
+// t.Helper()
- params := engine.PayloadAttributes{
- Timestamp: parent.Time + 1,
- Random: crypto.Keccak256Hash([]byte{byte(1)}),
- SuggestedFeeRecipient: parent.Coinbase,
- Withdrawals: withdrawals,
- }
+// params := engine.PayloadAttributes{
+// Timestamp: parent.Time + 1,
+// Random: crypto.Keccak256Hash([]byte{byte(1)}),
+// SuggestedFeeRecipient: parent.Coinbase,
+// Withdrawals: withdrawals,
+// }
- payload, err := assembleBlock(api, parent.Hash(), ¶ms)
- if err != nil {
- t.Fatal(err)
- }
+// payload, err := assembleBlock(api, parent.Hash(), ¶ms)
+// if err != nil {
+// t.Fatal(err)
+// }
- return payload
-}
+// return payload
+// }
// setBlockhash sets the blockhash of a modified ExecutableData.
// Can be used to make modified payloads look valid.
@@ -903,811 +891,811 @@ func decodeTransactions(enc [][]byte) ([]*types.Transaction, error) {
return txs, nil
}
-func TestTrickRemoteBlockCache(t *testing.T) {
- t.Parallel()
+// func TestTrickRemoteBlockCache(t *testing.T) {
+// t.Parallel()
- // Setup two nodes
- genesis, preMergeBlocks := generateMergeChain(10, false)
- nodeA, ethserviceA := startEthService(t, genesis, preMergeBlocks)
- nodeB, ethserviceB := startEthService(t, genesis, preMergeBlocks)
+// // Setup two nodes
+// genesis, preMergeBlocks := generateMergeChain(10, false)
+// nodeA, ethserviceA := startEthService(t, genesis, preMergeBlocks)
+// nodeB, ethserviceB := startEthService(t, genesis, preMergeBlocks)
- defer nodeA.Close()
- defer nodeB.Close()
+// defer nodeA.Close()
+// defer nodeB.Close()
- for nodeB.Server().NodeInfo().Ports.Listener == 0 {
- time.Sleep(250 * time.Millisecond)
- }
- nodeA.Server().AddPeer(nodeB.Server().Self())
- nodeB.Server().AddPeer(nodeA.Server().Self())
+// for nodeB.Server().NodeInfo().Ports.Listener == 0 {
+// time.Sleep(250 * time.Millisecond)
+// }
+// nodeA.Server().AddPeer(nodeB.Server().Self())
+// nodeB.Server().AddPeer(nodeA.Server().Self())
- apiA := NewConsensusAPI(ethserviceA)
- apiB := NewConsensusAPI(ethserviceB)
+// apiA := NewConsensusAPI(ethserviceA)
+// apiB := NewConsensusAPI(ethserviceB)
- commonAncestor := ethserviceA.BlockChain().CurrentBlock()
+// commonAncestor := ethserviceA.BlockChain().CurrentBlock()
- // Setup 10 blocks on the canonical chain
- setupBlocks(t, ethserviceA, 10, commonAncestor, func(parent *types.Header) {}, nil)
- commonAncestor = ethserviceA.BlockChain().CurrentBlock()
+// // Setup 10 blocks on the canonical chain
+// setupBlocks(t, ethserviceA, 10, commonAncestor, func(parent *types.Header) {}, nil)
+// commonAncestor = ethserviceA.BlockChain().CurrentBlock()
- // nolint:prealloc
- var invalidChain []*engine.ExecutableData
- // create a valid payload (P1)
- //payload1 := getNewPayload(t, apiA, commonAncestor)
- //invalidChain = append(invalidChain, payload1)
+// // nolint:prealloc
+// var invalidChain []*engine.ExecutableData
+// // create a valid payload (P1)
+// //payload1 := getNewPayload(t, apiA, commonAncestor)
+// //invalidChain = append(invalidChain, payload1)
- // create an invalid payload2 (P2)
- payload2 := getNewPayload(t, apiA, commonAncestor, nil)
- //payload2.ParentHash = payload1.BlockHash
- payload2.GasUsed += 1
- payload2 = setBlockhash(payload2)
- invalidChain = append(invalidChain, payload2)
+// // create an invalid payload2 (P2)
+// payload2 := getNewPayload(t, apiA, commonAncestor, nil)
+// //payload2.ParentHash = payload1.BlockHash
+// payload2.GasUsed += 1
+// payload2 = setBlockhash(payload2)
+// invalidChain = append(invalidChain, payload2)
- head := payload2
- // create some valid payloads on top
- for i := 0; i < 10; i++ {
- payload := getNewPayload(t, apiA, commonAncestor, nil)
- payload.ParentHash = head.BlockHash
- payload = setBlockhash(payload)
- invalidChain = append(invalidChain, payload)
- head = payload
- }
+// head := payload2
+// // create some valid payloads on top
+// for i := 0; i < 10; i++ {
+// payload := getNewPayload(t, apiA, commonAncestor, nil)
+// payload.ParentHash = head.BlockHash
+// payload = setBlockhash(payload)
+// invalidChain = append(invalidChain, payload)
+// head = payload
+// }
- // feed the payloads to node B
- for _, payload := range invalidChain {
- status, err := apiB.NewPayloadV1(*payload)
- if err != nil {
- panic(err)
- }
+// // feed the payloads to node B
+// for _, payload := range invalidChain {
+// status, err := apiB.NewPayloadV1(*payload)
+// if err != nil {
+// panic(err)
+// }
- if status.Status == engine.VALID {
- t.Error("invalid status: VALID on an invalid chain")
- }
- // Now reorg to the head of the invalid chain
- resp, err := apiB.ForkchoiceUpdatedV1(engine.ForkchoiceStateV1{HeadBlockHash: payload.BlockHash, SafeBlockHash: payload.BlockHash, FinalizedBlockHash: payload.ParentHash}, nil)
- if err != nil {
- t.Fatal(err)
- }
+// if status.Status == engine.VALID {
+// t.Error("invalid status: VALID on an invalid chain")
+// }
+// // Now reorg to the head of the invalid chain
+// resp, err := apiB.ForkchoiceUpdatedV1(engine.ForkchoiceStateV1{HeadBlockHash: payload.BlockHash, SafeBlockHash: payload.BlockHash, FinalizedBlockHash: payload.ParentHash}, nil)
+// if err != nil {
+// t.Fatal(err)
+// }
- if resp.PayloadStatus.Status == engine.VALID {
- t.Error("invalid status: VALID on an invalid chain")
- }
+// if resp.PayloadStatus.Status == engine.VALID {
+// t.Error("invalid status: VALID on an invalid chain")
+// }
- time.Sleep(100 * time.Millisecond)
- }
-}
+// time.Sleep(100 * time.Millisecond)
+// }
+// }
-func TestInvalidBloom(t *testing.T) {
- t.Parallel()
+// func TestInvalidBloom(t *testing.T) {
+// t.Parallel()
- genesis, preMergeBlocks := generateMergeChain(10, false)
- n, ethservice := startEthService(t, genesis, preMergeBlocks)
- ethservice.Merger().ReachTTD()
+// genesis, preMergeBlocks := generateMergeChain(10, false)
+// n, ethservice := startEthService(t, genesis, preMergeBlocks)
+// ethservice.Merger().ReachTTD()
- defer n.Close()
+// defer n.Close()
- commonAncestor := ethservice.BlockChain().CurrentBlock()
- api := NewConsensusAPI(ethservice)
+// commonAncestor := ethservice.BlockChain().CurrentBlock()
+// api := NewConsensusAPI(ethservice)
- // Setup 10 blocks on the canonical chain
- setupBlocks(t, ethservice, 10, commonAncestor, func(parent *types.Header) {}, nil)
+// // Setup 10 blocks on the canonical chain
+// setupBlocks(t, ethservice, 10, commonAncestor, func(parent *types.Header) {}, nil)
- // (1) check LatestValidHash by sending a normal payload (P1'')
- payload := getNewPayload(t, api, commonAncestor, nil)
- payload.LogsBloom = append(payload.LogsBloom, byte(1))
- status, err := api.NewPayloadV1(*payload)
+// // (1) check LatestValidHash by sending a normal payload (P1'')
+// payload := getNewPayload(t, api, commonAncestor, nil)
+// payload.LogsBloom = append(payload.LogsBloom, byte(1))
+// status, err := api.NewPayloadV1(*payload)
- if err != nil {
- t.Fatal(err)
- }
+// if err != nil {
+// t.Fatal(err)
+// }
- if status.Status != engine.INVALID {
- t.Errorf("invalid status: expected INVALID got: %v", status.Status)
- }
-}
+// if status.Status != engine.INVALID {
+// t.Errorf("invalid status: expected INVALID got: %v", status.Status)
+// }
+// }
-func TestNewPayloadOnInvalidTerminalBlock(t *testing.T) {
- t.Parallel()
+// func TestNewPayloadOnInvalidTerminalBlock(t *testing.T) {
+// t.Parallel()
- genesis, preMergeBlocks := generateMergeChain(100, false)
- n, ethservice := startEthService(t, genesis, preMergeBlocks)
+// genesis, preMergeBlocks := generateMergeChain(100, false)
+// n, ethservice := startEthService(t, genesis, preMergeBlocks)
- defer n.Close()
+// defer n.Close()
- api := NewConsensusAPI(ethservice)
+// api := NewConsensusAPI(ethservice)
- // Test parent already post TTD in FCU
- parent := preMergeBlocks[len(preMergeBlocks)-2]
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: parent.Hash(),
- SafeBlockHash: common.Hash{},
- FinalizedBlockHash: common.Hash{},
- }
- resp, err := api.ForkchoiceUpdatedV1(fcState, nil)
+// // Test parent already post TTD in FCU
+// parent := preMergeBlocks[len(preMergeBlocks)-2]
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: parent.Hash(),
+// SafeBlockHash: common.Hash{},
+// FinalizedBlockHash: common.Hash{},
+// }
+// resp, err := api.ForkchoiceUpdatedV1(fcState, nil)
- if err != nil {
- t.Fatalf("error sending forkchoice, err=%v", err)
- }
+// if err != nil {
+// t.Fatalf("error sending forkchoice, err=%v", err)
+// }
- if resp.PayloadStatus != engine.INVALID_TERMINAL_BLOCK {
- t.Fatalf("error sending invalid forkchoice, invalid status: %v", resp.PayloadStatus.Status)
- }
+// if resp.PayloadStatus != engine.INVALID_TERMINAL_BLOCK {
+// t.Fatalf("error sending invalid forkchoice, invalid status: %v", resp.PayloadStatus.Status)
+// }
- // Test parent already post TTD in NewPayload
- args := &miner.BuildPayloadArgs{
- Parent: parent.Hash(),
- Timestamp: parent.Time() + 1,
- Random: crypto.Keccak256Hash([]byte{byte(1)}),
- FeeRecipient: parent.Coinbase(),
- }
- payload, err := api.eth.Miner().BuildPayload(args)
+// // Test parent already post TTD in NewPayload
+// args := &miner.BuildPayloadArgs{
+// Parent: parent.Hash(),
+// Timestamp: parent.Time() + 1,
+// Random: crypto.Keccak256Hash([]byte{byte(1)}),
+// FeeRecipient: parent.Coinbase(),
+// }
+// payload, err := api.eth.Miner().BuildPayload(args)
- if err != nil {
- t.Fatalf("error preparing payload, err=%v", err)
- }
+// if err != nil {
+// t.Fatalf("error preparing payload, err=%v", err)
+// }
- data := *payload.Resolve().ExecutionPayload
- // We need to recompute the blockhash, since the miner computes a wrong (correct) blockhash
- txs, _ := decodeTransactions(data.Transactions)
- header := &types.Header{
- ParentHash: data.ParentHash,
- UncleHash: types.EmptyUncleHash,
- Coinbase: data.FeeRecipient,
- Root: data.StateRoot,
- TxHash: types.DeriveSha(types.Transactions(txs), trie.NewStackTrie(nil)),
- ReceiptHash: data.ReceiptsRoot,
- Bloom: types.BytesToBloom(data.LogsBloom),
- Difficulty: common.Big0,
- Number: new(big.Int).SetUint64(data.Number),
- GasLimit: data.GasLimit,
- GasUsed: data.GasUsed,
- Time: data.Timestamp,
- BaseFee: data.BaseFeePerGas,
- Extra: data.ExtraData,
- MixDigest: data.Random,
- }
- block := types.NewBlockWithHeader(header).WithBody(txs, nil /* uncles */)
- data.BlockHash = block.Hash()
- // Send the new payload
- resp2, err := api.NewPayloadV1(data)
- if err != nil {
- t.Fatalf("error sending NewPayload, err=%v", err)
- }
+// data := *payload.Resolve().ExecutionPayload
+// // We need to recompute the blockhash, since the miner computes a wrong (correct) blockhash
+// txs, _ := decodeTransactions(data.Transactions)
+// header := &types.Header{
+// ParentHash: data.ParentHash,
+// UncleHash: types.EmptyUncleHash,
+// Coinbase: data.FeeRecipient,
+// Root: data.StateRoot,
+// TxHash: types.DeriveSha(types.Transactions(txs), trie.NewStackTrie(nil)),
+// ReceiptHash: data.ReceiptsRoot,
+// Bloom: types.BytesToBloom(data.LogsBloom),
+// Difficulty: common.Big0,
+// Number: new(big.Int).SetUint64(data.Number),
+// GasLimit: data.GasLimit,
+// GasUsed: data.GasUsed,
+// Time: data.Timestamp,
+// BaseFee: data.BaseFeePerGas,
+// Extra: data.ExtraData,
+// MixDigest: data.Random,
+// }
+// block := types.NewBlockWithHeader(header).WithBody(txs, nil /* uncles */)
+// data.BlockHash = block.Hash()
+// // Send the new payload
+// resp2, err := api.NewPayloadV1(data)
+// if err != nil {
+// t.Fatalf("error sending NewPayload, err=%v", err)
+// }
- if resp2 != engine.INVALID_TERMINAL_BLOCK {
- t.Fatalf("error sending invalid forkchoice, invalid status: %v", resp.PayloadStatus.Status)
- }
-}
+// if resp2 != engine.INVALID_TERMINAL_BLOCK {
+// t.Fatalf("error sending invalid forkchoice, invalid status: %v", resp.PayloadStatus.Status)
+// }
+// }
-// TestSimultaneousNewBlock does several parallel inserts, both as
-// newPayLoad and forkchoiceUpdate. This is to test that the api behaves
-// well even of the caller is not being 'serial'.
-func TestSimultaneousNewBlock(t *testing.T) {
- t.Parallel()
+// // TestSimultaneousNewBlock does several parallel inserts, both as
+// // newPayLoad and forkchoiceUpdate. This is to test that the api behaves
+// // well even of the caller is not being 'serial'.
+// func TestSimultaneousNewBlock(t *testing.T) {
+// t.Parallel()
- genesis, preMergeBlocks := generateMergeChain(10, false)
- n, ethservice := startEthService(t, genesis, preMergeBlocks)
+// genesis, preMergeBlocks := generateMergeChain(10, false)
+// n, ethservice := startEthService(t, genesis, preMergeBlocks)
- defer n.Close()
+// defer n.Close()
- var (
- api = NewConsensusAPI(ethservice)
- parent = preMergeBlocks[len(preMergeBlocks)-1]
- )
+// var (
+// api = NewConsensusAPI(ethservice)
+// parent = preMergeBlocks[len(preMergeBlocks)-1]
+// )
- for i := 0; i < 10; i++ {
- execData, err := assembleBlock(api, parent.Hash(), &engine.PayloadAttributes{
- Timestamp: parent.Time() + 5,
- })
- if err != nil {
- t.Fatalf("Failed to create the executable data %v", err)
- }
- // Insert it 10 times in parallel. Should be ignored.
- {
- var (
- wg sync.WaitGroup
- testErr error
- errMu sync.Mutex
- )
+// for i := 0; i < 10; i++ {
+// execData, err := assembleBlock(api, parent.Hash(), &engine.PayloadAttributes{
+// Timestamp: parent.Time() + 5,
+// })
+// if err != nil {
+// t.Fatalf("Failed to create the executable data %v", err)
+// }
+// // Insert it 10 times in parallel. Should be ignored.
+// {
+// var (
+// wg sync.WaitGroup
+// testErr error
+// errMu sync.Mutex
+// )
- wg.Add(10)
+// wg.Add(10)
- for ii := 0; ii < 10; ii++ {
- go func() {
- defer wg.Done()
+// for ii := 0; ii < 10; ii++ {
+// go func() {
+// defer wg.Done()
- if newResp, err := api.NewPayloadV1(*execData); err != nil {
- errMu.Lock()
- testErr = fmt.Errorf("Failed to insert block: %w", err)
- errMu.Unlock()
- } else if newResp.Status != "VALID" {
- errMu.Lock()
- testErr = fmt.Errorf("Failed to insert block: %v", newResp.Status)
- errMu.Unlock()
- }
- }()
- }
- wg.Wait()
+// if newResp, err := api.NewPayloadV1(*execData); err != nil {
+// errMu.Lock()
+// testErr = fmt.Errorf("Failed to insert block: %w", err)
+// errMu.Unlock()
+// } else if newResp.Status != "VALID" {
+// errMu.Lock()
+// testErr = fmt.Errorf("Failed to insert block: %v", newResp.Status)
+// errMu.Unlock()
+// }
+// }()
+// }
+// wg.Wait()
- if testErr != nil {
- t.Fatal(testErr)
- }
- }
+// if testErr != nil {
+// t.Fatal(testErr)
+// }
+// }
- block, err := engine.ExecutableDataToBlock(*execData)
+// block, err := engine.ExecutableDataToBlock(*execData)
- if err != nil {
- t.Fatalf("Failed to convert executable data to block %v", err)
- }
+// if err != nil {
+// t.Fatalf("Failed to convert executable data to block %v", err)
+// }
- if ethservice.BlockChain().CurrentBlock().Number.Uint64() != block.NumberU64()-1 {
- t.Fatalf("Chain head shouldn't be updated")
- }
+// if ethservice.BlockChain().CurrentBlock().Number.Uint64() != block.NumberU64()-1 {
+// t.Fatalf("Chain head shouldn't be updated")
+// }
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: block.Hash(),
- SafeBlockHash: block.Hash(),
- FinalizedBlockHash: block.Hash(),
- }
- {
- var (
- wg sync.WaitGroup
- testErr error
- errMu sync.Mutex
- )
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: block.Hash(),
+// SafeBlockHash: block.Hash(),
+// FinalizedBlockHash: block.Hash(),
+// }
+// {
+// var (
+// wg sync.WaitGroup
+// testErr error
+// errMu sync.Mutex
+// )
- wg.Add(10)
- // Do each FCU 10 times
- for ii := 0; ii < 10; ii++ {
- go func() {
- defer wg.Done()
+// wg.Add(10)
+// // Do each FCU 10 times
+// for ii := 0; ii < 10; ii++ {
+// go func() {
+// defer wg.Done()
- if _, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
- errMu.Lock()
- testErr = fmt.Errorf("Failed to insert block: %w", err)
- errMu.Unlock()
- }
- }()
- }
- wg.Wait()
+// if _, err := api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
+// errMu.Lock()
+// testErr = fmt.Errorf("Failed to insert block: %w", err)
+// errMu.Unlock()
+// }
+// }()
+// }
+// wg.Wait()
- if testErr != nil {
- t.Fatal(testErr)
- }
- }
+// if testErr != nil {
+// t.Fatal(testErr)
+// }
+// }
- if have, want := ethservice.BlockChain().CurrentBlock().Number.Uint64(), block.NumberU64(); have != want {
- t.Fatalf("Chain head should be updated, have %d want %d", have, want)
- }
+// if have, want := ethservice.BlockChain().CurrentBlock().Number.Uint64(), block.NumberU64(); have != want {
+// t.Fatalf("Chain head should be updated, have %d want %d", have, want)
+// }
- parent = block
- }
-}
+// parent = block
+// }
+// }
// TestWithdrawals creates and verifies two post-Shanghai blocks. The first
// includes zero withdrawals and the second includes two.
-func TestWithdrawals(t *testing.T) {
- t.Parallel()
-
- genesis, blocks := generateMergeChain(10, true)
- // Set shanghai time to last block + 5 seconds (first post-merge block)
- time := blocks[len(blocks)-1].Time() + 5
- genesis.Config.ShanghaiTime = &time
-
- n, ethservice := startEthService(t, genesis, blocks)
- ethservice.Merger().ReachTTD()
-
- defer n.Close()
-
- api := NewConsensusAPI(ethservice)
-
- // 10: Build Shanghai block with no withdrawals.
- parent := ethservice.BlockChain().CurrentHeader()
- blockParams := engine.PayloadAttributes{
- Timestamp: parent.Time + 5,
- Withdrawals: make([]*types.Withdrawal, 0),
- }
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: parent.Hash(),
- }
- resp, err := api.ForkchoiceUpdatedV2(fcState, &blockParams)
-
- if err != nil {
- t.Fatalf("error preparing payload, err=%v", err)
- }
-
- if resp.PayloadStatus.Status != engine.VALID {
- t.Fatalf("unexpected status (got: %s, want: %s)", resp.PayloadStatus.Status, engine.VALID)
- }
-
- // 10: verify state root is the same as parent
- payloadID := (&miner.BuildPayloadArgs{
- Parent: fcState.HeadBlockHash,
- Timestamp: blockParams.Timestamp,
- FeeRecipient: blockParams.SuggestedFeeRecipient,
- Random: blockParams.Random,
- Withdrawals: blockParams.Withdrawals,
- }).Id()
- execData, err := api.GetPayloadV2(payloadID)
-
- if err != nil {
- t.Fatalf("error getting payload, err=%v", err)
- }
-
- if execData.ExecutionPayload.StateRoot != parent.Root {
- t.Fatalf("mismatch state roots (got: %s, want: %s)", execData.ExecutionPayload.StateRoot, blocks[8].Root())
- }
-
- // 10: verify locally built block
- if status, err := api.NewPayloadV2(*execData.ExecutionPayload); err != nil {
- t.Fatalf("error validating payload: %v", err)
- } else if status.Status != engine.VALID {
- t.Fatalf("invalid payload")
- }
-
- // 11: build shanghai block with withdrawal
- aa := common.Address{0xaa}
- bb := common.Address{0xbb}
- blockParams = engine.PayloadAttributes{
- Timestamp: execData.ExecutionPayload.Timestamp + 5,
- Withdrawals: []*types.Withdrawal{
- {
- Index: 0,
- Address: aa,
- Amount: 32,
- },
- {
- Index: 1,
- Address: bb,
- Amount: 33,
- },
- },
- }
- fcState.HeadBlockHash = execData.ExecutionPayload.BlockHash
- _, err = api.ForkchoiceUpdatedV2(fcState, &blockParams)
-
- if err != nil {
- t.Fatalf("error preparing payload, err=%v", err)
- }
-
- // 11: verify locally build block.
- payloadID = (&miner.BuildPayloadArgs{
- Parent: fcState.HeadBlockHash,
- Timestamp: blockParams.Timestamp,
- FeeRecipient: blockParams.SuggestedFeeRecipient,
- Random: blockParams.Random,
- Withdrawals: blockParams.Withdrawals,
- }).Id()
- execData, err = api.GetPayloadV2(payloadID)
-
- if err != nil {
- t.Fatalf("error getting payload, err=%v", err)
- }
-
- if status, err := api.NewPayloadV2(*execData.ExecutionPayload); err != nil {
- t.Fatalf("error validating payload: %v", err)
- } else if status.Status != engine.VALID {
- t.Fatalf("invalid payload")
- }
-
- // 11: set block as head.
- fcState.HeadBlockHash = execData.ExecutionPayload.BlockHash
- _, err = api.ForkchoiceUpdatedV2(fcState, nil)
-
- if err != nil {
- t.Fatalf("error preparing payload, err=%v", err)
- }
-
- // 11: verify withdrawals were processed.
- db, _, err := ethservice.APIBackend.StateAndHeaderByNumber(context.Background(), rpc.BlockNumber(execData.ExecutionPayload.Number))
- if err != nil {
- t.Fatalf("unable to load db: %v", err)
- }
-
- for i, w := range blockParams.Withdrawals {
- // w.Amount is in gwei, balance in wei
- if db.GetBalance(w.Address).Uint64() != w.Amount*params.GWei {
- t.Fatalf("failed to process withdrawal %d", i)
- }
- }
-}
-
-func TestNilWithdrawals(t *testing.T) {
- t.Parallel()
-
- genesis, blocks := generateMergeChain(10, true)
- // Set shanghai time to last block + 4 seconds (first post-merge block)
- time := blocks[len(blocks)-1].Time() + 4
- genesis.Config.ShanghaiTime = &time
-
- n, ethservice := startEthService(t, genesis, blocks)
- ethservice.Merger().ReachTTD()
-
- defer n.Close()
-
- api := NewConsensusAPI(ethservice)
- parent := ethservice.BlockChain().CurrentHeader()
- aa := common.Address{0xaa}
-
- type test struct {
- blockParams engine.PayloadAttributes
- wantErr bool
- }
-
- tests := []test{
- // Before Shanghai
- {
- blockParams: engine.PayloadAttributes{
- Timestamp: parent.Time + 2,
- Withdrawals: nil,
- },
- wantErr: false,
- },
- {
- blockParams: engine.PayloadAttributes{
- Timestamp: parent.Time + 2,
- Withdrawals: make([]*types.Withdrawal, 0),
- },
- wantErr: true,
- },
- {
- blockParams: engine.PayloadAttributes{
- Timestamp: parent.Time + 2,
- Withdrawals: []*types.Withdrawal{
- {
- Index: 0,
- Address: aa,
- Amount: 32,
- },
- },
- },
- wantErr: true,
- },
- // After Shanghai
- {
- blockParams: engine.PayloadAttributes{
- Timestamp: parent.Time + 5,
- Withdrawals: nil,
- },
- wantErr: true,
- },
- {
- blockParams: engine.PayloadAttributes{
- Timestamp: parent.Time + 5,
- Withdrawals: make([]*types.Withdrawal, 0),
- },
- wantErr: false,
- },
- {
- blockParams: engine.PayloadAttributes{
- Timestamp: parent.Time + 5,
- Withdrawals: []*types.Withdrawal{
- {
- Index: 0,
- Address: aa,
- Amount: 32,
- },
- },
- },
- wantErr: false,
- },
- }
-
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: parent.Hash(),
- }
-
- for _, test := range tests {
- _, err := api.ForkchoiceUpdatedV2(fcState, &test.blockParams)
- if test.wantErr {
- if err == nil {
- t.Fatal("wanted error on fcuv2 with invalid withdrawals")
- }
-
- continue
- }
-
- if err != nil {
- t.Fatalf("error preparing payload, err=%v", err)
- }
-
- // 11: verify locally build block.
- payloadID := (&miner.BuildPayloadArgs{
- Parent: fcState.HeadBlockHash,
- Timestamp: test.blockParams.Timestamp,
- FeeRecipient: test.blockParams.SuggestedFeeRecipient,
- Random: test.blockParams.Random,
- }).Id()
- execData, err := api.GetPayloadV2(payloadID)
-
- if err != nil {
- t.Fatalf("error getting payload, err=%v", err)
- }
-
- if status, err := api.NewPayloadV2(*execData.ExecutionPayload); err != nil {
- t.Fatalf("error validating payload: %v", err)
- } else if status.Status != engine.VALID {
- t.Fatalf("invalid payload")
- }
- }
-}
-
-func setupBodies(t *testing.T) (*node.Node, *eth.Ethereum, []*types.Block) {
- t.Helper()
-
- genesis, blocks := generateMergeChain(10, true)
- // enable shanghai on the last block
- time := blocks[len(blocks)-1].Header().Time + 1
- genesis.Config.ShanghaiTime = &time
- n, ethservice := startEthService(t, genesis, blocks)
-
- var (
- parent = ethservice.BlockChain().CurrentBlock()
- // This EVM code generates a log when the contract is created.
- logCode = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
- )
-
- callback := func(parent *types.Header) {
- statedb, _ := ethservice.BlockChain().StateAt(parent.Root)
- nonce := statedb.GetNonce(testAddr)
- tx, _ := types.SignTx(types.NewContractCreation(nonce, new(big.Int), 1000000, big.NewInt(2*params.InitialBaseFee), logCode), types.LatestSigner(ethservice.BlockChain().Config()), testKey)
- _ = ethservice.TxPool().AddLocal(tx)
- }
-
- withdrawals := make([][]*types.Withdrawal, 10)
- withdrawals[0] = nil // should be filtered out by miner
- withdrawals[1] = make([]*types.Withdrawal, 0)
-
- for i := 2; i < len(withdrawals); i++ {
- addr := make([]byte, 20)
-
- _, _ = crand.Read(addr)
-
- withdrawals[i] = []*types.Withdrawal{
- {Index: rand.Uint64(), Validator: rand.Uint64(), Amount: rand.Uint64(), Address: common.BytesToAddress(addr)},
- }
- }
-
- postShanghaiHeaders := setupBlocks(t, ethservice, 10, parent, callback, withdrawals)
- postShanghaiBlocks := make([]*types.Block, len(postShanghaiHeaders))
-
- for i, header := range postShanghaiHeaders {
- postShanghaiBlocks[i] = ethservice.BlockChain().GetBlock(header.Hash(), header.Number.Uint64())
- }
-
- return n, ethservice, append(blocks, postShanghaiBlocks...)
-}
-
-func allHashes(blocks []*types.Block) []common.Hash {
- hashes := make([]common.Hash, 0, len(blocks))
-
- for _, b := range blocks {
- hashes = append(hashes, b.Hash())
- }
-
- return hashes
-}
-func allBodies(blocks []*types.Block) []*types.Body {
- bodies := make([]*types.Body, 0, len(blocks))
-
- for _, b := range blocks {
- bodies = append(bodies, b.Body())
- }
-
- return bodies
-}
-
-func TestGetBlockBodiesByHash(t *testing.T) {
- t.Parallel()
-
- node, eth, blocks := setupBodies(t)
- api := NewConsensusAPI(eth)
-
- defer node.Close()
-
- tests := []struct {
- results []*types.Body
- hashes []common.Hash
- }{
- // First pow block
- {
- results: []*types.Body{eth.BlockChain().GetBlockByNumber(0).Body()},
- hashes: []common.Hash{eth.BlockChain().GetBlockByNumber(0).Hash()},
- },
- // Last pow block
- {
- results: []*types.Body{blocks[9].Body()},
- hashes: []common.Hash{blocks[9].Hash()},
- },
- // First post-merge block
- {
- results: []*types.Body{blocks[10].Body()},
- hashes: []common.Hash{blocks[10].Hash()},
- },
- // Pre & post merge blocks
- {
- results: []*types.Body{blocks[0].Body(), blocks[9].Body(), blocks[14].Body()},
- hashes: []common.Hash{blocks[0].Hash(), blocks[9].Hash(), blocks[14].Hash()},
- },
- // unavailable block
- {
- results: []*types.Body{blocks[0].Body(), nil, blocks[14].Body()},
- hashes: []common.Hash{blocks[0].Hash(), {1, 2}, blocks[14].Hash()},
- },
- // same block multiple times
- {
- results: []*types.Body{blocks[0].Body(), nil, blocks[0].Body(), blocks[0].Body()},
- hashes: []common.Hash{blocks[0].Hash(), {1, 2}, blocks[0].Hash(), blocks[0].Hash()},
- },
- // all blocks
- {
- results: allBodies(blocks),
- hashes: allHashes(blocks),
- },
- }
-
- for k, test := range tests {
- result := api.GetPayloadBodiesByHashV1(test.hashes)
- for i, r := range result {
- if !equalBody(test.results[i], r) {
- t.Fatalf("test %v: invalid response: expected %+v got %+v", k, test.results[i], r)
- }
- }
- }
-}
-
-func TestGetBlockBodiesByRange(t *testing.T) {
- t.Parallel()
-
- node, eth, blocks := setupBodies(t)
- api := NewConsensusAPI(eth)
-
- defer node.Close()
-
- tests := []struct {
- results []*types.Body
- start hexutil.Uint64
- count hexutil.Uint64
- }{
- {
- results: []*types.Body{blocks[9].Body()},
- start: 10,
- count: 1,
- },
- // Genesis
- {
- results: []*types.Body{blocks[0].Body()},
- start: 1,
- count: 1,
- },
- // First post-merge block
- {
- results: []*types.Body{blocks[9].Body()},
- start: 10,
- count: 1,
- },
- // Pre & post merge blocks
- {
- results: []*types.Body{blocks[7].Body(), blocks[8].Body(), blocks[9].Body(), blocks[10].Body()},
- start: 8,
- count: 4,
- },
- // unavailable block
- {
- results: []*types.Body{blocks[18].Body(), blocks[19].Body()},
- start: 19,
- count: 3,
- },
- // unavailable block
- {
- results: []*types.Body{blocks[19].Body()},
- start: 20,
- count: 2,
- },
- {
- results: []*types.Body{blocks[19].Body()},
- start: 20,
- count: 1,
- },
- // whole range unavailable
- {
- results: make([]*types.Body, 0),
- start: 22,
- count: 2,
- },
- // allBlocks
- {
- results: allBodies(blocks),
- start: 1,
- count: hexutil.Uint64(len(blocks)),
- },
- }
-
- for k, test := range tests {
- result, err := api.GetPayloadBodiesByRangeV1(test.start, test.count)
- if err != nil {
- t.Fatal(err)
- }
-
- if len(result) == len(test.results) {
- for i, r := range result {
- if !equalBody(test.results[i], r) {
- t.Fatalf("test %d: invalid response: expected \n%+v\ngot\n%+v", k, test.results[i], r)
- }
- }
- } else {
- t.Fatalf("test %d: invalid length want %v got %v", k, len(test.results), len(result))
- }
- }
-}
-
-func TestGetBlockBodiesByRangeInvalidParams(t *testing.T) {
- t.Parallel()
-
- node, eth, _ := setupBodies(t)
- api := NewConsensusAPI(eth)
-
- defer node.Close()
-
- tests := []struct {
- start hexutil.Uint64
- count hexutil.Uint64
- want *engine.EngineAPIError
- }{
- // Genesis
- {
- start: 0,
- count: 1,
- want: engine.InvalidParams,
- },
- // No block requested
- {
- start: 1,
- count: 0,
- want: engine.InvalidParams,
- },
- // Genesis & no block
- {
- start: 0,
- count: 0,
- want: engine.InvalidParams,
- },
- // More than 1024 blocks
- {
- start: 1,
- count: 1025,
- want: engine.TooLargeRequest,
- },
- }
-
- for i, tc := range tests {
- result, err := api.GetPayloadBodiesByRangeV1(tc.start, tc.count)
- if err == nil {
- t.Fatalf("test %d: expected error, got %v", i, result)
- }
-
- if have, want := err.Error(), tc.want.Error(); have != want {
- t.Fatalf("test %d: have %s, want %s", i, have, want)
- }
- }
-}
-
-func equalBody(a *types.Body, b *engine.ExecutionPayloadBodyV1) bool {
- if a == nil && b == nil {
- return true
- } else if a == nil || b == nil {
- return false
- }
-
- if len(a.Transactions) != len(b.TransactionData) {
- return false
- }
-
- for i, tx := range a.Transactions {
- data, _ := tx.MarshalBinary()
- if !bytes.Equal(data, b.TransactionData[i]) {
- return false
- }
- }
-
- return reflect.DeepEqual(a.Withdrawals, b.Withdrawals)
-}
+// func TestWithdrawals(t *testing.T) {
+// t.Parallel()
+
+// genesis, blocks := generateMergeChain(10, true)
+// // Set shanghai time to last block + 5 seconds (first post-merge block)
+// number := new(big.Int).Add(blocks[len(blocks)-1].Header().Number, big.NewInt(5))
+// genesis.Config.ShanghaiBlock = number
+
+// n, ethservice := startEthService(t, genesis, blocks)
+// ethservice.Merger().ReachTTD()
+
+// defer n.Close()
+
+// api := NewConsensusAPI(ethservice)
+
+// // 10: Build Shanghai block with no withdrawals.
+// parent := ethservice.BlockChain().CurrentHeader()
+// blockParams := engine.PayloadAttributes{
+// Timestamp: parent.Time + 5,
+// Withdrawals: make([]*types.Withdrawal, 0),
+// }
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: parent.Hash(),
+// }
+// resp, err := api.ForkchoiceUpdatedV2(fcState, &blockParams)
+
+// if err != nil {
+// t.Fatalf("error preparing payload, err=%v", err)
+// }
+
+// if resp.PayloadStatus.Status != engine.VALID {
+// t.Fatalf("unexpected status (got: %s, want: %s)", resp.PayloadStatus.Status, engine.VALID)
+// }
+
+// // 10: verify state root is the same as parent
+// payloadID := (&miner.BuildPayloadArgs{
+// Parent: fcState.HeadBlockHash,
+// Timestamp: blockParams.Timestamp,
+// FeeRecipient: blockParams.SuggestedFeeRecipient,
+// Random: blockParams.Random,
+// Withdrawals: blockParams.Withdrawals,
+// }).Id()
+// execData, err := api.GetPayloadV2(payloadID)
+
+// if err != nil {
+// t.Fatalf("error getting payload, err=%v", err)
+// }
+
+// if execData.ExecutionPayload.StateRoot != parent.Root {
+// t.Fatalf("mismatch state roots (got: %s, want: %s)", execData.ExecutionPayload.StateRoot, blocks[8].Root())
+// }
+
+// // 10: verify locally built block
+// if status, err := api.NewPayloadV2(*execData.ExecutionPayload); err != nil {
+// t.Fatalf("error validating payload: %v", err)
+// } else if status.Status != engine.VALID {
+// t.Fatalf("invalid payload")
+// }
+
+// // 11: build shanghai block with withdrawal
+// aa := common.Address{0xaa}
+// bb := common.Address{0xbb}
+// blockParams = engine.PayloadAttributes{
+// Timestamp: execData.ExecutionPayload.Timestamp + 5,
+// Withdrawals: []*types.Withdrawal{
+// {
+// Index: 0,
+// Address: aa,
+// Amount: 32,
+// },
+// {
+// Index: 1,
+// Address: bb,
+// Amount: 33,
+// },
+// },
+// }
+// fcState.HeadBlockHash = execData.ExecutionPayload.BlockHash
+// _, err = api.ForkchoiceUpdatedV2(fcState, &blockParams)
+
+// if err != nil {
+// t.Fatalf("error preparing payload, err=%v", err)
+// }
+
+// // 11: verify locally build block.
+// payloadID = (&miner.BuildPayloadArgs{
+// Parent: fcState.HeadBlockHash,
+// Timestamp: blockParams.Timestamp,
+// FeeRecipient: blockParams.SuggestedFeeRecipient,
+// Random: blockParams.Random,
+// Withdrawals: blockParams.Withdrawals,
+// }).Id()
+// execData, err = api.GetPayloadV2(payloadID)
+
+// if err != nil {
+// t.Fatalf("error getting payload, err=%v", err)
+// }
+
+// if status, err := api.NewPayloadV2(*execData.ExecutionPayload); err != nil {
+// t.Fatalf("error validating payload: %v", err)
+// } else if status.Status != engine.VALID {
+// t.Fatalf("invalid payload")
+// }
+
+// // 11: set block as head.
+// fcState.HeadBlockHash = execData.ExecutionPayload.BlockHash
+// _, err = api.ForkchoiceUpdatedV2(fcState, nil)
+
+// if err != nil {
+// t.Fatalf("error preparing payload, err=%v", err)
+// }
+
+// // 11: verify withdrawals were processed.
+// db, _, err := ethservice.APIBackend.StateAndHeaderByNumber(context.Background(), rpc.BlockNumber(execData.ExecutionPayload.Number))
+// if err != nil {
+// t.Fatalf("unable to load db: %v", err)
+// }
+
+// for i, w := range blockParams.Withdrawals {
+// // w.Amount is in gwei, balance in wei
+// if db.GetBalance(w.Address).Uint64() != w.Amount*params.GWei {
+// t.Fatalf("failed to process withdrawal %d", i)
+// }
+// }
+// }
+
+// func TestNilWithdrawals(t *testing.T) {
+// t.Parallel()
+
+// genesis, blocks := generateMergeChain(10, true)
+// // Set shanghai time to last block + 4 seconds (first post-merge block)
+// block := new(big.Int).Add(blocks[len(blocks)-1].Header().Number, big.NewInt(4))
+// genesis.Config.ShanghaiBlock = block
+
+// n, ethservice := startEthService(t, genesis, blocks)
+// ethservice.Merger().ReachTTD()
+
+// defer n.Close()
+
+// api := NewConsensusAPI(ethservice)
+// parent := ethservice.BlockChain().CurrentHeader()
+// aa := common.Address{0xaa}
+
+// type test struct {
+// blockParams engine.PayloadAttributes
+// wantErr bool
+// }
+
+// tests := []test{
+// // Before Shanghai
+// {
+// blockParams: engine.PayloadAttributes{
+// Timestamp: parent.Time + 2,
+// Withdrawals: nil,
+// },
+// wantErr: false,
+// },
+// {
+// blockParams: engine.PayloadAttributes{
+// Timestamp: parent.Time + 2,
+// Withdrawals: make([]*types.Withdrawal, 0),
+// },
+// wantErr: true,
+// },
+// {
+// blockParams: engine.PayloadAttributes{
+// Timestamp: parent.Time + 2,
+// Withdrawals: []*types.Withdrawal{
+// {
+// Index: 0,
+// Address: aa,
+// Amount: 32,
+// },
+// },
+// },
+// wantErr: true,
+// },
+// // After Shanghai
+// {
+// blockParams: engine.PayloadAttributes{
+// Timestamp: parent.Time + 5,
+// Withdrawals: nil,
+// },
+// wantErr: true,
+// },
+// {
+// blockParams: engine.PayloadAttributes{
+// Timestamp: parent.Time + 5,
+// Withdrawals: make([]*types.Withdrawal, 0),
+// },
+// wantErr: false,
+// },
+// {
+// blockParams: engine.PayloadAttributes{
+// Timestamp: parent.Time + 5,
+// Withdrawals: []*types.Withdrawal{
+// {
+// Index: 0,
+// Address: aa,
+// Amount: 32,
+// },
+// },
+// },
+// wantErr: false,
+// },
+// }
+
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: parent.Hash(),
+// }
+
+// for _, test := range tests {
+// _, err := api.ForkchoiceUpdatedV2(fcState, &test.blockParams)
+// if test.wantErr {
+// if err == nil {
+// t.Fatal("wanted error on fcuv2 with invalid withdrawals")
+// }
+
+// continue
+// }
+
+// if err != nil {
+// t.Fatalf("error preparing payload, err=%v", err)
+// }
+
+// // 11: verify locally build block.
+// payloadID := (&miner.BuildPayloadArgs{
+// Parent: fcState.HeadBlockHash,
+// Timestamp: test.blockParams.Timestamp,
+// FeeRecipient: test.blockParams.SuggestedFeeRecipient,
+// Random: test.blockParams.Random,
+// }).Id()
+// execData, err := api.GetPayloadV2(payloadID)
+
+// if err != nil {
+// t.Fatalf("error getting payload, err=%v", err)
+// }
+
+// if status, err := api.NewPayloadV2(*execData.ExecutionPayload); err != nil {
+// t.Fatalf("error validating payload: %v", err)
+// } else if status.Status != engine.VALID {
+// t.Fatalf("invalid payload")
+// }
+// }
+// }
+
+// func setupBodies(t *testing.T) (*node.Node, *eth.Ethereum, []*types.Block) {
+// t.Helper()
+
+// genesis, blocks := generateMergeChain(10, true)
+// // enable shanghai on the last block
+// number := new(big.Int).Add(blocks[len(blocks)-1].Header().Number, big.NewInt(1))
+// genesis.Config.ShanghaiBlock = number
+// n, ethservice := startEthService(t, genesis, blocks)
+
+// var (
+// parent = ethservice.BlockChain().CurrentBlock()
+// // This EVM code generates a log when the contract is created.
+// logCode = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00")
+// )
+
+// callback := func(parent *types.Header) {
+// statedb, _ := ethservice.BlockChain().StateAt(parent.Root)
+// nonce := statedb.GetNonce(testAddr)
+// tx, _ := types.SignTx(types.NewContractCreation(nonce, new(big.Int), 1000000, big.NewInt(2*params.InitialBaseFee), logCode), types.LatestSigner(ethservice.BlockChain().Config()), testKey)
+// _ = ethservice.TxPool().AddLocal(tx)
+// }
+
+// withdrawals := make([][]*types.Withdrawal, 10)
+// withdrawals[0] = nil // should be filtered out by miner
+// withdrawals[1] = make([]*types.Withdrawal, 0)
+
+// for i := 2; i < len(withdrawals); i++ {
+// addr := make([]byte, 20)
+
+// _, _ = crand.Read(addr)
+
+// withdrawals[i] = []*types.Withdrawal{
+// {Index: rand.Uint64(), Validator: rand.Uint64(), Amount: rand.Uint64(), Address: common.BytesToAddress(addr)},
+// }
+// }
+
+// postShanghaiHeaders := setupBlocks(t, ethservice, 10, parent, callback, withdrawals)
+// postShanghaiBlocks := make([]*types.Block, len(postShanghaiHeaders))
+
+// for i, header := range postShanghaiHeaders {
+// postShanghaiBlocks[i] = ethservice.BlockChain().GetBlock(header.Hash(), header.Number.Uint64())
+// }
+
+// return n, ethservice, append(blocks, postShanghaiBlocks...)
+// }
+
+// func allHashes(blocks []*types.Block) []common.Hash {
+// hashes := make([]common.Hash, 0, len(blocks))
+
+// for _, b := range blocks {
+// hashes = append(hashes, b.Hash())
+// }
+
+// return hashes
+// }
+// func allBodies(blocks []*types.Block) []*types.Body {
+// bodies := make([]*types.Body, 0, len(blocks))
+
+// for _, b := range blocks {
+// bodies = append(bodies, b.Body())
+// }
+
+// return bodies
+// }
+
+// func TestGetBlockBodiesByHash(t *testing.T) {
+// t.Parallel()
+
+// node, eth, blocks := setupBodies(t)
+// api := NewConsensusAPI(eth)
+
+// defer node.Close()
+
+// tests := []struct {
+// results []*types.Body
+// hashes []common.Hash
+// }{
+// // First pow block
+// {
+// results: []*types.Body{eth.BlockChain().GetBlockByNumber(0).Body()},
+// hashes: []common.Hash{eth.BlockChain().GetBlockByNumber(0).Hash()},
+// },
+// // Last pow block
+// {
+// results: []*types.Body{blocks[9].Body()},
+// hashes: []common.Hash{blocks[9].Hash()},
+// },
+// // First post-merge block
+// {
+// results: []*types.Body{blocks[10].Body()},
+// hashes: []common.Hash{blocks[10].Hash()},
+// },
+// // Pre & post merge blocks
+// {
+// results: []*types.Body{blocks[0].Body(), blocks[9].Body(), blocks[14].Body()},
+// hashes: []common.Hash{blocks[0].Hash(), blocks[9].Hash(), blocks[14].Hash()},
+// },
+// // unavailable block
+// {
+// results: []*types.Body{blocks[0].Body(), nil, blocks[14].Body()},
+// hashes: []common.Hash{blocks[0].Hash(), {1, 2}, blocks[14].Hash()},
+// },
+// // same block multiple times
+// {
+// results: []*types.Body{blocks[0].Body(), nil, blocks[0].Body(), blocks[0].Body()},
+// hashes: []common.Hash{blocks[0].Hash(), {1, 2}, blocks[0].Hash(), blocks[0].Hash()},
+// },
+// // all blocks
+// {
+// results: allBodies(blocks),
+// hashes: allHashes(blocks),
+// },
+// }
+
+// for k, test := range tests {
+// result := api.GetPayloadBodiesByHashV1(test.hashes)
+// for i, r := range result {
+// if !equalBody(test.results[i], r) {
+// t.Fatalf("test %v: invalid response: expected %+v got %+v", k, test.results[i], r)
+// }
+// }
+// }
+// }
+
+// func TestGetBlockBodiesByRange(t *testing.T) {
+// t.Parallel()
+
+// node, eth, blocks := setupBodies(t)
+// api := NewConsensusAPI(eth)
+
+// defer node.Close()
+
+// tests := []struct {
+// results []*types.Body
+// start hexutil.Uint64
+// count hexutil.Uint64
+// }{
+// {
+// results: []*types.Body{blocks[9].Body()},
+// start: 10,
+// count: 1,
+// },
+// // Genesis
+// {
+// results: []*types.Body{blocks[0].Body()},
+// start: 1,
+// count: 1,
+// },
+// // First post-merge block
+// {
+// results: []*types.Body{blocks[9].Body()},
+// start: 10,
+// count: 1,
+// },
+// // Pre & post merge blocks
+// {
+// results: []*types.Body{blocks[7].Body(), blocks[8].Body(), blocks[9].Body(), blocks[10].Body()},
+// start: 8,
+// count: 4,
+// },
+// // unavailable block
+// {
+// results: []*types.Body{blocks[18].Body(), blocks[19].Body()},
+// start: 19,
+// count: 3,
+// },
+// // unavailable block
+// {
+// results: []*types.Body{blocks[19].Body()},
+// start: 20,
+// count: 2,
+// },
+// {
+// results: []*types.Body{blocks[19].Body()},
+// start: 20,
+// count: 1,
+// },
+// // whole range unavailable
+// {
+// results: make([]*types.Body, 0),
+// start: 22,
+// count: 2,
+// },
+// // allBlocks
+// {
+// results: allBodies(blocks),
+// start: 1,
+// count: hexutil.Uint64(len(blocks)),
+// },
+// }
+
+// for k, test := range tests {
+// result, err := api.GetPayloadBodiesByRangeV1(test.start, test.count)
+// if err != nil {
+// t.Fatal(err)
+// }
+
+// if len(result) == len(test.results) {
+// for i, r := range result {
+// if !equalBody(test.results[i], r) {
+// t.Fatalf("test %d: invalid response: expected \n%+v\ngot\n%+v", k, test.results[i], r)
+// }
+// }
+// } else {
+// t.Fatalf("test %d: invalid length want %v got %v", k, len(test.results), len(result))
+// }
+// }
+// }
+
+// func TestGetBlockBodiesByRangeInvalidParams(t *testing.T) {
+// t.Parallel()
+
+// node, eth, _ := setupBodies(t)
+// api := NewConsensusAPI(eth)
+
+// defer node.Close()
+
+// tests := []struct {
+// start hexutil.Uint64
+// count hexutil.Uint64
+// want *engine.EngineAPIError
+// }{
+// // Genesis
+// {
+// start: 0,
+// count: 1,
+// want: engine.InvalidParams,
+// },
+// // No block requested
+// {
+// start: 1,
+// count: 0,
+// want: engine.InvalidParams,
+// },
+// // Genesis & no block
+// {
+// start: 0,
+// count: 0,
+// want: engine.InvalidParams,
+// },
+// // More than 1024 blocks
+// {
+// start: 1,
+// count: 1025,
+// want: engine.TooLargeRequest,
+// },
+// }
+
+// for i, tc := range tests {
+// result, err := api.GetPayloadBodiesByRangeV1(tc.start, tc.count)
+// if err == nil {
+// t.Fatalf("test %d: expected error, got %v", i, result)
+// }
+
+// if have, want := err.Error(), tc.want.Error(); have != want {
+// t.Fatalf("test %d: have %s, want %s", i, have, want)
+// }
+// }
+// }
+
+// func equalBody(a *types.Body, b *engine.ExecutionPayloadBodyV1) bool {
+// if a == nil && b == nil {
+// return true
+// } else if a == nil || b == nil {
+// return false
+// }
+
+// if len(a.Transactions) != len(b.TransactionData) {
+// return false
+// }
+
+// for i, tx := range a.Transactions {
+// data, _ := tx.MarshalBinary()
+// if !bytes.Equal(data, b.TransactionData[i]) {
+// return false
+// }
+// }
+
+// return reflect.DeepEqual(a.Withdrawals, b.Withdrawals)
+// }
diff --git a/eth/ethconfig/config.go b/eth/ethconfig/config.go
index 77b127a3a8..3237b27968 100644
--- a/eth/ethconfig/config.go
+++ b/eth/ethconfig/config.go
@@ -18,6 +18,7 @@
package ethconfig
import (
+ "math/big"
"os"
"os/user"
"path/filepath"
@@ -220,7 +221,7 @@ type Config struct {
// TODO marcello double check
// OverrideShanghai (TODO: remove after the fork)
- OverrideShanghai *uint64 `toml:",omitempty"`
+ OverrideShanghai *big.Int `toml:",omitempty"`
// URL to connect to Heimdall node
HeimdallURL string
diff --git a/eth/ethconfig/gen_config.go b/eth/ethconfig/gen_config.go
index 4ef94b47fe..29c5bb3f41 100644
--- a/eth/ethconfig/gen_config.go
+++ b/eth/ethconfig/gen_config.go
@@ -3,6 +3,7 @@
package ethconfig
import (
+ "math/big"
"time"
"github.com/ethereum/go-ethereum/common"
@@ -48,6 +49,7 @@ func (c Config) MarshalTOML() (interface{}, error) {
TrieTimeout time.Duration
SnapshotCache int
Preimages bool
+ TriesInMemory uint64
FilterLogCacheSize int
Miner miner.Config
Ethash ethash.Config
@@ -56,13 +58,22 @@ func (c Config) MarshalTOML() (interface{}, error) {
EnablePreimageRecording bool
DocRoot string `toml:"-"`
RPCGasCap uint64
+ RPCReturnDataLimit uint64
RPCEVMTimeout time.Duration
RPCTxFeeCap float64
Checkpoint *params.TrustedCheckpoint `toml:",omitempty"`
CheckpointOracle *params.CheckpointOracleConfig `toml:",omitempty"`
- OverrideShanghai *uint64 `toml:",omitempty"`
+ OverrideShanghai *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"`
}
-
var enc Config
enc.Genesis = c.Genesis
enc.NetworkId = c.NetworkId
@@ -94,6 +105,7 @@ func (c Config) MarshalTOML() (interface{}, error) {
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.Ethash = c.Ethash
@@ -102,12 +114,21 @@ 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.Checkpoint = c.Checkpoint
enc.CheckpointOracle = c.CheckpointOracle
enc.OverrideShanghai = c.OverrideShanghai
-
+ 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
return &enc, nil
}
@@ -144,6 +165,7 @@ func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error {
TrieTimeout *time.Duration
SnapshotCache *int
Preimages *bool
+ TriesInMemory *uint64
FilterLogCacheSize *int
Miner *miner.Config
Ethash *ethash.Config
@@ -152,189 +174,187 @@ func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error {
EnablePreimageRecording *bool
DocRoot *string `toml:"-"`
RPCGasCap *uint64
+ RPCReturnDataLimit *uint64
RPCEVMTimeout *time.Duration
RPCTxFeeCap *float64
Checkpoint *params.TrustedCheckpoint `toml:",omitempty"`
CheckpointOracle *params.CheckpointOracleConfig `toml:",omitempty"`
- OverrideShanghai *uint64 `toml:",omitempty"`
+ OverrideShanghai *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"`
}
-
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.SyncFromCheckpoint != nil {
c.SyncFromCheckpoint = *dec.SyncFromCheckpoint
}
-
if dec.UltraLightServers != nil {
c.UltraLightServers = dec.UltraLightServers
}
-
if dec.UltraLightFraction != nil {
c.UltraLightFraction = *dec.UltraLightFraction
}
-
if dec.UltraLightOnlyAnnounce != nil {
c.UltraLightOnlyAnnounce = *dec.UltraLightOnlyAnnounce
}
-
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.TrieCleanCache != nil {
c.TrieCleanCache = *dec.TrieCleanCache
}
-
if dec.TrieCleanCacheJournal != nil {
c.TrieCleanCacheJournal = *dec.TrieCleanCacheJournal
}
-
if dec.TrieCleanCacheRejournal != nil {
c.TrieCleanCacheRejournal = *dec.TrieCleanCacheRejournal
}
-
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
}
-
if dec.Ethash != nil {
c.Ethash = *dec.Ethash
}
-
if dec.TxPool != nil {
c.TxPool = *dec.TxPool
}
-
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.Checkpoint != nil {
c.Checkpoint = dec.Checkpoint
}
-
if dec.CheckpointOracle != nil {
c.CheckpointOracle = dec.CheckpointOracle
}
- // TODO marcello double check
if dec.OverrideShanghai != nil {
c.OverrideShanghai = dec.OverrideShanghai
}
-
+ 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
+ }
return nil
}
diff --git a/eth/protocols/eth/handler_test.go b/eth/protocols/eth/handler_test.go
index 29e71a5d5a..980be46d4e 100644
--- a/eth/protocols/eth/handler_test.go
+++ b/eth/protocols/eth/handler_test.go
@@ -94,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),
diff --git a/eth/tracers/api.go b/eth/tracers/api.go
index fb20d52e19..532347f90e 100644
--- a/eth/tracers/api.go
+++ b/eth/tracers/api.go
@@ -1425,18 +1425,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
}
diff --git a/light/txpool.go b/light/txpool.go
index b83b244757..b866981ebd 100644
--- a/light/txpool.go
+++ b/light/txpool.go
@@ -341,7 +341,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(uint64(time.Now().Unix()))
+ pool.shanghai = pool.config.IsShanghai(next)
}
// Stop stops the light transaction pool
diff --git a/miner/stress/beacon/main.go b/miner/stress/beacon/main.go
index a94e6e9467..abdc7b71f5 100644
--- a/miner/stress/beacon/main.go
+++ b/miner/stress/beacon/main.go
@@ -1,619 +1,619 @@
-// Copyright 2021 The go-ethereum Authors
-// This file is part of the go-ethereum library.
-//
-// The go-ethereum library is free software: you can redistribute it and/or modify
-// it under the terms of the GNU Lesser General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-//
-// The go-ethereum library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public License
-// along with the go-ethereum library. If not, see .
+// // Copyright 2021 The go-ethereum Authors
+// // This file is part of the go-ethereum library.
+// //
+// // The go-ethereum library is free software: you can redistribute it and/or modify
+// // it under the terms of the GNU Lesser General Public License as published by
+// // the Free Software Foundation, either version 3 of the License, or
+// // (at your option) any later version.
+// //
+// // The go-ethereum library is distributed in the hope that it will be useful,
+// // but WITHOUT ANY WARRANTY; without even the implied warranty of
+// // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// // GNU Lesser General Public License for more details.
+// //
+// // You should have received a copy of the GNU Lesser General Public License
+// // along with the go-ethereum library. If not, see .
-// This file contains a miner stress test for the eth1/2 transition
+// // This file contains a miner stress test for the eth1/2 transition
package main
-import (
- "crypto/ecdsa"
- "errors"
- "math/big"
- "math/rand"
- "os"
- "path/filepath"
- "time"
-
- "github.com/ethereum/go-ethereum/accounts/keystore"
- "github.com/ethereum/go-ethereum/beacon/engine"
- "github.com/ethereum/go-ethereum/common"
- "github.com/ethereum/go-ethereum/common/fdlimit"
- "github.com/ethereum/go-ethereum/consensus/ethash"
- "github.com/ethereum/go-ethereum/core"
- "github.com/ethereum/go-ethereum/core/txpool"
- "github.com/ethereum/go-ethereum/core/types"
- "github.com/ethereum/go-ethereum/crypto"
- "github.com/ethereum/go-ethereum/eth"
- ethcatalyst "github.com/ethereum/go-ethereum/eth/catalyst"
- "github.com/ethereum/go-ethereum/eth/downloader"
- "github.com/ethereum/go-ethereum/eth/ethconfig"
- "github.com/ethereum/go-ethereum/les"
- lescatalyst "github.com/ethereum/go-ethereum/les/catalyst"
- "github.com/ethereum/go-ethereum/log"
- "github.com/ethereum/go-ethereum/miner"
- "github.com/ethereum/go-ethereum/node"
- "github.com/ethereum/go-ethereum/p2p"
- "github.com/ethereum/go-ethereum/p2p/enode"
- "github.com/ethereum/go-ethereum/params"
-)
-
-type nodetype int
-
-const (
- legacyMiningNode nodetype = iota
- legacyNormalNode
- eth2MiningNode
- eth2NormalNode
- eth2LightClient
-)
-
-func (typ nodetype) String() string {
- switch typ {
- case legacyMiningNode:
- return "legacyMiningNode"
- case legacyNormalNode:
- return "legacyNormalNode"
- case eth2MiningNode:
- return "eth2MiningNode"
- case eth2NormalNode:
- return "eth2NormalNode"
- case eth2LightClient:
- return "eth2LightClient"
- default:
- return "undefined"
- }
-}
-
-var (
- // transitionDifficulty is the target total difficulty for transition
- transitionDifficulty = new(big.Int).Mul(big.NewInt(20), params.MinimumDifficulty)
-
- // blockInterval is the time interval for creating a new eth2 block
- blockIntervalInt = 3
- blockInterval = time.Second * time.Duration(blockIntervalInt)
-
- // finalizationDist is the block distance for finalizing block
- finalizationDist = 10
-)
-
-type ethNode struct {
- typ nodetype
- stack *node.Node
- enode *enode.Node
- api *ethcatalyst.ConsensusAPI
- ethBackend *eth.Ethereum
- lapi *lescatalyst.ConsensusAPI
- lesBackend *les.LightEthereum
-}
-
-func newNode(typ nodetype, genesis *core.Genesis, enodes []*enode.Node) *ethNode {
- var (
- err error
- api *ethcatalyst.ConsensusAPI
- lapi *lescatalyst.ConsensusAPI
- stack *node.Node
- ethBackend *eth.Ethereum
- lesBackend *les.LightEthereum
- )
- // Start the node and wait until it's up
- if typ == eth2LightClient {
- stack, lesBackend, lapi, err = makeLightNode(genesis)
- } else {
- stack, ethBackend, api, err = makeFullNode(genesis)
- }
-
- if err != nil {
- panic(err)
- }
-
- for stack.Server().NodeInfo().Ports.Listener == 0 {
- time.Sleep(250 * time.Millisecond)
- }
- // Connect the node to all the previous ones
- for _, n := range enodes {
- stack.Server().AddPeer(n)
- }
-
- enode := stack.Server().Self()
-
- // Inject the signer key and start sealing with it
- stack.AccountManager().AddBackend(keystore.NewPlaintextKeyStore("beacon-stress"))
- ks := stack.AccountManager().Backends(keystore.KeyStoreType)
-
- if len(ks) == 0 {
- panic("Keystore is not available")
- }
-
- store := ks[0].(*keystore.KeyStore)
- if _, err := store.NewAccount(""); err != nil {
- panic(err)
- }
-
- return ðNode{
- typ: typ,
- api: api,
- ethBackend: ethBackend,
- lapi: lapi,
- lesBackend: lesBackend,
- stack: stack,
- enode: enode,
- }
-}
-
-func (n *ethNode) assembleBlock(parentHash common.Hash, parentTimestamp uint64) (*engine.ExecutableData, error) {
- if n.typ != eth2MiningNode {
- return nil, errors.New("invalid node type")
- }
-
- timestamp := uint64(time.Now().Unix())
- if timestamp <= parentTimestamp {
- timestamp = parentTimestamp + 1
- }
-
- payloadAttribute := engine.PayloadAttributes{
- Timestamp: timestamp,
- Random: common.Hash{},
- SuggestedFeeRecipient: common.HexToAddress("0xdeadbeef"),
- }
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: parentHash,
- SafeBlockHash: common.Hash{},
- FinalizedBlockHash: common.Hash{},
- }
-
- payload, err := n.api.ForkchoiceUpdatedV1(fcState, &payloadAttribute)
- if err != nil {
- return nil, err
- }
-
- time.Sleep(time.Second * 5) // give enough time for block creation
-
- return n.api.GetPayloadV1(*payload.PayloadID)
-}
-
-func (n *ethNode) insertBlock(eb engine.ExecutableData) error {
- if !eth2types(n.typ) {
- return errors.New("invalid node type")
- }
-
- switch n.typ {
- case eth2NormalNode, eth2MiningNode:
- newResp, err := n.api.NewPayloadV1(eb)
- if err != nil {
- return err
- } else if newResp.Status != "VALID" {
- return errors.New("failed to insert block")
- }
-
- return nil
- case eth2LightClient:
- newResp, err := n.lapi.ExecutePayloadV1(eb)
- if err != nil {
- return err
- } else if newResp.Status != "VALID" {
- return errors.New("failed to insert block")
- }
-
- return nil
- default:
- return errors.New("undefined node")
- }
-}
-
-func (n *ethNode) insertBlockAndSetHead(_ *types.Header, ed engine.ExecutableData) error {
- if !eth2types(n.typ) {
- return errors.New("invalid node type")
- }
-
- if err := n.insertBlock(ed); err != nil {
- return err
- }
-
- block, err := engine.ExecutableDataToBlock(ed)
- if err != nil {
- return err
- }
-
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: block.ParentHash(),
- SafeBlockHash: common.Hash{},
- FinalizedBlockHash: common.Hash{},
- }
-
- switch n.typ {
- case eth2NormalNode, eth2MiningNode:
- if _, err := n.api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
- return err
- }
-
- return nil
- case eth2LightClient:
- if _, err := n.lapi.ForkchoiceUpdatedV1(fcState, nil); err != nil {
- return err
- }
-
- return nil
- default:
- return errors.New("undefined node")
- }
-}
-
-type nodeManager struct {
- genesis *core.Genesis
- genesisBlock *types.Block
- nodes []*ethNode
- enodes []*enode.Node
- close chan struct{}
-}
-
-func newNodeManager(genesis *core.Genesis) *nodeManager {
- return &nodeManager{
- close: make(chan struct{}),
- genesis: genesis,
- genesisBlock: genesis.ToBlock(),
- }
-}
-
-func (mgr *nodeManager) createNode(typ nodetype) {
- node := newNode(typ, mgr.genesis, mgr.enodes)
- mgr.nodes = append(mgr.nodes, node)
- mgr.enodes = append(mgr.enodes, node.enode)
-}
-
-func (mgr *nodeManager) getNodes(typ nodetype) []*ethNode {
- var ret []*ethNode
-
- for _, node := range mgr.nodes {
- if node.typ == typ {
- ret = append(ret, node)
- }
- }
-
- return ret
-}
-
-func (mgr *nodeManager) startMining() {
- for _, node := range append(mgr.getNodes(eth2MiningNode), mgr.getNodes(legacyMiningNode)...) {
- if err := node.ethBackend.StartMining(1); err != nil {
- panic(err)
- }
- }
-}
-
-func (mgr *nodeManager) shutdown() {
- close(mgr.close)
-
- for _, node := range mgr.nodes {
- node.stack.Close()
- }
-}
-
-func (mgr *nodeManager) run() {
- if len(mgr.nodes) == 0 {
- return
- }
-
- chain := mgr.nodes[0].ethBackend.BlockChain()
- sink := make(chan core.ChainHeadEvent, 1024)
-
- sub := chain.SubscribeChainHeadEvent(sink)
- defer sub.Unsubscribe()
-
- var (
- transitioned bool
- parentBlock *types.Block
- waitFinalise []*types.Block
- )
-
- timer := time.NewTimer(0)
- defer timer.Stop()
- <-timer.C // discard the initial tick
-
- // Handle the by default transition.
- if transitionDifficulty.Sign() == 0 {
- transitioned = true
- parentBlock = mgr.genesisBlock
-
- timer.Reset(blockInterval)
- log.Info("Enable the transition by default")
- }
-
- // Handle the block finalization.
- checkFinalise := func() {
- if parentBlock == nil {
- return
- }
-
- if len(waitFinalise) == 0 {
- return
- }
-
- oldest := waitFinalise[0]
- if oldest.NumberU64() > parentBlock.NumberU64() {
- return
- }
-
- distance := parentBlock.NumberU64() - oldest.NumberU64()
- if int(distance) < finalizationDist {
- return
- }
-
- nodes := mgr.getNodes(eth2MiningNode)
- nodes = append(nodes, mgr.getNodes(eth2NormalNode)...)
- //nodes = append(nodes, mgr.getNodes(eth2LightClient)...)
- for _, node := range nodes {
- fcState := engine.ForkchoiceStateV1{
- HeadBlockHash: parentBlock.Hash(),
- SafeBlockHash: oldest.Hash(),
- FinalizedBlockHash: oldest.Hash(),
- }
- _, _ = node.api.ForkchoiceUpdatedV1(fcState, nil)
- }
-
- log.Info("Finalised eth2 block", "number", oldest.NumberU64(), "hash", oldest.Hash())
-
- waitFinalise = waitFinalise[1:]
- }
-
- for {
- checkFinalise()
- select {
- case <-mgr.close:
- return
-
- case ev := <-sink:
- if transitioned {
- continue
- }
-
- td := chain.GetTd(ev.Block.Hash(), ev.Block.NumberU64())
- if td.Cmp(transitionDifficulty) < 0 {
- continue
- }
-
- transitioned, parentBlock = true, ev.Block
-
- timer.Reset(blockInterval)
- log.Info("Transition difficulty reached", "td", td, "target", transitionDifficulty, "number", ev.Block.NumberU64(), "hash", ev.Block.Hash())
-
- case <-timer.C:
- producers := mgr.getNodes(eth2MiningNode)
- if len(producers) == 0 {
- continue
- }
-
- hash, timestamp := parentBlock.Hash(), parentBlock.Time()
- if parentBlock.NumberU64() == 0 {
- timestamp = uint64(time.Now().Unix()) - uint64(blockIntervalInt)
- }
-
- ed, err := producers[0].assembleBlock(hash, timestamp)
- if err != nil {
- log.Error("Failed to assemble the block", "err", err)
- continue
- }
-
- block, _ := engine.ExecutableDataToBlock(*ed)
-
- nodes := mgr.getNodes(eth2MiningNode)
- nodes = append(nodes, mgr.getNodes(eth2NormalNode)...)
- nodes = append(nodes, mgr.getNodes(eth2LightClient)...)
-
- for _, node := range nodes {
- if err := node.insertBlockAndSetHead(parentBlock.Header(), *ed); err != nil {
- log.Error("Failed to insert block", "type", node.typ, "err", err)
- }
- }
-
- log.Info("Create and insert eth2 block", "number", ed.Number)
-
- parentBlock = block
- waitFinalise = append(waitFinalise, block)
-
- timer.Reset(blockInterval)
- }
- }
-}
-
-func main() {
- log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
- fdlimit.Raise(2048)
-
- // Generate a batch of accounts to seal and fund with
- faucets := make([]*ecdsa.PrivateKey, 16)
- for i := 0; i < len(faucets); i++ {
- faucets[i], _ = crypto.GenerateKey()
- }
- // Pre-generate the ethash mining DAG so we don't race
- ethash.MakeDataset(1, filepath.Join(os.Getenv("HOME"), ".ethash"))
-
- // Create an Ethash network
- genesis := makeGenesis(faucets)
-
- manager := newNodeManager(genesis)
- defer manager.shutdown()
-
- manager.createNode(eth2NormalNode)
- manager.createNode(eth2MiningNode)
- manager.createNode(legacyMiningNode)
- manager.createNode(legacyNormalNode)
- manager.createNode(eth2LightClient)
-
- // Iterate over all the nodes and start mining
- time.Sleep(3 * time.Second)
-
- if transitionDifficulty.Sign() != 0 {
- manager.startMining()
- }
-
- go manager.run()
-
- // Start injecting transactions from the faucets like crazy
- time.Sleep(3 * time.Second)
-
- nonces := make([]uint64, len(faucets))
-
- for {
- // Pick a random mining node
- nodes := manager.getNodes(eth2MiningNode)
-
- index := rand.Intn(len(faucets))
- node := nodes[index%len(nodes)]
-
- // Create a self transaction and inject into the pool
- // nolint:gosec
- tx, err := types.SignTx(types.NewTransaction(nonces[index], crypto.PubkeyToAddress(faucets[index].PublicKey), new(big.Int), 21000, big.NewInt(10_000_000_000+rand.Int63n(6_553_600_000)), nil), types.HomesteadSigner{}, faucets[index])
- if err != nil {
- panic(err)
- }
-
- if err := node.ethBackend.TxPool().AddLocal(tx); err != nil {
- panic(err)
- }
-
- nonces[index]++
-
- // Wait if we're too saturated
- if pend, _ := node.ethBackend.TxPool().Stats(); pend > 2048 {
- time.Sleep(100 * time.Millisecond)
- }
- }
-}
-
-// makeGenesis creates a custom Ethash genesis block based on some pre-defined
-// faucet accounts.
-func makeGenesis(faucets []*ecdsa.PrivateKey) *core.Genesis {
- genesis := core.DefaultGenesisBlock()
- genesis.Difficulty = params.MinimumDifficulty
- genesis.GasLimit = 25000000
-
- genesis.BaseFee = big.NewInt(params.InitialBaseFee)
- genesis.Config = params.AllEthashProtocolChanges
- genesis.Config.TerminalTotalDifficulty = transitionDifficulty
-
- genesis.Alloc = core.GenesisAlloc{}
- for _, faucet := range faucets {
- genesis.Alloc[crypto.PubkeyToAddress(faucet.PublicKey)] = core.GenesisAccount{
- Balance: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil),
- }
- }
-
- return genesis
-}
-
-func makeFullNode(genesis *core.Genesis) (*node.Node, *eth.Ethereum, *ethcatalyst.ConsensusAPI, error) {
- // Define the basic configurations for the Ethereum node
- datadir, _ := os.MkdirTemp("", "")
-
- config := &node.Config{
- Name: "geth",
- Version: params.Version,
- DataDir: datadir,
- P2P: p2p.Config{
- ListenAddr: "0.0.0.0:0",
- NoDiscovery: true,
- MaxPeers: 25,
- },
- UseLightweightKDF: true,
- }
- // Create the node and configure a full Ethereum node on it
- stack, err := node.New(config)
- if err != nil {
- return nil, nil, nil, err
- }
-
- econfig := ðconfig.Config{
- Genesis: genesis,
- NetworkId: genesis.Config.ChainID.Uint64(),
- SyncMode: downloader.FullSync,
- DatabaseCache: 256,
- DatabaseHandles: 256,
- TxPool: txpool.DefaultConfig,
- GPO: ethconfig.Defaults.GPO,
- Ethash: ethconfig.Defaults.Ethash,
- Miner: miner.Config{
- GasFloor: genesis.GasLimit * 9 / 10,
- GasCeil: genesis.GasLimit * 11 / 10,
- GasPrice: big.NewInt(1),
- Recommit: 1 * time.Second,
- },
- LightServ: 100,
- LightPeers: 10,
- LightNoSyncServe: true,
- }
-
- ethBackend, err := eth.New(stack, econfig)
- if err != nil {
- return nil, nil, nil, err
- }
-
- _, err = les.NewLesServer(stack, ethBackend, econfig)
- if err != nil {
- log.Crit("Failed to create the LES server", "err", err)
- }
-
- err = stack.Start()
-
- return stack, ethBackend, ethcatalyst.NewConsensusAPI(ethBackend), err
-}
-
-func makeLightNode(genesis *core.Genesis) (*node.Node, *les.LightEthereum, *lescatalyst.ConsensusAPI, error) {
- // Define the basic configurations for the Ethereum node
- datadir, _ := os.MkdirTemp("", "")
-
- config := &node.Config{
- Name: "geth",
- Version: params.Version,
- DataDir: datadir,
- P2P: p2p.Config{
- ListenAddr: "0.0.0.0:0",
- NoDiscovery: true,
- MaxPeers: 25,
- },
- UseLightweightKDF: true,
- }
- // Create the node and configure a full Ethereum node on it
- stack, err := node.New(config)
- if err != nil {
- return nil, nil, nil, err
- }
-
- lesBackend, err := les.New(stack, ðconfig.Config{
- Genesis: genesis,
- NetworkId: genesis.Config.ChainID.Uint64(),
- SyncMode: downloader.LightSync,
- DatabaseCache: 256,
- DatabaseHandles: 256,
- TxPool: txpool.DefaultConfig,
- GPO: ethconfig.Defaults.GPO,
- Ethash: ethconfig.Defaults.Ethash,
- LightPeers: 10,
- })
- if err != nil {
- return nil, nil, nil, err
- }
-
- err = stack.Start()
-
- return stack, lesBackend, lescatalyst.NewConsensusAPI(lesBackend), err
-}
-
-func eth2types(typ nodetype) bool {
- if typ == eth2LightClient || typ == eth2NormalNode || typ == eth2MiningNode {
- return true
- }
-
- return false
-}
+// import (
+// "crypto/ecdsa"
+// "errors"
+// "math/big"
+// "math/rand"
+// "os"
+// "path/filepath"
+// "time"
+
+// "github.com/ethereum/go-ethereum/accounts/keystore"
+// "github.com/ethereum/go-ethereum/beacon/engine"
+// "github.com/ethereum/go-ethereum/common"
+// "github.com/ethereum/go-ethereum/common/fdlimit"
+// "github.com/ethereum/go-ethereum/consensus/ethash"
+// "github.com/ethereum/go-ethereum/core"
+// "github.com/ethereum/go-ethereum/core/txpool"
+// "github.com/ethereum/go-ethereum/core/types"
+// "github.com/ethereum/go-ethereum/crypto"
+// "github.com/ethereum/go-ethereum/eth"
+// ethcatalyst "github.com/ethereum/go-ethereum/eth/catalyst"
+// "github.com/ethereum/go-ethereum/eth/downloader"
+// "github.com/ethereum/go-ethereum/eth/ethconfig"
+// "github.com/ethereum/go-ethereum/les"
+// lescatalyst "github.com/ethereum/go-ethereum/les/catalyst"
+// "github.com/ethereum/go-ethereum/log"
+// "github.com/ethereum/go-ethereum/miner"
+// "github.com/ethereum/go-ethereum/node"
+// "github.com/ethereum/go-ethereum/p2p"
+// "github.com/ethereum/go-ethereum/p2p/enode"
+// "github.com/ethereum/go-ethereum/params"
+// )
+
+// type nodetype int
+
+// const (
+// legacyMiningNode nodetype = iota
+// legacyNormalNode
+// eth2MiningNode
+// eth2NormalNode
+// eth2LightClient
+// )
+
+// func (typ nodetype) String() string {
+// switch typ {
+// case legacyMiningNode:
+// return "legacyMiningNode"
+// case legacyNormalNode:
+// return "legacyNormalNode"
+// case eth2MiningNode:
+// return "eth2MiningNode"
+// case eth2NormalNode:
+// return "eth2NormalNode"
+// case eth2LightClient:
+// return "eth2LightClient"
+// default:
+// return "undefined"
+// }
+// }
+
+// var (
+// // transitionDifficulty is the target total difficulty for transition
+// transitionDifficulty = new(big.Int).Mul(big.NewInt(20), params.MinimumDifficulty)
+
+// // blockInterval is the time interval for creating a new eth2 block
+// blockIntervalInt = 3
+// blockInterval = time.Second * time.Duration(blockIntervalInt)
+
+// // finalizationDist is the block distance for finalizing block
+// finalizationDist = 10
+// )
+
+// type ethNode struct {
+// typ nodetype
+// stack *node.Node
+// enode *enode.Node
+// api *ethcatalyst.ConsensusAPI
+// ethBackend *eth.Ethereum
+// lapi *lescatalyst.ConsensusAPI
+// lesBackend *les.LightEthereum
+// }
+
+// func newNode(typ nodetype, genesis *core.Genesis, enodes []*enode.Node) *ethNode {
+// var (
+// err error
+// api *ethcatalyst.ConsensusAPI
+// lapi *lescatalyst.ConsensusAPI
+// stack *node.Node
+// ethBackend *eth.Ethereum
+// lesBackend *les.LightEthereum
+// )
+// // Start the node and wait until it's up
+// if typ == eth2LightClient {
+// stack, lesBackend, lapi, err = makeLightNode(genesis)
+// } else {
+// stack, ethBackend, api, err = makeFullNode(genesis)
+// }
+
+// if err != nil {
+// panic(err)
+// }
+
+// for stack.Server().NodeInfo().Ports.Listener == 0 {
+// time.Sleep(250 * time.Millisecond)
+// }
+// // Connect the node to all the previous ones
+// for _, n := range enodes {
+// stack.Server().AddPeer(n)
+// }
+
+// enode := stack.Server().Self()
+
+// // Inject the signer key and start sealing with it
+// stack.AccountManager().AddBackend(keystore.NewPlaintextKeyStore("beacon-stress"))
+// ks := stack.AccountManager().Backends(keystore.KeyStoreType)
+
+// if len(ks) == 0 {
+// panic("Keystore is not available")
+// }
+
+// store := ks[0].(*keystore.KeyStore)
+// if _, err := store.NewAccount(""); err != nil {
+// panic(err)
+// }
+
+// return ðNode{
+// typ: typ,
+// api: api,
+// ethBackend: ethBackend,
+// lapi: lapi,
+// lesBackend: lesBackend,
+// stack: stack,
+// enode: enode,
+// }
+// }
+
+// func (n *ethNode) assembleBlock(parentHash common.Hash, parentTimestamp uint64) (*engine.ExecutableData, error) {
+// if n.typ != eth2MiningNode {
+// return nil, errors.New("invalid node type")
+// }
+
+// timestamp := uint64(time.Now().Unix())
+// if timestamp <= parentTimestamp {
+// timestamp = parentTimestamp + 1
+// }
+
+// payloadAttribute := engine.PayloadAttributes{
+// Timestamp: timestamp,
+// Random: common.Hash{},
+// SuggestedFeeRecipient: common.HexToAddress("0xdeadbeef"),
+// }
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: parentHash,
+// SafeBlockHash: common.Hash{},
+// FinalizedBlockHash: common.Hash{},
+// }
+
+// payload, err := n.api.ForkchoiceUpdatedV1(fcState, &payloadAttribute)
+// if err != nil {
+// return nil, err
+// }
+
+// time.Sleep(time.Second * 5) // give enough time for block creation
+
+// return n.api.GetPayloadV1(*payload.PayloadID)
+// }
+
+// func (n *ethNode) insertBlock(eb engine.ExecutableData) error {
+// if !eth2types(n.typ) {
+// return errors.New("invalid node type")
+// }
+
+// switch n.typ {
+// case eth2NormalNode, eth2MiningNode:
+// newResp, err := n.api.NewPayloadV1(eb)
+// if err != nil {
+// return err
+// } else if newResp.Status != "VALID" {
+// return errors.New("failed to insert block")
+// }
+
+// return nil
+// case eth2LightClient:
+// newResp, err := n.lapi.ExecutePayloadV1(eb)
+// if err != nil {
+// return err
+// } else if newResp.Status != "VALID" {
+// return errors.New("failed to insert block")
+// }
+
+// return nil
+// default:
+// return errors.New("undefined node")
+// }
+// }
+
+// func (n *ethNode) insertBlockAndSetHead(_ *types.Header, ed engine.ExecutableData) error {
+// if !eth2types(n.typ) {
+// return errors.New("invalid node type")
+// }
+
+// if err := n.insertBlock(ed); err != nil {
+// return err
+// }
+
+// block, err := engine.ExecutableDataToBlock(ed)
+// if err != nil {
+// return err
+// }
+
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: block.ParentHash(),
+// SafeBlockHash: common.Hash{},
+// FinalizedBlockHash: common.Hash{},
+// }
+
+// switch n.typ {
+// case eth2NormalNode, eth2MiningNode:
+// if _, err := n.api.ForkchoiceUpdatedV1(fcState, nil); err != nil {
+// return err
+// }
+
+// return nil
+// case eth2LightClient:
+// if _, err := n.lapi.ForkchoiceUpdatedV1(fcState, nil); err != nil {
+// return err
+// }
+
+// return nil
+// default:
+// return errors.New("undefined node")
+// }
+// }
+
+// type nodeManager struct {
+// genesis *core.Genesis
+// genesisBlock *types.Block
+// nodes []*ethNode
+// enodes []*enode.Node
+// close chan struct{}
+// }
+
+// func newNodeManager(genesis *core.Genesis) *nodeManager {
+// return &nodeManager{
+// close: make(chan struct{}),
+// genesis: genesis,
+// genesisBlock: genesis.ToBlock(),
+// }
+// }
+
+// func (mgr *nodeManager) createNode(typ nodetype) {
+// node := newNode(typ, mgr.genesis, mgr.enodes)
+// mgr.nodes = append(mgr.nodes, node)
+// mgr.enodes = append(mgr.enodes, node.enode)
+// }
+
+// func (mgr *nodeManager) getNodes(typ nodetype) []*ethNode {
+// var ret []*ethNode
+
+// for _, node := range mgr.nodes {
+// if node.typ == typ {
+// ret = append(ret, node)
+// }
+// }
+
+// return ret
+// }
+
+// func (mgr *nodeManager) startMining() {
+// for _, node := range append(mgr.getNodes(eth2MiningNode), mgr.getNodes(legacyMiningNode)...) {
+// if err := node.ethBackend.StartMining(1); err != nil {
+// panic(err)
+// }
+// }
+// }
+
+// func (mgr *nodeManager) shutdown() {
+// close(mgr.close)
+
+// for _, node := range mgr.nodes {
+// node.stack.Close()
+// }
+// }
+
+// func (mgr *nodeManager) run() {
+// if len(mgr.nodes) == 0 {
+// return
+// }
+
+// chain := mgr.nodes[0].ethBackend.BlockChain()
+// sink := make(chan core.ChainHeadEvent, 1024)
+
+// sub := chain.SubscribeChainHeadEvent(sink)
+// defer sub.Unsubscribe()
+
+// var (
+// transitioned bool
+// parentBlock *types.Block
+// waitFinalise []*types.Block
+// )
+
+// timer := time.NewTimer(0)
+// defer timer.Stop()
+// <-timer.C // discard the initial tick
+
+// // Handle the by default transition.
+// if transitionDifficulty.Sign() == 0 {
+// transitioned = true
+// parentBlock = mgr.genesisBlock
+
+// timer.Reset(blockInterval)
+// log.Info("Enable the transition by default")
+// }
+
+// // Handle the block finalization.
+// checkFinalise := func() {
+// if parentBlock == nil {
+// return
+// }
+
+// if len(waitFinalise) == 0 {
+// return
+// }
+
+// oldest := waitFinalise[0]
+// if oldest.NumberU64() > parentBlock.NumberU64() {
+// return
+// }
+
+// distance := parentBlock.NumberU64() - oldest.NumberU64()
+// if int(distance) < finalizationDist {
+// return
+// }
+
+// nodes := mgr.getNodes(eth2MiningNode)
+// nodes = append(nodes, mgr.getNodes(eth2NormalNode)...)
+// //nodes = append(nodes, mgr.getNodes(eth2LightClient)...)
+// for _, node := range nodes {
+// fcState := engine.ForkchoiceStateV1{
+// HeadBlockHash: parentBlock.Hash(),
+// SafeBlockHash: oldest.Hash(),
+// FinalizedBlockHash: oldest.Hash(),
+// }
+// _, _ = node.api.ForkchoiceUpdatedV1(fcState, nil)
+// }
+
+// log.Info("Finalised eth2 block", "number", oldest.NumberU64(), "hash", oldest.Hash())
+
+// waitFinalise = waitFinalise[1:]
+// }
+
+// for {
+// checkFinalise()
+// select {
+// case <-mgr.close:
+// return
+
+// case ev := <-sink:
+// if transitioned {
+// continue
+// }
+
+// td := chain.GetTd(ev.Block.Hash(), ev.Block.NumberU64())
+// if td.Cmp(transitionDifficulty) < 0 {
+// continue
+// }
+
+// transitioned, parentBlock = true, ev.Block
+
+// timer.Reset(blockInterval)
+// log.Info("Transition difficulty reached", "td", td, "target", transitionDifficulty, "number", ev.Block.NumberU64(), "hash", ev.Block.Hash())
+
+// case <-timer.C:
+// producers := mgr.getNodes(eth2MiningNode)
+// if len(producers) == 0 {
+// continue
+// }
+
+// hash, timestamp := parentBlock.Hash(), parentBlock.Time()
+// if parentBlock.NumberU64() == 0 {
+// timestamp = uint64(time.Now().Unix()) - uint64(blockIntervalInt)
+// }
+
+// ed, err := producers[0].assembleBlock(hash, timestamp)
+// if err != nil {
+// log.Error("Failed to assemble the block", "err", err)
+// continue
+// }
+
+// block, _ := engine.ExecutableDataToBlock(*ed)
+
+// nodes := mgr.getNodes(eth2MiningNode)
+// nodes = append(nodes, mgr.getNodes(eth2NormalNode)...)
+// nodes = append(nodes, mgr.getNodes(eth2LightClient)...)
+
+// for _, node := range nodes {
+// if err := node.insertBlockAndSetHead(parentBlock.Header(), *ed); err != nil {
+// log.Error("Failed to insert block", "type", node.typ, "err", err)
+// }
+// }
+
+// log.Info("Create and insert eth2 block", "number", ed.Number)
+
+// parentBlock = block
+// waitFinalise = append(waitFinalise, block)
+
+// timer.Reset(blockInterval)
+// }
+// }
+// }
+
+// func main() {
+// log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
+// fdlimit.Raise(2048)
+
+// // Generate a batch of accounts to seal and fund with
+// faucets := make([]*ecdsa.PrivateKey, 16)
+// for i := 0; i < len(faucets); i++ {
+// faucets[i], _ = crypto.GenerateKey()
+// }
+// // Pre-generate the ethash mining DAG so we don't race
+// ethash.MakeDataset(1, filepath.Join(os.Getenv("HOME"), ".ethash"))
+
+// // Create an Ethash network
+// genesis := makeGenesis(faucets)
+
+// manager := newNodeManager(genesis)
+// defer manager.shutdown()
+
+// manager.createNode(eth2NormalNode)
+// manager.createNode(eth2MiningNode)
+// manager.createNode(legacyMiningNode)
+// manager.createNode(legacyNormalNode)
+// manager.createNode(eth2LightClient)
+
+// // Iterate over all the nodes and start mining
+// time.Sleep(3 * time.Second)
+
+// if transitionDifficulty.Sign() != 0 {
+// manager.startMining()
+// }
+
+// go manager.run()
+
+// // Start injecting transactions from the faucets like crazy
+// time.Sleep(3 * time.Second)
+
+// nonces := make([]uint64, len(faucets))
+
+// for {
+// // Pick a random mining node
+// nodes := manager.getNodes(eth2MiningNode)
+
+// index := rand.Intn(len(faucets))
+// node := nodes[index%len(nodes)]
+
+// // Create a self transaction and inject into the pool
+// // nolint:gosec
+// tx, err := types.SignTx(types.NewTransaction(nonces[index], crypto.PubkeyToAddress(faucets[index].PublicKey), new(big.Int), 21000, big.NewInt(10_000_000_000+rand.Int63n(6_553_600_000)), nil), types.HomesteadSigner{}, faucets[index])
+// if err != nil {
+// panic(err)
+// }
+
+// if err := node.ethBackend.TxPool().AddLocal(tx); err != nil {
+// panic(err)
+// }
+
+// nonces[index]++
+
+// // Wait if we're too saturated
+// if pend, _ := node.ethBackend.TxPool().Stats(); pend > 2048 {
+// time.Sleep(100 * time.Millisecond)
+// }
+// }
+// }
+
+// // makeGenesis creates a custom Ethash genesis block based on some pre-defined
+// // faucet accounts.
+// func makeGenesis(faucets []*ecdsa.PrivateKey) *core.Genesis {
+// genesis := core.DefaultGenesisBlock()
+// genesis.Difficulty = params.MinimumDifficulty
+// genesis.GasLimit = 25000000
+
+// genesis.BaseFee = big.NewInt(params.InitialBaseFee)
+// genesis.Config = params.AllEthashProtocolChanges
+// genesis.Config.TerminalTotalDifficulty = transitionDifficulty
+
+// genesis.Alloc = core.GenesisAlloc{}
+// for _, faucet := range faucets {
+// genesis.Alloc[crypto.PubkeyToAddress(faucet.PublicKey)] = core.GenesisAccount{
+// Balance: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil),
+// }
+// }
+
+// return genesis
+// }
+
+// func makeFullNode(genesis *core.Genesis) (*node.Node, *eth.Ethereum, *ethcatalyst.ConsensusAPI, error) {
+// // Define the basic configurations for the Ethereum node
+// datadir, _ := os.MkdirTemp("", "")
+
+// config := &node.Config{
+// Name: "geth",
+// Version: params.Version,
+// DataDir: datadir,
+// P2P: p2p.Config{
+// ListenAddr: "0.0.0.0:0",
+// NoDiscovery: true,
+// MaxPeers: 25,
+// },
+// UseLightweightKDF: true,
+// }
+// // Create the node and configure a full Ethereum node on it
+// stack, err := node.New(config)
+// if err != nil {
+// return nil, nil, nil, err
+// }
+
+// econfig := ðconfig.Config{
+// Genesis: genesis,
+// NetworkId: genesis.Config.ChainID.Uint64(),
+// SyncMode: downloader.FullSync,
+// DatabaseCache: 256,
+// DatabaseHandles: 256,
+// TxPool: txpool.DefaultConfig,
+// GPO: ethconfig.Defaults.GPO,
+// Ethash: ethconfig.Defaults.Ethash,
+// Miner: miner.Config{
+// GasFloor: genesis.GasLimit * 9 / 10,
+// GasCeil: genesis.GasLimit * 11 / 10,
+// GasPrice: big.NewInt(1),
+// Recommit: 1 * time.Second,
+// },
+// LightServ: 100,
+// LightPeers: 10,
+// LightNoSyncServe: true,
+// }
+
+// ethBackend, err := eth.New(stack, econfig)
+// if err != nil {
+// return nil, nil, nil, err
+// }
+
+// _, err = les.NewLesServer(stack, ethBackend, econfig)
+// if err != nil {
+// log.Crit("Failed to create the LES server", "err", err)
+// }
+
+// err = stack.Start()
+
+// return stack, ethBackend, ethcatalyst.NewConsensusAPI(ethBackend), err
+// }
+
+// func makeLightNode(genesis *core.Genesis) (*node.Node, *les.LightEthereum, *lescatalyst.ConsensusAPI, error) {
+// // Define the basic configurations for the Ethereum node
+// datadir, _ := os.MkdirTemp("", "")
+
+// config := &node.Config{
+// Name: "geth",
+// Version: params.Version,
+// DataDir: datadir,
+// P2P: p2p.Config{
+// ListenAddr: "0.0.0.0:0",
+// NoDiscovery: true,
+// MaxPeers: 25,
+// },
+// UseLightweightKDF: true,
+// }
+// // Create the node and configure a full Ethereum node on it
+// stack, err := node.New(config)
+// if err != nil {
+// return nil, nil, nil, err
+// }
+
+// lesBackend, err := les.New(stack, ðconfig.Config{
+// Genesis: genesis,
+// NetworkId: genesis.Config.ChainID.Uint64(),
+// SyncMode: downloader.LightSync,
+// DatabaseCache: 256,
+// DatabaseHandles: 256,
+// TxPool: txpool.DefaultConfig,
+// GPO: ethconfig.Defaults.GPO,
+// Ethash: ethconfig.Defaults.Ethash,
+// LightPeers: 10,
+// })
+// if err != nil {
+// return nil, nil, nil, err
+// }
+
+// err = stack.Start()
+
+// return stack, lesBackend, lescatalyst.NewConsensusAPI(lesBackend), err
+// }
+
+// func eth2types(typ nodetype) bool {
+// if typ == eth2LightClient || typ == eth2NormalNode || typ == eth2MiningNode {
+// return true
+// }
+
+// return false
+// }
diff --git a/params/config.go b/params/config.go
index 5c82c7b848..39552c284c 100644
--- a/params/config.go
+++ b/params/config.go
@@ -81,7 +81,6 @@ var (
GrayGlacierBlock: big.NewInt(15_050_000),
TerminalTotalDifficulty: MainnetTerminalTotalDifficulty, // 58_750_000_000_000_000_000_000
TerminalTotalDifficultyPassed: true,
- ShanghaiTime: newUint64(1681338455),
Ethash: new(EthashConfig),
}
@@ -125,7 +124,6 @@ var (
TerminalTotalDifficulty: big.NewInt(17_000_000_000_000_000),
TerminalTotalDifficultyPassed: true,
MergeNetsplitBlock: big.NewInt(1735371),
- ShanghaiTime: newUint64(1677557088),
Ethash: new(EthashConfig),
}
@@ -199,7 +197,6 @@ var (
ArrowGlacierBlock: nil,
TerminalTotalDifficulty: big.NewInt(10_790_000),
TerminalTotalDifficultyPassed: true,
- ShanghaiTime: newUint64(1678832736),
Clique: &CliqueConfig{
Period: 15,
Epoch: 30000,
@@ -445,9 +442,9 @@ var (
ArrowGlacierBlock: big.NewInt(0),
GrayGlacierBlock: big.NewInt(0),
MergeNetsplitBlock: nil,
- ShanghaiTime: nil,
- CancunTime: nil,
- PragueTime: nil,
+ ShanghaiBlock: nil,
+ CancunBlock: nil,
+ PragueBlock: nil,
TerminalTotalDifficulty: nil,
TerminalTotalDifficultyPassed: false,
Ethash: new(EthashConfig),
@@ -475,9 +472,9 @@ var (
ArrowGlacierBlock: nil,
GrayGlacierBlock: nil,
MergeNetsplitBlock: nil,
- ShanghaiTime: nil,
- CancunTime: nil,
- PragueTime: nil,
+ ShanghaiBlock: nil,
+ CancunBlock: nil,
+ PragueBlock: nil,
TerminalTotalDifficulty: nil,
TerminalTotalDifficultyPassed: false,
Ethash: nil,
@@ -505,9 +502,9 @@ var (
ArrowGlacierBlock: big.NewInt(0),
GrayGlacierBlock: big.NewInt(0),
MergeNetsplitBlock: nil,
- ShanghaiTime: nil,
- CancunTime: nil,
- PragueTime: nil,
+ ShanghaiBlock: nil,
+ CancunBlock: nil,
+ PragueBlock: nil,
TerminalTotalDifficulty: nil,
TerminalTotalDifficultyPassed: false,
Ethash: new(EthashConfig),
@@ -538,9 +535,9 @@ var (
ArrowGlacierBlock: nil,
GrayGlacierBlock: nil,
MergeNetsplitBlock: nil,
- ShanghaiTime: nil,
- CancunTime: nil,
- PragueTime: nil,
+ ShanghaiBlock: nil,
+ CancunBlock: nil,
+ PragueBlock: nil,
TerminalTotalDifficulty: nil,
TerminalTotalDifficultyPassed: false,
Ethash: new(EthashConfig),
@@ -640,10 +637,10 @@ type ChainConfig struct {
MergeNetsplitBlock *big.Int `json:"mergeNetsplitBlock,omitempty"` // Virtual fork after The Merge to use as a network splitter
// Fork scheduling was switched from blocks to timestamps here
-
- ShanghaiTime *uint64 `json:"shanghaiTime,omitempty"` // Shanghai switch time (nil = no fork, 0 = already on shanghai)
- CancunTime *uint64 `json:"cancunTime,omitempty"` // Cancun switch time (nil = no fork, 0 = already on cancun)
- PragueTime *uint64 `json:"pragueTime,omitempty"` // Prague switch time (nil = no fork, 0 = already on prague)
+ // Fork scheduling switched back to blockNumber in Bor
+ ShanghaiBlock *big.Int `json:"shanghaiBlock,omitempty"` // Shanghai switch Block (nil = no fork, 0 = already on shanghai)
+ CancunBlock *big.Int `json:"cancunBlock,omitempty"` // Cancun switch Block (nil = no fork, 0 = already on cancun)
+ PragueBlock *big.Int `json:"pragueBlock,omitempty"` // Prague switch Block (nil = no fork, 0 = already on prague)
// TerminalTotalDifficulty is the amount of total difficulty reached by
// the network that triggers the consensus upgrade.
@@ -900,16 +897,16 @@ func (c *ChainConfig) Description() string {
// Create a list of forks post-merge
banner += "Post-Merge hard forks (timestamp based):\n"
- if c.ShanghaiTime != nil {
- banner += fmt.Sprintf(" - Shanghai: @%-10v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md)\n", *c.ShanghaiTime)
+ if c.ShanghaiBlock != nil {
+ banner += fmt.Sprintf(" - Shanghai: @%-10v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md)\n", *c.ShanghaiBlock)
}
- if c.CancunTime != nil {
- banner += fmt.Sprintf(" - Cancun: @%-10v\n", *c.CancunTime)
+ if c.CancunBlock != nil {
+ banner += fmt.Sprintf(" - Cancun: @%-10v\n", *c.CancunBlock)
}
- if c.PragueTime != nil {
- banner += fmt.Sprintf(" - Prague: @%-10v\n", *c.PragueTime)
+ if c.PragueBlock != nil {
+ banner += fmt.Sprintf(" - Prague: @%-10v\n", *c.PragueBlock)
}
return banner
@@ -998,18 +995,18 @@ func (c *ChainConfig) IsTerminalPoWBlock(parentTotalDiff *big.Int, totalDiff *bi
// IsShanghai returns whether time is either equal to the Shanghai fork time or greater.
// TODO marcello double check
-func (c *ChainConfig) IsShanghai(time uint64) bool {
- return isTimestampForked(c.ShanghaiTime, time)
+func (c *ChainConfig) IsShanghai(num *big.Int) bool {
+ return isBlockForked(c.ShanghaiBlock, num)
}
// IsCancun returns whether num is either equal to the Cancun fork time or greater.
-func (c *ChainConfig) IsCancun(time uint64) bool {
- return isTimestampForked(c.CancunTime, time)
+func (c *ChainConfig) IsCancun(num *big.Int) bool {
+ return isBlockForked(c.CancunBlock, num)
}
// IsPrague returns whether num is either equal to the Prague fork time or greater.
-func (c *ChainConfig) IsPrague(time uint64) bool {
- return isTimestampForked(c.PragueTime, time)
+func (c *ChainConfig) IsPrague(num *big.Int) bool {
+ return isBlockForked(c.PragueBlock, num)
}
// CheckCompatible checks whether scheduled fork transitions have been imported
@@ -1067,9 +1064,9 @@ func (c *ChainConfig) CheckConfigForkOrder() error {
{name: "arrowGlacierBlock", block: c.ArrowGlacierBlock, optional: true},
{name: "grayGlacierBlock", block: c.GrayGlacierBlock, optional: true},
{name: "mergeNetsplitBlock", block: c.MergeNetsplitBlock, optional: true},
- {name: "shanghaiTime", timestamp: c.ShanghaiTime},
- {name: "cancunTime", timestamp: c.CancunTime, optional: true},
- {name: "pragueTime", timestamp: c.PragueTime, optional: true},
+ {name: "shanghaiTime", block: c.ShanghaiBlock},
+ {name: "cancunTime", block: c.CancunBlock, optional: true},
+ {name: "pragueTime", block: c.PragueBlock, optional: true},
} {
if lastFork.name != "" {
switch {
@@ -1182,16 +1179,16 @@ func (c *ChainConfig) checkCompatible(newcfg *ChainConfig, headNumber *big.Int,
return newBlockCompatError("Merge netsplit fork block", c.MergeNetsplitBlock, newcfg.MergeNetsplitBlock)
}
- if isForkTimestampIncompatible(c.ShanghaiTime, newcfg.ShanghaiTime, headTimestamp) {
- return newTimestampCompatError("Shanghai fork timestamp", c.ShanghaiTime, newcfg.ShanghaiTime)
+ if isForkBlockIncompatible(c.ShanghaiBlock, newcfg.ShanghaiBlock, headNumber) {
+ return newBlockCompatError("Shanghai fork block", c.ShanghaiBlock, newcfg.ShanghaiBlock)
}
- if isForkTimestampIncompatible(c.CancunTime, newcfg.CancunTime, headTimestamp) {
- return newTimestampCompatError("Cancun fork timestamp", c.CancunTime, newcfg.CancunTime)
+ if isForkBlockIncompatible(c.CancunBlock, newcfg.CancunBlock, headNumber) {
+ return newBlockCompatError("Cancun fork block", c.CancunBlock, newcfg.CancunBlock)
}
- if isForkTimestampIncompatible(c.PragueTime, newcfg.PragueTime, headTimestamp) {
- return newTimestampCompatError("Prague fork timestamp", c.PragueTime, newcfg.PragueTime)
+ if isForkBlockIncompatible(c.PragueBlock, newcfg.PragueBlock, headNumber) {
+ return newBlockCompatError("Prague fork block", c.PragueBlock, newcfg.PragueBlock)
}
return nil
@@ -1375,8 +1372,8 @@ func (c *ChainConfig) Rules(num *big.Int, isMerge bool, timestamp uint64) Rules
IsBerlin: c.IsBerlin(num),
IsLondon: c.IsLondon(num),
IsMerge: isMerge,
- IsShanghai: c.IsShanghai(timestamp),
- IsCancun: c.IsCancun(timestamp),
- IsPrague: c.IsPrague(timestamp),
+ IsShanghai: c.IsShanghai(num),
+ IsCancun: c.IsCancun(num),
+ IsPrague: c.IsPrague(num),
}
}
diff --git a/params/config_test.go b/params/config_test.go
index 713fbaf880..a26b0c4e7b 100644
--- a/params/config_test.go
+++ b/params/config_test.go
@@ -94,17 +94,17 @@ 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)},
+ stored: &ChainConfig{ShanghaiBlock: big.NewInt(30)},
+ new: &ChainConfig{ShanghaiBlock: big.NewInt(30)},
headTimestamp: 25,
wantErr: &ConfigCompatError{
- What: "Shanghai fork timestamp",
+ What: "Shanghai fork Block",
StoredTime: newUint64(10),
NewTime: newUint64(20),
RewindToTime: 9,
@@ -124,24 +124,24 @@ func TestConfigRules(t *testing.T) {
t.Parallel()
c := &ChainConfig{
- ShanghaiTime: newUint64(500),
+ ShanghaiBlock: big.NewInt(10),
}
- var stamp uint64
+ var block *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)
}
}
diff --git a/tests/init.go b/tests/init.go
index 13456feb9a..e81c7823b3 100644
--- a/tests/init.go
+++ b/tests/init.go
@@ -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,
},
}