diff --git a/accounts/abi/bind/backends/simulated.go b/accounts/abi/bind/backends/simulated.go index 6d0891111..3b8ebe1f3 100644 --- a/accounts/abi/bind/backends/simulated.go +++ b/accounts/abi/bind/backends/simulated.go @@ -87,8 +87,8 @@ type SimulatedBackend struct { // NewSimulatedBackend creates a new binding backend using a simulated blockchain // for testing purposes. -func NewSimulatedBackendWithConfig(alloc core.GenesisAlloc, config *chain.Config, gasLimit uint64) *SimulatedBackend { - genesis := core.Genesis{Config: config, GasLimit: gasLimit, Alloc: alloc} +func NewSimulatedBackendWithConfig(alloc types.GenesisAlloc, config *chain.Config, gasLimit uint64) *SimulatedBackend { + genesis := types.Genesis{Config: config, GasLimit: gasLimit, Alloc: alloc} engine := ethash.NewFaker() m := stages.MockWithGenesisEngine(nil, &genesis, engine, false) backend := &SimulatedBackend{ @@ -109,7 +109,7 @@ func NewSimulatedBackendWithConfig(alloc core.GenesisAlloc, config *chain.Config } // A simulated backend always uses chainID 1337. -func NewSimulatedBackend(t *testing.T, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { +func NewSimulatedBackend(t *testing.T, alloc types.GenesisAlloc, gasLimit uint64) *SimulatedBackend { b := NewSimulatedBackendWithConfig(alloc, params.TestChainConfig, gasLimit) t.Cleanup(func() { b.Close() @@ -120,7 +120,7 @@ func NewSimulatedBackend(t *testing.T, alloc core.GenesisAlloc, gasLimit uint64) return b } -func NewTestSimulatedBackendWithConfig(t *testing.T, alloc core.GenesisAlloc, config *chain.Config, gasLimit uint64) *SimulatedBackend { +func NewTestSimulatedBackendWithConfig(t *testing.T, alloc types.GenesisAlloc, config *chain.Config, gasLimit uint64) *SimulatedBackend { b := NewSimulatedBackendWithConfig(alloc, config, gasLimit) t.Cleanup(func() { b.Close() diff --git a/accounts/abi/bind/backends/simulated_test.go b/accounts/abi/bind/backends/simulated_test.go index 2e984e3db..287f2a126 100644 --- a/accounts/abi/bind/backends/simulated_test.go +++ b/accounts/abi/bind/backends/simulated_test.go @@ -34,7 +34,6 @@ import ( "github.com/ledgerwatch/erigon/accounts/abi/bind" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/common/u256" - "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/rawdb" "github.com/ledgerwatch/erigon/core/state" "github.com/ledgerwatch/erigon/core/types" @@ -46,8 +45,8 @@ func TestSimulatedBackend(t *testing.T) { var gasLimit uint64 = 8000029 key, _ := crypto.GenerateKey() // nolint: gosec auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337)) - genAlloc := make(core.GenesisAlloc) - genAlloc[auth.From] = core.GenesisAccount{Balance: big.NewInt(9223372036854775807)} + genAlloc := make(types.GenesisAlloc) + genAlloc[auth.From] = types.GenesisAccount{Balance: big.NewInt(9223372036854775807)} sim := NewSimulatedBackend(t, genAlloc, gasLimit) @@ -116,7 +115,7 @@ var expectedReturn = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 func simTestBackend(t *testing.T, testAddr libcommon.Address) *SimulatedBackend { expectedBal := uint256.NewInt(10000000000) return NewSimulatedBackend(t, - core.GenesisAlloc{ + types.GenesisAlloc{ testAddr: {Balance: expectedBal.ToBig()}, }, 10000000, ) @@ -158,7 +157,7 @@ func TestNewSimulatedBackend(t *testing.T) { func TestSimulatedBackend_AdjustTime(t *testing.T) { sim := NewSimulatedBackend(t, - core.GenesisAlloc{}, 10000000, + types.GenesisAlloc{}, 10000000, ) prevTime := sim.pendingBlock.Time() @@ -233,7 +232,7 @@ func TestSimulatedBackend_BalanceAt(t *testing.T) { func TestSimulatedBackend_BlockByHash(t *testing.T) { sim := NewSimulatedBackend(t, - core.GenesisAlloc{}, 10000000, + types.GenesisAlloc{}, 10000000, ) bgCtx := context.Background() @@ -253,7 +252,7 @@ func TestSimulatedBackend_BlockByHash(t *testing.T) { func TestSimulatedBackend_BlockByNumber(t *testing.T) { sim := NewSimulatedBackend(t, - core.GenesisAlloc{}, 10000000, + types.GenesisAlloc{}, 10000000, ) bgCtx := context.Background() @@ -370,7 +369,7 @@ func TestSimulatedBackend_TransactionByHash(t *testing.T) { testAddr := crypto.PubkeyToAddress(testKey.PublicKey) sim := NewSimulatedBackend(t, - core.GenesisAlloc{ + types.GenesisAlloc{ testAddr: {Balance: big.NewInt(10000000000)}, }, 10000000) bgCtx := context.Background() @@ -433,7 +432,7 @@ func TestSimulatedBackend_EstimateGas(t *testing.T) { addr := crypto.PubkeyToAddress(key.PublicKey) opts, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337)) - sim := NewSimulatedBackend(t, core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether)}}, 10000000) + sim := NewSimulatedBackend(t, types.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether)}}, 10000000) parsed, _ := abi.JSON(strings.NewReader(contractAbi)) contractAddr, _, _, _ := bind.DeployContract(opts, parsed, common.FromHex(contractBin), sim) @@ -537,7 +536,7 @@ func TestSimulatedBackend_EstimateGasWithPrice(t *testing.T) { key, _ := crypto.GenerateKey() addr := crypto.PubkeyToAddress(key.PublicKey) - sim := NewSimulatedBackend(t, core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether*2 + 2e17)}}, 10000000) + sim := NewSimulatedBackend(t, types.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether*2 + 2e17)}}, 10000000) recipient := libcommon.HexToAddress("deadbeef") var cases = []struct { @@ -875,7 +874,7 @@ func TestSimulatedBackend_TransactionReceipt(t *testing.T) { func TestSimulatedBackend_SuggestGasPrice(t *testing.T) { sim := NewSimulatedBackend(t, - core.GenesisAlloc{}, + types.GenesisAlloc{}, 10000000, ) bgCtx := context.Background() diff --git a/accounts/abi/bind/util_test.go b/accounts/abi/bind/util_test.go index d29880bfc..91a858d0e 100644 --- a/accounts/abi/bind/util_test.go +++ b/accounts/abi/bind/util_test.go @@ -25,12 +25,10 @@ import ( "time" libcommon "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon/accounts/abi/bind" "github.com/ledgerwatch/erigon/accounts/abi/bind/backends" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/common/u256" - "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/erigon/crypto" "github.com/ledgerwatch/erigon/params" @@ -67,7 +65,7 @@ func TestWaitDeployed(t *testing.T) { t.Run(name, func(t *testing.T) { backend := backends.NewSimulatedBackend(t, - core.GenesisAlloc{ + types.GenesisAlloc{ crypto.PubkeyToAddress(testKey.PublicKey): {Balance: big.NewInt(10000000000)}, }, 10000000, @@ -121,7 +119,7 @@ func TestWaitDeployedCornerCases(t *testing.T) { t.Skip("fix me on win please") } backend := backends.NewSimulatedBackend(t, - core.GenesisAlloc{ + types.GenesisAlloc{ crypto.PubkeyToAddress(testKey.PublicKey): {Balance: big.NewInt(10000000000)}, }, 10000000, diff --git a/cmd/evm/internal/t8ntool/execution.go b/cmd/evm/internal/t8ntool/execution.go index 559fed975..cc2369d7a 100644 --- a/cmd/evm/internal/t8ntool/execution.go +++ b/cmd/evm/internal/t8ntool/execution.go @@ -24,18 +24,16 @@ import ( "github.com/ledgerwatch/erigon-lib/chain" libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/kv" - "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/common/math" "github.com/ledgerwatch/erigon/consensus/ethash" - "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/state" "github.com/ledgerwatch/erigon/core/types" ) type Prestate struct { - Env stEnv `json:"env"` - Pre core.GenesisAlloc `json:"pre"` + Env stEnv `json:"env"` + Pre types.GenesisAlloc `json:"pre"` } type ommer struct { @@ -72,7 +70,7 @@ type stEnvMarshaling struct { BaseFee *math.HexOrDecimal256 } -func MakePreState(chainRules *chain.Rules, tx kv.RwTx, accounts core.GenesisAlloc) (*state.PlainStateReader, *state.PlainStateWriter) { +func MakePreState(chainRules *chain.Rules, tx kv.RwTx, accounts types.GenesisAlloc) (*state.PlainStateReader, *state.PlainStateWriter) { var blockNr uint64 = 0 stateReader, stateWriter := state.NewPlainStateReader(tx), state.NewPlainStateWriter(tx, tx, blockNr) statedb := state.New(stateReader) //ibs diff --git a/cmd/evm/internal/t8ntool/transition.go b/cmd/evm/internal/t8ntool/transition.go index d0dd21f46..d9df507f9 100644 --- a/cmd/evm/internal/t8ntool/transition.go +++ b/cmd/evm/internal/t8ntool/transition.go @@ -87,9 +87,9 @@ var ( ) type input struct { - Alloc core.GenesisAlloc `json:"alloc,omitempty"` - Env *stEnv `json:"env,omitempty"` - Txs []*txWithKey `json:"txs,omitempty"` + Alloc types.GenesisAlloc `json:"alloc,omitempty"` + Env *stEnv `json:"env,omitempty"` + Txs []*txWithKey `json:"txs,omitempty"` } func Main(ctx *cli.Context) error { @@ -487,7 +487,7 @@ func signUnsignedTransactions(txs []*txWithKey, signer types.Signer) (types.Tran return signedTxs, nil } -type Alloc map[libcommon.Address]core.GenesisAccount +type Alloc map[libcommon.Address]types.GenesisAccount func (g Alloc) OnRoot(libcommon.Hash) {} @@ -500,7 +500,7 @@ func (g Alloc) OnAccount(addr libcommon.Address, dumpAccount state.DumpAccount) storage[libcommon.HexToHash(k)] = libcommon.HexToHash(v) } } - genesisAccount := core.GenesisAccount{ + genesisAccount := types.GenesisAccount{ Code: dumpAccount.Code, Storage: storage, Balance: balance, diff --git a/cmd/evm/runner.go b/cmd/evm/runner.go index b69744885..bacd1982f 100644 --- a/cmd/evm/runner.go +++ b/cmd/evm/runner.go @@ -36,6 +36,7 @@ import ( "github.com/ledgerwatch/erigon-lib/common/hexutility" "github.com/ledgerwatch/erigon-lib/kv/kvcfg" "github.com/ledgerwatch/erigon-lib/kv/memdb" + "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/log/v3" "github.com/urfave/cli/v2" @@ -60,7 +61,7 @@ var runCommand = cli.Command{ // readGenesis will read the given JSON format genesis file and return // the initialized Genesis structure -func readGenesis(genesisPath string) *core.Genesis { +func readGenesis(genesisPath string) *types.Genesis { // Make sure we have a valid genesis JSON //genesisPath := ctx.Args().First() if len(genesisPath) == 0 { @@ -77,7 +78,7 @@ func readGenesis(genesisPath string) *core.Genesis { } }(file) - genesis := new(core.Genesis) + genesis := new(types.Genesis) if err := json.NewDecoder(file).Decode(genesis); err != nil { utils.Fatalf("invalid genesis file: %v", err) } @@ -137,7 +138,7 @@ func runCmd(ctx *cli.Context) error { chainConfig *chain.Config sender = libcommon.BytesToAddress([]byte("sender")) receiver = libcommon.BytesToAddress([]byte("receiver")) - genesisConfig *core.Genesis + genesisConfig *types.Genesis ) if ctx.Bool(MachineFlag.Name) { tracer = logger.NewJSONLogger(logconfig, os.Stdout) @@ -150,11 +151,11 @@ func runCmd(ctx *cli.Context) error { db := memdb.New("") if ctx.String(GenesisFlag.Name) != "" { gen := readGenesis(ctx.String(GenesisFlag.Name)) - gen.MustCommit(db, "") + core.MustCommitGenesis(gen, db, "") genesisConfig = gen chainConfig = gen.Config } else { - genesisConfig = new(core.Genesis) + genesisConfig = new(types.Genesis) } tx, err := db.BeginRw(context.Background()) if err != nil { diff --git a/cmd/integration/commands/state_domains.go b/cmd/integration/commands/state_domains.go index e8eb668dd..d3847a12b 100644 --- a/cmd/integration/commands/state_domains.go +++ b/cmd/integration/commands/state_domains.go @@ -425,9 +425,9 @@ func (b *blockProcessor) PrintStatsLoop(ctx context.Context, interval time.Durat } } -func (b *blockProcessor) ApplyGenesis(genesis *core.Genesis) error { +func (b *blockProcessor) ApplyGenesis(genesis *types.Genesis) error { b.logger.Info("apply genesis", "chain_id", genesis.Config.ChainID) - genBlock, genesisIbs, err := genesis.ToBlock("") + genBlock, genesisIbs, err := core.GenesisToBlock(genesis, "") if err != nil { return err } diff --git a/cmd/pics/state.go b/cmd/pics/state.go index 9d0214ecf..ae33a3640 100644 --- a/cmd/pics/state.go +++ b/cmd/pics/state.go @@ -273,9 +273,9 @@ func initialState1() error { address1 = crypto.PubkeyToAddress(key1.PublicKey) address2 = crypto.PubkeyToAddress(key2.PublicKey) theAddr = libcommon.Address{1} - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.AllProtocolChanges, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: big.NewInt(9000000000000000000)}, address1: {Balance: big.NewInt(200000000000000000)}, address2: {Balance: big.NewInt(300000000000000000)}, diff --git a/cmd/rpcdaemon/commands/erigon_receipts_test.go b/cmd/rpcdaemon/commands/erigon_receipts_test.go index 18304675c..92415eda2 100644 --- a/cmd/rpcdaemon/commands/erigon_receipts_test.go +++ b/cmd/rpcdaemon/commands/erigon_receipts_test.go @@ -222,9 +222,9 @@ func TestGetBlockReceiptsByBlockHash(t *testing.T) { // newTestBackend creates a chain with a number of explicitly defined blocks and // wraps it into a mock backend. func mockWithGenerator(t *testing.T, blocks int, generator func(int, *core.BlockGen)) *stages.MockSentry { - m := stages.MockWithGenesis(t, &core.Genesis{ + m := stages.MockWithGenesis(t, &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{testAddr: {Balance: big.NewInt(1000000)}}, + Alloc: types.GenesisAlloc{testAddr: {Balance: big.NewInt(1000000)}}, }, testKey, false) if blocks > 0 { chain, _ := core.GenerateChain(m.ChainConfig, m.Genesis, m.Engine, m.DB, blocks, generator, true) diff --git a/cmd/rpcdaemon/commands/eth_callMany_test.go b/cmd/rpcdaemon/commands/eth_callMany_test.go index 6c7036f41..0a1fd3666 100644 --- a/cmd/rpcdaemon/commands/eth_callMany_test.go +++ b/cmd/rpcdaemon/commands/eth_callMany_test.go @@ -14,7 +14,7 @@ import ( "github.com/ledgerwatch/erigon/accounts/abi/bind/backends" "github.com/ledgerwatch/erigon/cmd/rpcdaemon/commands/contracts" "github.com/ledgerwatch/erigon/common/hexutil" - "github.com/ledgerwatch/erigon/core" + "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/erigon/crypto" "github.com/ledgerwatch/erigon/params" "github.com/ledgerwatch/erigon/rpc" @@ -38,9 +38,9 @@ func TestCallMany(t *testing.T) { address = crypto.PubkeyToAddress(key.PublicKey) address1 = crypto.PubkeyToAddress(key1.PublicKey) address2 = crypto.PubkeyToAddress(key2.PublicKey) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: big.NewInt(9000000000000000000)}, address1: {Balance: big.NewInt(200000000000000000)}, address2: {Balance: big.NewInt(300000000000000000)}, diff --git a/cmd/rpcdaemon/commands/eth_call_test.go b/cmd/rpcdaemon/commands/eth_call_test.go index 90636d530..44f66172b 100644 --- a/cmd/rpcdaemon/commands/eth_call_test.go +++ b/cmd/rpcdaemon/commands/eth_call_test.go @@ -551,9 +551,9 @@ func chainWithDeployedContract(t *testing.T) (*stages.MockSentry, libcommon.Addr bankAddress = crypto.PubkeyToAddress(bankKey.PublicKey) bankFunds = big.NewInt(1e9) contract = hexutil.MustDecode("0x608060405234801561001057600080fd5b50610150806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80632e64cec11461003b5780636057361d14610059575b600080fd5b610043610075565b60405161005091906100d9565b60405180910390f35b610073600480360381019061006e919061009d565b61007e565b005b60008054905090565b8060008190555050565b60008135905061009781610103565b92915050565b6000602082840312156100b3576100b26100fe565b5b60006100c184828501610088565b91505092915050565b6100d3816100f4565b82525050565b60006020820190506100ee60008301846100ca565b92915050565b6000819050919050565b600080fd5b61010c816100f4565b811461011757600080fd5b5056fea26469706673582212209a159a4f3847890f10bfb87871a61eba91c5dbf5ee3cf6398207e292eee22a1664736f6c63430008070033") - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{bankAddress: {Balance: bankFunds}}, + Alloc: types.GenesisAlloc{bankAddress: {Balance: bankFunds}}, } ) m := stages.MockWithGenesis(t, gspec, bankKey, false) diff --git a/cmd/rpcdaemon/commands/eth_system_test.go b/cmd/rpcdaemon/commands/eth_system_test.go index 9411d9496..923a1d477 100644 --- a/cmd/rpcdaemon/commands/eth_system_test.go +++ b/cmd/rpcdaemon/commands/eth_system_test.go @@ -9,7 +9,6 @@ import ( "github.com/holiman/uint256" libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/kv/kvcache" - "github.com/ledgerwatch/erigon/rpc/rpccfg" "github.com/ledgerwatch/erigon/core" @@ -65,9 +64,9 @@ func createGasPriceTestKV(t *testing.T, chainSize int) *stages.MockSentry { var ( key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") addr = crypto.PubkeyToAddress(key.PublicKey) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{addr: {Balance: big.NewInt(math.MaxInt64)}}, + Alloc: types.GenesisAlloc{addr: {Balance: big.NewInt(math.MaxInt64)}}, } signer = types.LatestSigner(gspec.Config) ) diff --git a/cmd/rpcdaemon/rpcdaemontest/test_util.go b/cmd/rpcdaemon/rpcdaemontest/test_util.go index 9a5339224..53afe0a08 100644 --- a/cmd/rpcdaemon/rpcdaemontest/test_util.go +++ b/cmd/rpcdaemon/rpcdaemontest/test_util.go @@ -74,9 +74,9 @@ func CreateTestSentry(t *testing.T) (*stages.MockSentry, *core.ChainPack, []*cor ) var ( - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: big.NewInt(9000000000000000000)}, address1: {Balance: big.NewInt(200000000000000000)}, address2: {Balance: big.NewInt(300000000000000000)}, @@ -333,9 +333,9 @@ func CreateTestSentryForTraces(t *testing.T) *stages.MockSentry { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, // The address 0x00ff a0: { @@ -490,9 +490,9 @@ func CreateTestSentryForTracesCollision(t *testing.T) *stages.MockSentry { aa := crypto.CreateAddress2(bb, [32]byte{}, initHash[:]) t.Logf("Destination address: %x\n", aa) - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, // The address 0xAAAAA selfdestructs if called aa: { diff --git a/cmd/sentry/sentry/sentry_grpc_server_test.go b/cmd/sentry/sentry/sentry_grpc_server_test.go index ee977f5c9..43a870595 100644 --- a/cmd/sentry/sentry/sentry_grpc_server_test.go +++ b/cmd/sentry/sentry/sentry_grpc_server_test.go @@ -13,16 +13,17 @@ import ( proto_sentry "github.com/ledgerwatch/erigon-lib/gointerfaces/sentry" "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon-lib/kv/memdb" + "github.com/ledgerwatch/erigon/core" + "github.com/ledgerwatch/erigon/core/types" "github.com/stretchr/testify/require" - "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/forkid" "github.com/ledgerwatch/erigon/core/rawdb" "github.com/ledgerwatch/erigon/eth/protocols/eth" "github.com/ledgerwatch/erigon/p2p" ) -func testSentryServer(db kv.Getter, genesis *core.Genesis, genesisHash libcommon.Hash) *GrpcServer { +func testSentryServer(db kv.Getter, genesis *types.Genesis, genesisHash libcommon.Hash) *GrpcServer { s := &GrpcServer{ ctx: context.Background(), } @@ -70,11 +71,11 @@ func testForkIDSplit(t *testing.T, protocol uint) { dbNoFork = memdb.NewTestDB(t) dbProFork = memdb.NewTestDB(t) - gspecNoFork = &core.Genesis{Config: configNoFork} - gspecProFork = &core.Genesis{Config: configProFork} + gspecNoFork = &types.Genesis{Config: configNoFork} + gspecProFork = &types.Genesis{Config: configProFork} - genesisNoFork = gspecNoFork.MustCommit(dbNoFork, "") - genesisProFork = gspecProFork.MustCommit(dbProFork, "") + genesisNoFork = core.MustCommitGenesis(gspecNoFork, dbNoFork, "") + genesisProFork = core.MustCommitGenesis(gspecProFork, dbProFork, "") ) var s1, s2 *GrpcServer @@ -161,8 +162,8 @@ func TestSentryServerImpl_SetStatusInitPanic(t *testing.T) { configNoFork := &chain.Config{HomesteadBlock: big.NewInt(1), ChainID: big.NewInt(1)} dbNoFork := memdb.NewTestDB(t) - gspecNoFork := &core.Genesis{Config: configNoFork} - genesisNoFork := gspecNoFork.MustCommit(dbNoFork, "") + gspecNoFork := &types.Genesis{Config: configNoFork} + genesisNoFork := core.MustCommitGenesis(gspecNoFork, dbNoFork, "") ss := &GrpcServer{p2p: &p2p.Config{}} _, err := ss.SetStatus(context.Background(), &proto_sentry.StatusData{ diff --git a/cmd/state/commands/check_change_sets.go b/cmd/state/commands/check_change_sets.go index f64d30f18..5beb708a2 100644 --- a/cmd/state/commands/check_change_sets.go +++ b/cmd/state/commands/check_change_sets.go @@ -19,7 +19,6 @@ import ( "github.com/ledgerwatch/log/v3" "github.com/spf13/cobra" - "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/state" "github.com/ledgerwatch/erigon/core/systemcontracts" "github.com/ledgerwatch/erigon/core/types" @@ -56,7 +55,7 @@ var checkChangeSetsCmd = &cobra.Command{ // CheckChangeSets re-executes historical transactions in read-only mode // and checks that their outputs match the database ChangeSets. -func CheckChangeSets(genesis *core.Genesis, logger log.Logger, blockNum uint64, chaindata string, historyfile string, nocheck bool, transactionV3 bool) error { +func CheckChangeSets(genesis *types.Genesis, logger log.Logger, blockNum uint64, chaindata string, historyfile string, nocheck bool, transactionV3 bool) error { if len(historyfile) == 0 { historyfile = chaindata } diff --git a/cmd/state/commands/erigon4.go b/cmd/state/commands/erigon4.go index 00f8993c1..4d027599b 100644 --- a/cmd/state/commands/erigon4.go +++ b/cmd/state/commands/erigon4.go @@ -86,7 +86,7 @@ var erigon4Cmd = &cobra.Command{ }, } -func Erigon4(genesis *core.Genesis, chainConfig *chain2.Config, logger log.Logger) error { +func Erigon4(genesis *types.Genesis, chainConfig *chain2.Config, logger log.Logger) error { sigs := make(chan os.Signal, 1) interruptCh := make(chan bool, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) @@ -173,12 +173,12 @@ func Erigon4(genesis *core.Genesis, chainConfig *chain2.Config, logger log.Logge interrupt := false if startTxNum == 0 { - genBlock, genesisIbs, err := genesis.ToBlock("") + genBlock, genesisIbs, err := core.GenesisToBlock(genesis, "") if err != nil { return err } agg.SetTxNum(0) - if err = genesisIbs.CommitBlock(&chain2.Rules{}, &WriterWrapper23{w: agg}); err != nil { + if err = genesisIbs.CommitBlock(&chain2.Rules{}, &StateWriterV4{w: agg}); err != nil { return fmt.Errorf("cannot write state: %w", err) } @@ -244,8 +244,8 @@ func Erigon4(genesis *core.Genesis, chainConfig *chain2.Config, logger log.Logge } return h } - readWrapper := &ReaderWrapper23{ac: agg.MakeContext(), roTx: rwTx} - writeWrapper := &WriterWrapper23{w: agg} + readWrapper := &StateReaderV4{ac: agg.MakeContext(), roTx: rwTx} + writeWrapper := &StateWriterV4{w: agg} commitFn := func(txn uint64) error { if db == nil || rwTx == nil { @@ -375,7 +375,7 @@ func (s *stat23) delta(aStats libstate.FilesStats, blockNum, txNum uint64) *stat return s } -func processBlock23(startTxNum uint64, trace bool, txNumStart uint64, rw *ReaderWrapper23, ww *WriterWrapper23, chainConfig *chain2.Config, +func processBlock23(startTxNum uint64, trace bool, txNumStart uint64, rw *StateReaderV4, ww *StateWriterV4, chainConfig *chain2.Config, engine consensus.Engine, getHeader func(hash libcommon.Hash, number uint64) *types.Header, block *types.Block, vmConfig vm.Config, ) (uint64, types.Receipts, error) { defer blockExecutionTimer.UpdateDuration(time.Now()) @@ -390,7 +390,6 @@ func processBlock23(startTxNum uint64, trace bool, txNumStart uint64, rw *Reader ww.w.SetTxNum(txNum) rw.blockNum = block.NumberU64() - ww.blockNum = block.NumberU64() daoFork := txNum >= startTxNum && chainConfig.DAOForkBlock != nil && chainConfig.DAOForkBlock.Cmp(block.Number()) == 0 if daoFork { @@ -514,18 +513,21 @@ func processBlock23(startTxNum uint64, trace bool, txNumStart uint64, rw *Reader } // Implements StateReader and StateWriter -type ReaderWrapper23 struct { +type StateReaderV4 struct { roTx kv.Tx ac *libstate.AggregatorContext blockNum uint64 } -type WriterWrapper23 struct { - blockNum uint64 - w *libstate.Aggregator +type StateWriterV4 struct { + w *libstate.Aggregator } -func (rw *ReaderWrapper23) ReadAccountData(address libcommon.Address) (*accounts.Account, error) { +func NewStateWriterV4(w *libstate.Aggregator) { + +} + +func (rw *StateReaderV4) ReadAccountData(address libcommon.Address) (*accounts.Account, error) { enc, err := rw.ac.ReadAccountData(address.Bytes(), rw.roTx) if err != nil { return nil, err @@ -540,7 +542,7 @@ func (rw *ReaderWrapper23) ReadAccountData(address libcommon.Address) (*accounts return &a, nil } -func (rw *ReaderWrapper23) ReadAccountStorage(address libcommon.Address, incarnation uint64, key *libcommon.Hash) ([]byte, error) { +func (rw *StateReaderV4) ReadAccountStorage(address libcommon.Address, incarnation uint64, key *libcommon.Hash) ([]byte, error) { enc, err := rw.ac.ReadAccountStorage(address.Bytes(), key.Bytes(), rw.roTx) if err != nil { return nil, err @@ -554,19 +556,19 @@ func (rw *ReaderWrapper23) ReadAccountStorage(address libcommon.Address, incarna return enc, nil } -func (rw *ReaderWrapper23) ReadAccountCode(address libcommon.Address, incarnation uint64, codeHash libcommon.Hash) ([]byte, error) { +func (rw *StateReaderV4) ReadAccountCode(address libcommon.Address, incarnation uint64, codeHash libcommon.Hash) ([]byte, error) { return rw.ac.ReadAccountCode(address.Bytes(), rw.roTx) } -func (rw *ReaderWrapper23) ReadAccountCodeSize(address libcommon.Address, incarnation uint64, codeHash libcommon.Hash) (int, error) { +func (rw *StateReaderV4) ReadAccountCodeSize(address libcommon.Address, incarnation uint64, codeHash libcommon.Hash) (int, error) { return rw.ac.ReadAccountCodeSize(address.Bytes(), rw.roTx) } -func (rw *ReaderWrapper23) ReadAccountIncarnation(address libcommon.Address) (uint64, error) { +func (rw *StateReaderV4) ReadAccountIncarnation(address libcommon.Address) (uint64, error) { return 0, nil } -func (ww *WriterWrapper23) UpdateAccountData(address libcommon.Address, original, account *accounts.Account) error { +func (ww *StateWriterV4) UpdateAccountData(address libcommon.Address, original, account *accounts.Account) error { value := accounts.SerialiseV3(account) if err := ww.w.UpdateAccountData(address.Bytes(), value); err != nil { return err @@ -574,28 +576,28 @@ func (ww *WriterWrapper23) UpdateAccountData(address libcommon.Address, original return nil } -func (ww *WriterWrapper23) UpdateAccountCode(address libcommon.Address, incarnation uint64, codeHash libcommon.Hash, code []byte) error { +func (ww *StateWriterV4) UpdateAccountCode(address libcommon.Address, incarnation uint64, codeHash libcommon.Hash, code []byte) error { if err := ww.w.UpdateAccountCode(address.Bytes(), code); err != nil { return err } return nil } -func (ww *WriterWrapper23) DeleteAccount(address libcommon.Address, original *accounts.Account) error { +func (ww *StateWriterV4) DeleteAccount(address libcommon.Address, original *accounts.Account) error { if err := ww.w.DeleteAccount(address.Bytes()); err != nil { return err } return nil } -func (ww *WriterWrapper23) WriteAccountStorage(address libcommon.Address, incarnation uint64, key *libcommon.Hash, original, value *uint256.Int) error { +func (ww *StateWriterV4) WriteAccountStorage(address libcommon.Address, incarnation uint64, key *libcommon.Hash, original, value *uint256.Int) error { if err := ww.w.WriteAccountStorage(address.Bytes(), key.Bytes(), value.Bytes()); err != nil { return err } return nil } -func (ww *WriterWrapper23) CreateContract(address libcommon.Address) error { +func (ww *StateWriterV4) CreateContract(address libcommon.Address) error { return nil } diff --git a/cmd/state/commands/history22.go b/cmd/state/commands/history22.go index 3316b0a3f..0a9dd1726 100644 --- a/cmd/state/commands/history22.go +++ b/cmd/state/commands/history22.go @@ -56,7 +56,7 @@ var history22Cmd = &cobra.Command{ }, } -func History22(genesis *core.Genesis, logger log.Logger) error { +func History22(genesis *types.Genesis, logger log.Logger) error { sigs := make(chan os.Signal, 1) interruptCh := make(chan bool, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) diff --git a/cmd/state/commands/opcode_tracer.go b/cmd/state/commands/opcode_tracer.go index 720fe1709..9edfe8b03 100644 --- a/cmd/state/commands/opcode_tracer.go +++ b/cmd/state/commands/opcode_tracer.go @@ -393,7 +393,7 @@ type segPrefix struct { // OpcodeTracer re-executes historical transactions in read-only mode // and traces them at the opcode level -func OpcodeTracer(genesis *core.Genesis, blockNum uint64, chaindata string, numBlocks uint64, +func OpcodeTracer(genesis *types.Genesis, blockNum uint64, chaindata string, numBlocks uint64, saveOpcodes bool, saveBblocks bool) error { blockNumOrig := blockNum diff --git a/cmd/state/commands/root.go b/cmd/state/commands/root.go index d54dfea58..ddbca2889 100644 --- a/cmd/state/commands/root.go +++ b/cmd/state/commands/root.go @@ -8,6 +8,7 @@ import ( chain2 "github.com/ledgerwatch/erigon-lib/chain" "github.com/ledgerwatch/erigon-lib/common" + "github.com/ledgerwatch/erigon/core/types" "github.com/spf13/cobra" "github.com/ledgerwatch/erigon/turbo/debug" @@ -20,7 +21,7 @@ import ( var ( genesisPath string - genesis *core.Genesis + genesis *types.Genesis chainConfig *chain2.Config ) @@ -59,21 +60,21 @@ var rootCmd = &cobra.Command{ }, } -func genesisFromFile(genesisPath string) *core.Genesis { +func genesisFromFile(genesisPath string) *types.Genesis { file, err := os.Open(genesisPath) if err != nil { utils.Fatalf("Failed to read genesis file: %v", err) } defer file.Close() - genesis := new(core.Genesis) + genesis := new(types.Genesis) if err := json.NewDecoder(file).Decode(genesis); err != nil { utils.Fatalf("invalid genesis file: %v", err) } return genesis } -func getChainGenesisAndConfig() (genesis *core.Genesis, chainConfig *chain2.Config) { +func getChainGenesisAndConfig() (genesis *types.Genesis, chainConfig *chain2.Config) { if chain == "" { genesis, chainConfig = core.MainnetGenesisBlock(), params.MainnetChainConfig } else { diff --git a/cmd/state/commands/state_root.go b/cmd/state/commands/state_root.go index 126260333..10af1baca 100644 --- a/cmd/state/commands/state_root.go +++ b/cmd/state/commands/state_root.go @@ -14,11 +14,11 @@ import ( datadir2 "github.com/ledgerwatch/erigon-lib/common/datadir" "github.com/ledgerwatch/erigon-lib/kv" kv2 "github.com/ledgerwatch/erigon-lib/kv/mdbx" + "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/log/v3" "github.com/spf13/cobra" "github.com/ledgerwatch/erigon/consensus/ethash" - "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/rawdb" "github.com/ledgerwatch/erigon/core/state" "github.com/ledgerwatch/erigon/core/types" @@ -42,7 +42,7 @@ var stateRootCmd = &cobra.Command{ }, } -func StateRoot(genesis *core.Genesis, logger log.Logger, blockNum uint64, datadir string) error { +func StateRoot(genesis *types.Genesis, logger log.Logger, blockNum uint64, datadir string) error { sigs := make(chan os.Signal, 1) interruptCh := make(chan bool, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) @@ -89,7 +89,7 @@ func StateRoot(genesis *core.Genesis, logger log.Logger, blockNum uint64, datadi if rwTx, err = db.BeginRw(ctx); err != nil { return err } - _, genesisIbs, err4 := genesis.ToBlock("") + _, genesisIbs, err4 := core.GenesisToBlock(genesis, "") if err4 != nil { return err4 } diff --git a/cmd/state/exec3/state.go b/cmd/state/exec3/state.go index e9845fcc1..914269499 100644 --- a/cmd/state/exec3/state.go +++ b/cmd/state/exec3/state.go @@ -39,7 +39,7 @@ type Worker struct { ctx context.Context engine consensus.Engine logger log.Logger - genesis *core.Genesis + genesis *types.Genesis resultCh chan *exec22.TxTask epoch EpochReader chain ChainReader @@ -53,7 +53,7 @@ type Worker struct { ibs *state.IntraBlockState } -func NewWorker(lock sync.Locker, ctx context.Context, background bool, chainDb kv.RoDB, rs *state.StateV3, blockReader services.FullBlockReader, chainConfig *chain.Config, logger log.Logger, genesis *core.Genesis, resultCh chan *exec22.TxTask, engine consensus.Engine) *Worker { +func NewWorker(lock sync.Locker, ctx context.Context, background bool, chainDb kv.RoDB, rs *state.StateV3, blockReader services.FullBlockReader, chainConfig *chain.Config, logger log.Logger, genesis *types.Genesis, resultCh chan *exec22.TxTask, engine consensus.Engine) *Worker { w := &Worker{ lock: lock, chainDb: chainDb, @@ -146,7 +146,7 @@ func (rw *Worker) RunTxTaskNoLock(txTask *exec22.TxTask) { if txTask.BlockNum == 0 && txTask.TxIndex == -1 { //fmt.Printf("txNum=%d, blockNum=%d, Genesis\n", txTask.TxNum, txTask.BlockNum) // Genesis block - _, ibs, err = rw.genesis.ToBlock("") + _, ibs, err = core.GenesisToBlock(rw.genesis, "") if err != nil { panic(err) } @@ -327,7 +327,7 @@ func (cr EpochReader) FindBeforeOrEqualNumber(number uint64) (blockNum uint64, b return rawdb.FindEpochBeforeOrEqualNumber(cr.tx, number) } -func NewWorkersPool(lock sync.Locker, ctx context.Context, background bool, chainDb kv.RoDB, rs *state.StateV3, blockReader services.FullBlockReader, chainConfig *chain.Config, logger log.Logger, genesis *core.Genesis, engine consensus.Engine, workerCount int) (reconWorkers []*Worker, applyWorker *Worker, resultCh chan *exec22.TxTask, clear func(), wait func()) { +func NewWorkersPool(lock sync.Locker, ctx context.Context, background bool, chainDb kv.RoDB, rs *state.StateV3, blockReader services.FullBlockReader, chainConfig *chain.Config, logger log.Logger, genesis *types.Genesis, engine consensus.Engine, workerCount int) (reconWorkers []*Worker, applyWorker *Worker, resultCh chan *exec22.TxTask, clear func(), wait func()) { queueSize := workerCount * 256 reconWorkers = make([]*Worker, workerCount) resultCh = make(chan *exec22.TxTask, queueSize) diff --git a/cmd/state/exec3/state_recon.go b/cmd/state/exec3/state_recon.go index 63baf5296..a8b46b6c9 100644 --- a/cmd/state/exec3/state_recon.go +++ b/cmd/state/exec3/state_recon.go @@ -229,7 +229,7 @@ type ReconWorker struct { engine consensus.Engine chainConfig *chain.Config logger log.Logger - genesis *core.Genesis + genesis *types.Genesis epoch EpochReader chain ChainReader isPoSA bool @@ -241,7 +241,7 @@ type ReconWorker struct { func NewReconWorker(lock sync.Locker, ctx context.Context, rs *state.ReconState, as *libstate.AggregatorStep, blockReader services.FullBlockReader, - chainConfig *chain.Config, logger log.Logger, genesis *core.Genesis, engine consensus.Engine, + chainConfig *chain.Config, logger log.Logger, genesis *types.Genesis, engine consensus.Engine, chainTx kv.Tx, ) *ReconWorker { rw := &ReconWorker{ @@ -302,7 +302,7 @@ func (rw *ReconWorker) runTxTask(txTask *exec22.TxTask) error { if txTask.BlockNum == 0 && txTask.TxIndex == -1 { //fmt.Printf("txNum=%d, blockNum=%d, Genesis\n", txTask.TxNum, txTask.BlockNum) // Genesis block - _, ibs, err = rw.genesis.ToBlock("") + _, ibs, err = core.GenesisToBlock(rw.genesis, "") if err != nil { return err } diff --git a/cmd/txpool/main.go b/cmd/txpool/main.go index 727cd8213..6c44d6a41 100644 --- a/cmd/txpool/main.go +++ b/cmd/txpool/main.go @@ -19,6 +19,7 @@ import ( "github.com/ledgerwatch/erigon-lib/kv/remotedb" "github.com/ledgerwatch/erigon-lib/kv/remotedbserver" "github.com/ledgerwatch/erigon-lib/txpool" + "github.com/ledgerwatch/erigon-lib/txpool/txpoolcfg" "github.com/ledgerwatch/erigon-lib/txpool/txpooluitl" "github.com/ledgerwatch/erigon-lib/types" "github.com/ledgerwatch/erigon/cmd/rpcdaemon/rpcdaemontest" @@ -68,12 +69,12 @@ func init() { rootCmd.PersistentFlags().StringVar(&TLSKeyFile, "tls.key", "", "key file for client side TLS handshake") rootCmd.PersistentFlags().StringVar(&TLSCACert, "tls.cacert", "", "CA certificate for client side TLS handshake") - rootCmd.PersistentFlags().IntVar(&pendingPoolLimit, "txpool.globalslots", txpool.DefaultConfig.PendingSubPoolLimit, "Maximum number of executable transaction slots for all accounts") - rootCmd.PersistentFlags().IntVar(&baseFeePoolLimit, "txpool.globalbasefeeeslots", txpool.DefaultConfig.BaseFeeSubPoolLimit, "Maximum number of non-executable transactions where only not enough baseFee") - rootCmd.PersistentFlags().IntVar(&queuedPoolLimit, "txpool.globalqueue", txpool.DefaultConfig.QueuedSubPoolLimit, "Maximum number of non-executable transaction slots for all accounts") - rootCmd.PersistentFlags().Uint64Var(&priceLimit, "txpool.pricelimit", txpool.DefaultConfig.MinFeeCap, "Minimum gas price (fee cap) limit to enforce for acceptance into the pool") - rootCmd.PersistentFlags().Uint64Var(&accountSlots, "txpool.accountslots", txpool.DefaultConfig.AccountSlots, "Minimum number of executable transaction slots guaranteed per account") - rootCmd.PersistentFlags().Uint64Var(&priceBump, "txpool.pricebump", txpool.DefaultConfig.PriceBump, "Price bump percentage to replace an already existing transaction") + rootCmd.PersistentFlags().IntVar(&pendingPoolLimit, "txpool.globalslots", txpoolcfg.DefaultConfig.PendingSubPoolLimit, "Maximum number of executable transaction slots for all accounts") + rootCmd.PersistentFlags().IntVar(&baseFeePoolLimit, "txpool.globalbasefeeeslots", txpoolcfg.DefaultConfig.BaseFeeSubPoolLimit, "Maximum number of non-executable transactions where only not enough baseFee") + rootCmd.PersistentFlags().IntVar(&queuedPoolLimit, "txpool.globalqueue", txpoolcfg.DefaultConfig.QueuedSubPoolLimit, "Maximum number of non-executable transaction slots for all accounts") + rootCmd.PersistentFlags().Uint64Var(&priceLimit, "txpool.pricelimit", txpoolcfg.DefaultConfig.MinFeeCap, "Minimum gas price (fee cap) limit to enforce for acceptance into the pool") + rootCmd.PersistentFlags().Uint64Var(&accountSlots, "txpool.accountslots", txpoolcfg.DefaultConfig.AccountSlots, "Minimum number of executable transaction slots guaranteed per account") + rootCmd.PersistentFlags().Uint64Var(&priceBump, "txpool.pricebump", txpoolcfg.DefaultConfig.PriceBump, "Price bump percentage to replace an already existing transaction") rootCmd.PersistentFlags().DurationVar(&commitEvery, utils.TxPoolCommitEveryFlag.Name, utils.TxPoolCommitEveryFlag.Value, utils.TxPoolCommitEveryFlag.Usage) rootCmd.Flags().StringSliceVar(&traceSenders, utils.TxPoolTraceSendersFlag.Name, []string{}, utils.TxPoolTraceSendersFlag.Usage) } @@ -131,7 +132,7 @@ func doTxpool(ctx context.Context) error { sentryClients[i] = direct.NewSentryClientRemote(proto_sentry.NewSentryClient(sentryConn)) } - cfg := txpool.DefaultConfig + cfg := txpoolcfg.DefaultConfig dirs := datadir.New(datadirCli) cfg.DBDir = dirs.TxPool diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index 8fa2a610b..71806fcf7 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -34,8 +34,10 @@ import ( "github.com/ledgerwatch/erigon-lib/common/metrics" downloadercfg2 "github.com/ledgerwatch/erigon-lib/downloader/downloadercfg" "github.com/ledgerwatch/erigon-lib/kv" - "github.com/ledgerwatch/erigon-lib/txpool" + "github.com/ledgerwatch/erigon-lib/txpool/txpoolcfg" common2 "github.com/ledgerwatch/erigon/common" + "github.com/ledgerwatch/erigon/consensus/ethash/ethashcfg" + "github.com/ledgerwatch/erigon/eth/gasprice/gaspricecfg" "github.com/ledgerwatch/log/v3" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -44,11 +46,9 @@ import ( "github.com/ledgerwatch/erigon/cl/clparams" "github.com/ledgerwatch/erigon/cmd/downloader/downloadernat" "github.com/ledgerwatch/erigon/common/paths" - "github.com/ledgerwatch/erigon/consensus/ethash" "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/crypto" "github.com/ledgerwatch/erigon/eth/ethconfig" - "github.com/ledgerwatch/erigon/eth/gasprice" "github.com/ledgerwatch/erigon/eth/protocols/eth" "github.com/ledgerwatch/erigon/node/nodecfg" "github.com/ledgerwatch/erigon/p2p" @@ -157,7 +157,7 @@ var ( TxPoolPriceBumpFlag = cli.Uint64Flag{ Name: "txpool.pricebump", Usage: "Price bump percentage to replace an already existing transaction", - Value: txpool.DefaultConfig.PriceBump, + Value: txpoolcfg.DefaultConfig.PriceBump, } TxPoolAccountSlotsFlag = cli.Uint64Flag{ Name: "txpool.accountslots", @@ -197,7 +197,7 @@ var ( TxPoolCommitEveryFlag = cli.DurationFlag{ Name: "txpool.commit.every", Usage: "How often transactions should be committed to the storage", - Value: txpool.DefaultConfig.CommitEvery, + Value: txpoolcfg.DefaultConfig.CommitEvery, } // Miner settings MiningEnabledFlag = cli.BoolFlag{ @@ -1193,7 +1193,7 @@ func setDataDirCobra(f *pflag.FlagSet, cfg *nodecfg.Config) { cfg.Dirs = datadir.New(cfg.Dirs.DataDir) } -func setGPO(ctx *cli.Context, cfg *gasprice.Config) { +func setGPO(ctx *cli.Context, cfg *gaspricecfg.Config) { if ctx.IsSet(GpoBlocksFlag.Name) { cfg.Blocks = ctx.Int(GpoBlocksFlag.Name) } @@ -1206,7 +1206,7 @@ func setGPO(ctx *cli.Context, cfg *gasprice.Config) { } // nolint -func setGPOCobra(f *pflag.FlagSet, cfg *gasprice.Config) { +func setGPOCobra(f *pflag.FlagSet, cfg *gaspricecfg.Config) { if v := f.Int(GpoBlocksFlag.Name, GpoBlocksFlag.Value, GpoBlocksFlag.Usage); v != nil { cfg.Blocks = *v } @@ -1218,7 +1218,7 @@ func setGPOCobra(f *pflag.FlagSet, cfg *gasprice.Config) { } } -func setTxPool(ctx *cli.Context, cfg *core.TxPoolConfig) { +func setTxPool(ctx *cli.Context, cfg *ethconfig.DeprecatedTxPoolConfig) { if ctx.IsSet(TxPoolDisableFlag.Name) { cfg.Disable = true } @@ -1285,7 +1285,7 @@ func setEthash(ctx *cli.Context, datadir string, cfg *ethconfig.Config) { cfg.Ethash.CachesLockMmap = ctx.Bool(EthashCachesLockMmapFlag.Name) } if ctx.IsSet(FakePoWFlag.Name) { - cfg.Ethash.PowMode = ethash.ModeFake + cfg.Ethash.PowMode = ethashcfg.ModeFake } if ctx.IsSet(EthashDatasetsLockMmapFlag.Name) { cfg.Ethash.DatasetsLockMmap = ctx.Bool(EthashDatasetsLockMmapFlag.Name) @@ -1511,7 +1511,7 @@ func SetEthConfig(ctx *cli.Context, nodeConfig *nodecfg.Config, cfg *ethconfig.C setGPO(ctx, &cfg.GPO) setTxPool(ctx, &cfg.DeprecatedTxPool) - cfg.TxPool = core.DefaultTxPool2Config(cfg.DeprecatedTxPool) + cfg.TxPool = ethconfig.DefaultTxPool2Config(cfg.DeprecatedTxPool) cfg.TxPool.DBDir = nodeConfig.Dirs.TxPool setEthash(ctx, nodeConfig.Dirs.DataDir, cfg) diff --git a/consensus/aura/aura_test.go b/consensus/aura/aura_test.go index 314d5e49e..306d6e54c 100644 --- a/consensus/aura/aura_test.go +++ b/consensus/aura/aura_test.go @@ -203,7 +203,7 @@ func TestEmptyBlock(t *testing.T) { require := require.New(t) genesis := core.GnosisGenesisBlock() - genesisBlock, _, err := genesis.ToBlock("") + genesisBlock, _, err := core.GenesisToBlock(genesis, "") require.NoError(err) genesis.Config.TerminalTotalDifficultyPassed = false diff --git a/consensus/bor/bor.go b/consensus/bor/bor.go index b8f0e1ce3..737b29747 100644 --- a/consensus/bor/bor.go +++ b/consensus/bor/bor.go @@ -30,7 +30,6 @@ import ( "github.com/ledgerwatch/erigon/consensus/bor/statefull" "github.com/ledgerwatch/erigon/consensus/bor/valset" "github.com/ledgerwatch/erigon/consensus/misc" - "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/state" "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/erigon/core/types/accounts" @@ -794,8 +793,8 @@ func (c *Bor) Finalize(config *chain.Config, header *types.Header, state *state. return nil, types.Receipts{}, nil } -func decodeGenesisAlloc(i interface{}) (core.GenesisAlloc, error) { - var alloc core.GenesisAlloc +func decodeGenesisAlloc(i interface{}) (types.GenesisAlloc, error) { + var alloc types.GenesisAlloc b, err := json.Marshal(i) if err != nil { diff --git a/consensus/clique/clique_test.go b/consensus/clique/clique_test.go index 3dbfbf8ef..6407b6dfa 100644 --- a/consensus/clique/clique_test.go +++ b/consensus/clique/clique_test.go @@ -26,7 +26,6 @@ import ( "github.com/ledgerwatch/erigon-lib/common/length" "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon-lib/kv/memdb" - "github.com/ledgerwatch/erigon/consensus/clique" "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/rawdb" @@ -51,9 +50,9 @@ func TestReimportMirroredState(t *testing.T) { engine = clique.New(params.AllCliqueProtocolChanges, params.CliqueSnapshot, cliqueDB) signer = types.LatestSignerForChainID(nil) ) - genspec := &core.Genesis{ + genspec := &types.Genesis{ ExtraData: make([]byte, clique.ExtraVanity+length.Addr+clique.ExtraSeal), - Alloc: map[libcommon.Address]core.GenesisAccount{ + Alloc: map[libcommon.Address]types.GenesisAccount{ addr: {Balance: big.NewInt(10000000000000000)}, }, Config: params.AllCliqueProtocolChanges, diff --git a/consensus/clique/snapshot_test.go b/consensus/clique/snapshot_test.go index be473f476..33d69ae71 100644 --- a/consensus/clique/snapshot_test.go +++ b/consensus/clique/snapshot_test.go @@ -26,7 +26,6 @@ import ( libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/common/length" "github.com/ledgerwatch/erigon-lib/kv/memdb" - "github.com/ledgerwatch/erigon/consensus/clique" "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/types" @@ -406,7 +405,7 @@ func TestClique(t *testing.T) { } } // Create the genesis block with the initial set of signers - genesis := &core.Genesis{ + genesis := &types.Genesis{ ExtraData: make([]byte, clique.ExtraVanity+length.Addr*len(signers)+clique.ExtraSeal), Config: params.AllCliqueProtocolChanges, } diff --git a/consensus/ethash/consensus.go b/consensus/ethash/consensus.go index f54576e72..ed3ffc6ad 100644 --- a/consensus/ethash/consensus.go +++ b/consensus/ethash/consensus.go @@ -28,6 +28,7 @@ import ( "github.com/holiman/uint256" "github.com/ledgerwatch/erigon-lib/chain" libcommon "github.com/ledgerwatch/erigon-lib/common" + "github.com/ledgerwatch/erigon/consensus/ethash/ethashcfg" "github.com/ledgerwatch/log/v3" "golang.org/x/crypto/sha3" @@ -517,7 +518,7 @@ func (ethash *Ethash) verifySeal(header *types.Header, fulldag bool) error { //n cache := ethash.cache(number) size := datasetSize(number) - if ethash.config.PowMode == ModeTest { + if ethash.config.PowMode == ethashcfg.ModeTest { size = 32 * 1024 } digest, result = hashimotoLight(size, cache.cache, ethash.SealHash(header).Bytes(), header.Nonce.Uint64()) diff --git a/consensus/ethash/ethash.go b/consensus/ethash/ethash.go index 312678a7c..813c5283e 100644 --- a/consensus/ethash/ethash.go +++ b/consensus/ethash/ethash.go @@ -33,6 +33,7 @@ import ( "github.com/edsrzf/mmap-go" "github.com/hashicorp/golang-lru/simplelru" + "github.com/ledgerwatch/erigon/consensus/ethash/ethashcfg" "github.com/ledgerwatch/erigon/common/debug" cmath "github.com/ledgerwatch/erigon/common/math" @@ -64,8 +65,8 @@ var ( // sharedEthash is a full instance that can be shared between multiple users. func GetSharedEthash() *Ethash { sharedEthashOnce.Do(func() { - sharedConfig := Config{ - PowMode: ModeNormal, + sharedConfig := ethashcfg.Config{ + PowMode: ethashcfg.ModeNormal, CachesInMem: 3, DatasetsInMem: 1, } @@ -400,39 +401,10 @@ func (d *dataset) finalizer() { } } -// Mode defines the type and amount of PoW verification an ethash engine makes. -type Mode uint - -const ( - ModeNormal Mode = iota - ModeShared - ModeTest - - ModeFake - ModeFullFake -) - -// Config are the configuration parameters of the ethash. -type Config struct { - CachesInMem int - CachesLockMmap bool - DatasetDir string - DatasetsInMem int - DatasetsOnDisk int - DatasetsLockMmap bool - PowMode Mode - - // When set, notifications sent by the remote sealer will - // be block header JSON objects instead of work package arrays. - NotifyFull bool - - Log log.Logger `toml:"-"` -} - // Ethash is a consensus engine based on proof-of-work implementing the ethash // algorithm. type Ethash struct { - config Config + config ethashcfg.Config caches *lru // In memory caches to avoid regenerating too often datasets *lru // In memory datasets to avoid regenerating too often @@ -452,7 +424,7 @@ type Ethash struct { // New creates a full sized ethash PoW scheme and starts a background thread for // remote mining, also optionally notifying a batch of remote services of new work // packages. -func New(config Config, notify []string, noverify bool) *Ethash { +func New(config ethashcfg.Config, notify []string, noverify bool) *Ethash { if config.Log == nil { config.Log = log.Root() } @@ -469,7 +441,7 @@ func New(config Config, notify []string, noverify bool) *Ethash { datasets: newlru("dataset", config.DatasetsInMem, newDataset), hashrate: metrics.NewMeterForced(), } - if config.PowMode == ModeShared { + if config.PowMode == ethashcfg.ModeShared { ethash.shared = GetSharedEthash() } ethash.remote = startRemoteSealer(ethash, notify, noverify) @@ -479,7 +451,7 @@ func New(config Config, notify []string, noverify bool) *Ethash { // NewTester creates a small sized ethash PoW scheme useful only for testing // purposes. func NewTester(notify []string, noverify bool) *Ethash { - return New(Config{PowMode: ModeTest}, notify, noverify) + return New(ethashcfg.Config{PowMode: ethashcfg.ModeTest}, notify, noverify) } // NewShared creates a full sized ethash PoW shared between all requesters running @@ -510,12 +482,12 @@ func (ethash *Ethash) cache(block uint64) *cache { current := currentI.(*cache) // Wait for generation finish. - current.generate(doNotStoreCachesOnDisk, 0, ethash.config.CachesLockMmap, ethash.config.PowMode == ModeTest) + current.generate(doNotStoreCachesOnDisk, 0, ethash.config.CachesLockMmap, ethash.config.PowMode == ethashcfg.ModeTest) // If we need a new future cache, now's a good time to regenerate it. if futureI != nil { future := futureI.(*cache) - go future.generate(doNotStoreCachesOnDisk, 0, ethash.config.CachesLockMmap, ethash.config.PowMode == ModeTest) + go future.generate(doNotStoreCachesOnDisk, 0, ethash.config.CachesLockMmap, ethash.config.PowMode == ethashcfg.ModeTest) } return current } @@ -536,20 +508,20 @@ func (ethash *Ethash) dataset(block uint64, async bool) *dataset { if async && !current.generated() { go func() { defer debug.LogPanic() - current.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest) + current.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ethashcfg.ModeTest) if futureI != nil { future := futureI.(*dataset) - future.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest) + future.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ethashcfg.ModeTest) } }() } else { // Either blocking generation was requested, or already done - current.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest) + current.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ethashcfg.ModeTest) if futureI != nil { future := futureI.(*dataset) - go future.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest) + go future.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ethashcfg.ModeTest) } } return current @@ -561,7 +533,7 @@ func (ethash *Ethash) dataset(block uint64, async bool) *dataset { // hashrate of all remote miner. func (ethash *Ethash) Hashrate() float64 { // Short circuit if we are run the ethash in normal/test mode. - if (ethash.config.PowMode != ModeNormal && ethash.config.PowMode != ModeTest) || ethash.remote == nil { + if (ethash.config.PowMode != ethashcfg.ModeNormal && ethash.config.PowMode != ethashcfg.ModeTest) || ethash.remote == nil { return ethash.hashrate.Rate1() } var res = make(chan uint64, 1) diff --git a/consensus/ethash/ethashcfg/ethashcfg.go b/consensus/ethash/ethashcfg/ethashcfg.go new file mode 100644 index 000000000..62356c4be --- /dev/null +++ b/consensus/ethash/ethashcfg/ethashcfg.go @@ -0,0 +1,34 @@ +package ethashcfg + +import ( + "github.com/ledgerwatch/log/v3" +) + +// Config are the configuration parameters of the ethash. +type Config struct { + CachesInMem int + CachesLockMmap bool + DatasetDir string + DatasetsInMem int + DatasetsOnDisk int + DatasetsLockMmap bool + PowMode Mode + + // When set, notifications sent by the remote sealer will + // be block header JSON objects instead of work package arrays. + NotifyFull bool + + Log log.Logger `toml:"-"` +} + +// Mode defines the type and amount of PoW verification an ethash engine makes. +type Mode uint + +const ( + ModeNormal Mode = iota + ModeShared + ModeTest + + ModeFake + ModeFullFake +) diff --git a/consensus/ethash/fake.go b/consensus/ethash/fake.go index 19b1f3d52..19a362a97 100644 --- a/consensus/ethash/fake.go +++ b/consensus/ethash/fake.go @@ -5,6 +5,7 @@ import ( mapset "github.com/deckarep/golang-set" libcommon "github.com/ledgerwatch/erigon-lib/common" + "github.com/ledgerwatch/erigon/consensus/ethash/ethashcfg" "github.com/ledgerwatch/log/v3" "github.com/ledgerwatch/erigon/consensus" @@ -22,7 +23,7 @@ type FakeEthash struct { // still have to conform to the Ethereum consensus rules. func NewFakeFailer(fail uint64) *FakeEthash { return &FakeEthash{ - Ethash: newFakeEth(ModeFake), + Ethash: newFakeEth(ethashcfg.ModeFake), fakeFail: fail, } } @@ -32,7 +33,7 @@ func NewFakeFailer(fail uint64) *FakeEthash { // consensus rules. func NewFaker() *FakeEthash { return &FakeEthash{ - Ethash: newFakeEth(ModeFake), + Ethash: newFakeEth(ethashcfg.ModeFake), } } @@ -41,14 +42,14 @@ func NewFaker() *FakeEthash { // they still have to conform to the Ethereum consensus rules. func NewFakeDelayer(delay time.Duration) *FakeEthash { return &FakeEthash{ - Ethash: newFakeEth(ModeFake), + Ethash: newFakeEth(ethashcfg.ModeFake), fakeDelay: delay, } } -func newFakeEth(mode Mode) Ethash { +func newFakeEth(mode ethashcfg.Mode) Ethash { return Ethash{ - config: Config{ + config: ethashcfg.Config{ PowMode: mode, Log: log.Root(), }, @@ -132,8 +133,8 @@ type FullFakeEthash FakeEthash func NewFullFaker() *FullFakeEthash { return &FullFakeEthash{ Ethash: Ethash{ - config: Config{ - PowMode: ModeFullFake, + config: ethashcfg.Config{ + PowMode: ethashcfg.ModeFullFake, Log: log.Root(), }, }, diff --git a/consensus/ethash/sealer_test.go b/consensus/ethash/sealer_test.go index 610991dff..72bcf16fd 100644 --- a/consensus/ethash/sealer_test.go +++ b/consensus/ethash/sealer_test.go @@ -27,6 +27,7 @@ import ( "github.com/goccy/go-json" libcommon "github.com/ledgerwatch/erigon-lib/common" + "github.com/ledgerwatch/erigon/consensus/ethash/ethashcfg" "github.com/ledgerwatch/erigon/turbo/testlog" @@ -98,8 +99,8 @@ func TestRemoteNotifyFull(t *testing.T) { defer server.Close() // Create the custom ethash engine. - config := Config{ - PowMode: ModeTest, + config := ethashcfg.Config{ + PowMode: ethashcfg.ModeTest, NotifyFull: true, Log: testlog.Logger(t, log.LvlWarn), } @@ -196,8 +197,8 @@ func TestRemoteMultiNotifyFull(t *testing.T) { defer server.Close() // Create the custom ethash engine. - config := Config{ - PowMode: ModeTest, + config := ethashcfg.Config{ + PowMode: ethashcfg.ModeTest, NotifyFull: true, Log: testlog.Logger(t, log.LvlWarn), } diff --git a/core/block_validator_test.go b/core/block_validator_test.go index 7ec0b9d60..dd7a05089 100644 --- a/core/block_validator_test.go +++ b/core/block_validator_test.go @@ -21,6 +21,7 @@ import ( "github.com/ledgerwatch/erigon/consensus/ethash" "github.com/ledgerwatch/erigon/core" + "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/erigon/eth/stagedsync" "github.com/ledgerwatch/erigon/ethdb/olddb" "github.com/ledgerwatch/erigon/params" @@ -31,7 +32,7 @@ import ( func TestHeaderVerification(t *testing.T) { // Create a simple chain to verify var ( - gspec = &core.Genesis{Config: params.TestChainConfig} + gspec = &types.Genesis{Config: params.TestChainConfig} engine = ethash.NewFaker() ) m := stages.MockWithGenesisEngine(t, gspec, engine, false) @@ -68,7 +69,7 @@ func TestHeaderVerification(t *testing.T) { func TestHeaderWithSealVerification(t *testing.T) { // Create a simple chain to verify var ( - gspec = &core.Genesis{Config: params.TestChainAuraConfig} + gspec = &types.Genesis{Config: params.TestChainAuraConfig} engine = ethash.NewFaker() ) m := stages.MockWithGenesisEngine(t, gspec, engine, false) diff --git a/core/chain_makers.go b/core/chain_makers.go index 7b6a9f45f..6c2167294 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -24,6 +24,7 @@ import ( "github.com/ledgerwatch/erigon-lib/chain" libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/common/length" + "github.com/ledgerwatch/erigon/eth/ethconfig" "github.com/ledgerwatch/erigon/core/systemcontracts" @@ -311,7 +312,7 @@ func GenerateChain(config *chain.Config, parent *types.Block, engine consensus.E defer tx.Rollback() genblock := func(i int, parent *types.Block, ibs *state.IntraBlockState, stateReader state.StateReader, - plainStateWriter *state.PlainStateWriter) (*types.Block, types.Receipts, error) { + stateWriter state.StateWriter) (*types.Block, types.Receipts, error) { b := &BlockGen{i: i, chain: blocks, parent: parent, ibs: ibs, stateReader: stateReader, config: config, engine: engine, txs: make([]types.Transaction, 0, 1), receipts: make([]*types.Receipt, 0, 1), uncles: make([]*types.Header, 0, 1)} b.header = makeHeader(chainreader, parent, ibs, b.engine) // Mutate the state and block according to any hard-fork specs @@ -335,8 +336,8 @@ func GenerateChain(config *chain.Config, parent *types.Block, engine consensus.E return nil, nil, fmt.Errorf("call to FinaliseAndAssemble: %w", err) } // Write state changes to db - if err := ibs.CommitBlock(config.Rules(b.header.Number.Uint64(), b.header.Time), plainStateWriter); err != nil { - return nil, nil, fmt.Errorf("call to CommitBlock to plainStateWriter: %w", err) + if err := ibs.CommitBlock(config.Rules(b.header.Number.Uint64(), b.header.Time), stateWriter); err != nil { + return nil, nil, fmt.Errorf("call to CommitBlock to stateWriter: %w", err) } if err := tx.ClearBucket(kv.HashedAccounts); err != nil { @@ -431,10 +432,16 @@ func GenerateChain(config *chain.Config, parent *types.Block, engine consensus.E } for i := 0; i < n; i++ { - stateReader := state.NewPlainStateReader(tx) - plainStateWriter := state.NewPlainStateWriter(tx, nil, parent.NumberU64()+uint64(i)+1) + var stateReader state.StateReader + var stateWriter state.StateWriter + if ethconfig.EnableHistoryV4InTest { + + } else { + stateReader = state.NewPlainStateReader(tx) + stateWriter = state.NewPlainStateWriter(tx, nil, parent.NumberU64()+uint64(i)+1) + } ibs := state.New(stateReader) - block, receipt, err := genblock(i, parent, ibs, stateReader, plainStateWriter) + block, receipt, err := genblock(i, parent, ibs, stateReader, stateWriter) if err != nil { return nil, fmt.Errorf("generating block %d: %w", i, err) } diff --git a/core/genesis_test.go b/core/genesis_test.go index 1c176e3f0..92eef5152 100644 --- a/core/genesis_test.go +++ b/core/genesis_test.go @@ -46,12 +46,12 @@ func TestGenesisBlockRoots(t *testing.T) { require := require.New(t) var err error - block, _, _ := core.MainnetGenesisBlock().ToBlock("") + block, _, _ := core.GenesisToBlock(core.MainnetGenesisBlock(), "") if block.Hash() != params.MainnetGenesisHash { t.Errorf("wrong mainnet genesis hash, got %v, want %v", block.Hash(), params.MainnetGenesisHash) } - block, _, err = core.SokolGenesisBlock().ToBlock("") + block, _, err = core.GenesisToBlock(core.SokolGenesisBlock(), "") require.NoError(err) if block.Root() != params.SokolGenesisStateRoot { t.Errorf("wrong Sokol genesis state root, got %v, want %v", block.Root(), params.SokolGenesisStateRoot) @@ -60,7 +60,7 @@ func TestGenesisBlockRoots(t *testing.T) { t.Errorf("wrong Sokol genesis hash, got %v, want %v", block.Hash(), params.SokolGenesisHash) } - block, _, err = core.GnosisGenesisBlock().ToBlock("") + block, _, err = core.GenesisToBlock(core.GnosisGenesisBlock(), "") require.NoError(err) if block.Root() != params.GnosisGenesisStateRoot { t.Errorf("wrong Gnosis Chain genesis state root, got %v, want %v", block.Root(), params.GnosisGenesisStateRoot) @@ -69,7 +69,7 @@ func TestGenesisBlockRoots(t *testing.T) { t.Errorf("wrong Gnosis Chain genesis hash, got %v, want %v", block.Hash(), params.GnosisGenesisHash) } - block, _, err = core.ChiadoGenesisBlock().ToBlock("") + block, _, err = core.GenesisToBlock(core.ChiadoGenesisBlock(), "") require.NoError(err) if block.Root() != params.ChiadoGenesisStateRoot { t.Errorf("wrong Chiado genesis state root, got %v, want %v", block.Root(), params.ChiadoGenesisStateRoot) @@ -99,7 +99,7 @@ func TestSokolHeaderRLP(t *testing.T) { require := require.New(t) { //sokol expect := common.FromHex("f9020da00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0fad4af258fd11939fae0c6c6eec9d340b1caac0b0196fd9a1bc3f489c5bf00b3a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200008083663be080808080b8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") - block, _, err := core.SokolGenesisBlock().ToBlock("") + block, _, err := core.GenesisToBlock(core.SokolGenesisBlock(), "") require.NoError(err) b, err := rlp.EncodeToBytes(block.Header()) require.NoError(err) @@ -154,9 +154,9 @@ func TestAllocConstructor(t *testing.T) { funds := big.NewInt(1000000000) address := libcommon.HexToAddress("0x1000000000000000000000000000000000000001") - genSpec := &core.Genesis{ + genSpec := &types.Genesis{ Config: params.AllProtocolChanges, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Constructor: deploymentCode, Balance: funds}, }, } diff --git a/core/genesis.go b/core/genesis_write.go similarity index 73% rename from core/genesis.go rename to core/genesis_write.go index 255f49d5f..2c0e0f8f6 100644 --- a/core/genesis.go +++ b/core/genesis_write.go @@ -17,13 +17,10 @@ package core import ( - "bytes" "context" "embed" "encoding/binary" - "encoding/hex" "encoding/json" - "errors" "fmt" "math/big" "sync" @@ -37,7 +34,6 @@ import ( "github.com/ledgerwatch/erigon-lib/kv/rawdbv3" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/common/hexutil" - "github.com/ledgerwatch/erigon/common/math" "github.com/ledgerwatch/erigon/consensus/ethash" "github.com/ledgerwatch/erigon/consensus/serenity" "github.com/ledgerwatch/erigon/core/rawdb" @@ -51,131 +47,6 @@ import ( "golang.org/x/exp/slices" ) -//go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go -//go:generate gencodec -type GenesisAccount -field-override genesisAccountMarshaling -out gen_genesis_account.go - -//go:embed allocs -var allocs embed.FS - -var ErrGenesisNoConfig = errors.New("genesis has no chain configuration") - -// Genesis specifies the header fields, state of a genesis block. It also defines hard -// fork switch-over blocks through the chain configuration. -type Genesis struct { - Config *chain.Config `json:"config"` - Nonce uint64 `json:"nonce"` - Timestamp uint64 `json:"timestamp"` - ExtraData []byte `json:"extraData"` - GasLimit uint64 `json:"gasLimit" gencodec:"required"` - Difficulty *big.Int `json:"difficulty" gencodec:"required"` - Mixhash libcommon.Hash `json:"mixHash"` - Coinbase libcommon.Address `json:"coinbase"` - Alloc GenesisAlloc `json:"alloc" gencodec:"required"` - AuRaStep uint64 `json:"auRaStep"` - AuRaSeal []byte `json:"auRaSeal"` - - // These fields are used for consensus tests. Please don't use them - // in actual genesis blocks. - Number uint64 `json:"number"` - GasUsed uint64 `json:"gasUsed"` - ParentHash libcommon.Hash `json:"parentHash"` - BaseFee *big.Int `json:"baseFeePerGas"` - ExcessDataGas *big.Int `json:"excessDataGas"` -} - -// GenesisAlloc specifies the initial state that is part of the genesis block. -type GenesisAlloc map[libcommon.Address]GenesisAccount - -type AuthorityRoundSeal struct { - /// Seal step. - Step uint64 `json:"step"` - /// Seal signature. - Signature libcommon.Hash `json:"signature"` -} - -var genesisTmpDB kv.RwDB -var genesisDBLock sync.Mutex - -func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error { - m := make(map[common.UnprefixedAddress]GenesisAccount) - if err := json.Unmarshal(data, &m); err != nil { - return err - } - *ga = make(GenesisAlloc) - for addr, a := range m { - (*ga)[libcommon.Address(addr)] = a - } - return nil -} - -// GenesisAccount is an account in the state of the genesis block. -// Either use "constructor" for deployment code or "code" directly for the final code. -type GenesisAccount struct { - Constructor []byte `json:"constructor,omitempty"` // deployment code - Code []byte `json:"code,omitempty"` // final contract code - Storage map[libcommon.Hash]libcommon.Hash `json:"storage,omitempty"` - Balance *big.Int `json:"balance" gencodec:"required"` - Nonce uint64 `json:"nonce,omitempty"` - PrivateKey []byte `json:"secretKey,omitempty"` // for tests -} - -// field type overrides for gencodec -type genesisSpecMarshaling struct { - Nonce math.HexOrDecimal64 - Timestamp math.HexOrDecimal64 - ExtraData hexutil.Bytes - GasLimit math.HexOrDecimal64 - GasUsed math.HexOrDecimal64 - Number math.HexOrDecimal64 - Difficulty *math.HexOrDecimal256 - BaseFee *math.HexOrDecimal256 - ExcessDataGas *math.HexOrDecimal256 - Alloc map[common.UnprefixedAddress]GenesisAccount -} - -type genesisAccountMarshaling struct { - Constructor hexutil.Bytes - Code hexutil.Bytes - Balance *math.HexOrDecimal256 - Nonce math.HexOrDecimal64 - Storage map[storageJSON]storageJSON - PrivateKey hexutil.Bytes -} - -// storageJSON represents a 256 bit byte array, but allows less than 256 bits when -// unmarshaling from hex. -type storageJSON libcommon.Hash - -func (h *storageJSON) UnmarshalText(text []byte) error { - text = bytes.TrimPrefix(text, []byte("0x")) - if len(text) > 64 { - return fmt.Errorf("too many hex characters in storage key/value %q", text) - } - offset := len(h) - len(text)/2 // pad on the left - if _, err := hex.Decode(h[offset:], text); err != nil { - return fmt.Errorf("invalid hex storage key/value %q", text) - } - return nil -} - -func (h storageJSON) MarshalText() ([]byte, error) { - return hexutil.Bytes(h[:]).MarshalText() -} - -// GenesisMismatchError is raised when trying to overwrite an existing -// genesis block with an incompatible one. -type GenesisMismatchError struct { - Stored, New libcommon.Hash -} - -func (e *GenesisMismatchError) Error() string { - config := params.ChainConfigByGenesisHash(e.Stored) - if config == nil { - return fmt.Sprintf("database contains incompatible genesis (have %x, new %x)", e.Stored, e.New) - } - return fmt.Sprintf("database contains incompatible genesis (try with --chain=%s)", config.ChainName) -} - // CommitGenesisBlock writes or updates the genesis block in db. // The block that will be used is: // @@ -189,11 +60,11 @@ func (e *GenesisMismatchError) Error() string { // error is a *params.ConfigCompatError and the new, unwritten config is returned. // // The returned chain configuration is never nil. -func CommitGenesisBlock(db kv.RwDB, genesis *Genesis, tmpDir string) (*chain.Config, *types.Block, error) { +func CommitGenesisBlock(db kv.RwDB, genesis *types.Genesis, tmpDir string) (*chain.Config, *types.Block, error) { return CommitGenesisBlockWithOverride(db, genesis, nil, tmpDir) } -func CommitGenesisBlockWithOverride(db kv.RwDB, genesis *Genesis, overrideShanghaiTime *big.Int, tmpDir string) (*chain.Config, *types.Block, error) { +func CommitGenesisBlockWithOverride(db kv.RwDB, genesis *types.Genesis, overrideShanghaiTime *big.Int, tmpDir string) (*chain.Config, *types.Block, error) { tx, err := db.BeginRw(context.Background()) if err != nil { return nil, nil, err @@ -210,20 +81,12 @@ func CommitGenesisBlockWithOverride(db kv.RwDB, genesis *Genesis, overrideShangh return c, b, nil } -func MustCommitGenesisBlock(db kv.RwDB, genesis *Genesis, tmpDir string) (*chain.Config, *types.Block) { - c, b, err := CommitGenesisBlock(db, genesis, tmpDir) - if err != nil { - panic(err) - } - return c, b -} - -func WriteGenesisBlock(db kv.RwTx, genesis *Genesis, overrideShanghaiTime *big.Int, tmpDir string) (*chain.Config, *types.Block, error) { +func WriteGenesisBlock(tx kv.RwTx, genesis *types.Genesis, overrideShanghaiTime *big.Int, tmpDir string) (*chain.Config, *types.Block, error) { if genesis != nil && genesis.Config == nil { - return params.AllProtocolChanges, nil, ErrGenesisNoConfig + return params.AllProtocolChanges, nil, types.ErrGenesisNoConfig } // Just commit the new block if there is no stored genesis block. - storedHash, storedErr := rawdb.ReadCanonicalHash(db, 0) + storedHash, storedErr := rawdb.ReadCanonicalHash(tx, 0) if storedErr != nil { return nil, nil, storedErr } @@ -242,7 +105,7 @@ func WriteGenesisBlock(db kv.RwTx, genesis *Genesis, overrideShanghaiTime *big.I custom = false } applyOverrides(genesis.Config) - block, _, err1 := genesis.Write(db, tmpDir) + block, _, err1 := write(tx, genesis, tmpDir) if err1 != nil { return genesis.Config, nil, err1 } @@ -254,32 +117,32 @@ func WriteGenesisBlock(db kv.RwTx, genesis *Genesis, overrideShanghaiTime *big.I // Check whether the genesis block is already written. if genesis != nil { - block, _, err1 := genesis.ToBlock(tmpDir) + block, _, err1 := GenesisToBlock(genesis, tmpDir) if err1 != nil { return genesis.Config, nil, err1 } hash := block.Hash() if hash != storedHash { - return genesis.Config, block, &GenesisMismatchError{storedHash, hash} + return genesis.Config, block, &types.GenesisMismatchError{Stored: storedHash, New: hash} } } - storedBlock, err := rawdb.ReadBlockByHash(db, storedHash) + storedBlock, err := rawdb.ReadBlockByHash(tx, storedHash) if err != nil { return genesis.Config, nil, err } // Get the existing chain configuration. - newCfg := genesis.configOrDefault(storedHash) + newCfg := genesis.ConfigOrDefault(storedHash) applyOverrides(newCfg) if err := newCfg.CheckConfigForkOrder(); err != nil { return newCfg, nil, err } - storedCfg, storedErr := rawdb.ReadChainConfig(db, storedHash) + storedCfg, storedErr := rawdb.ReadChainConfig(tx, storedHash) if storedErr != nil && newCfg.Bor == nil { return newCfg, nil, storedErr } if storedCfg == nil { log.Warn("Found genesis block without chain config") - err1 := rawdb.WriteChainConfig(db, storedHash, newCfg) + err1 := rawdb.WriteChainConfig(tx, storedHash, newCfg) if err1 != nil { return newCfg, nil, err1 } @@ -294,46 +157,357 @@ func WriteGenesisBlock(db kv.RwTx, genesis *Genesis, overrideShanghaiTime *big.I } // Check config compatibility and write the config. Compatibility errors // are returned to the caller unless we're already at block zero. - height := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db)) + height := rawdb.ReadHeaderNumber(tx, rawdb.ReadHeadHeaderHash(tx)) if height != nil { compatibilityErr := storedCfg.CheckCompatible(newCfg, *height) if compatibilityErr != nil && *height != 0 && compatibilityErr.RewindTo != 0 { return newCfg, storedBlock, compatibilityErr } } - if err := rawdb.WriteChainConfig(db, storedHash, newCfg); err != nil { + if err := rawdb.WriteChainConfig(tx, storedHash, newCfg); err != nil { return newCfg, nil, err } return newCfg, storedBlock, nil } -func (g *Genesis) configOrDefault(genesisHash libcommon.Hash) *chain.Config { - if g != nil { - return g.Config +func WriteGenesisState(g *types.Genesis, tx kv.RwTx, tmpDir string) (*types.Block, *state.IntraBlockState, error) { + block, statedb, err := GenesisToBlock(g, tmpDir) + if err != nil { + return nil, nil, err + } + for addr, account := range g.Alloc { + if len(account.Code) > 0 || len(account.Storage) > 0 { + // Special case for weird tests - inaccessible storage + var b [8]byte + binary.BigEndian.PutUint64(b[:], state.FirstContractIncarnation) + if err := tx.Put(kv.IncarnationMap, addr[:], b[:]); err != nil { + return nil, nil, err + } + } } - config := params.ChainConfigByGenesisHash(genesisHash) - if config != nil { - return config + if block.Number().Sign() != 0 { + return nil, statedb, fmt.Errorf("can't commit genesis block with number > 0") + } + + blockWriter := state.NewPlainStateWriter(tx, tx, 0) + + if err := statedb.CommitBlock(&chain.Rules{}, blockWriter); err != nil { + return nil, statedb, fmt.Errorf("cannot write state: %w", err) + } + if err := blockWriter.WriteChangeSets(); err != nil { + return nil, statedb, fmt.Errorf("cannot write change sets: %w", err) + } + if err := blockWriter.WriteHistory(); err != nil { + return nil, statedb, fmt.Errorf("cannot write history: %w", err) + } + return block, statedb, nil +} +func MustCommitGenesis(g *types.Genesis, db kv.RwDB, tmpDir string) *types.Block { + tx, err := db.BeginRw(context.Background()) + if err != nil { + panic(err) + } + defer tx.Rollback() + block, _, err := write(tx, g, tmpDir) + if err != nil { + panic(err) + } + err = tx.Commit() + if err != nil { + panic(err) + } + return block +} + +// Write writes the block and state of a genesis specification to the database. +// The block is committed as the canonical head block. +func write(tx kv.RwTx, g *types.Genesis, tmpDir string) (*types.Block, *state.IntraBlockState, error) { + block, statedb, err2 := WriteGenesisState(g, tx, tmpDir) + if err2 != nil { + return block, statedb, err2 + } + config := g.Config + if config == nil { + config = params.AllProtocolChanges + } + if err := config.CheckConfigForkOrder(); err != nil { + return nil, nil, err + } + if err := rawdb.WriteTd(tx, block.Hash(), block.NumberU64(), g.Difficulty); err != nil { + return nil, nil, err + } + if err := rawdb.WriteBlock(tx, block); err != nil { + return nil, nil, err + } + if err := rawdbv3.TxNums.WriteForGenesis(tx, 1); err != nil { + return nil, nil, err + } + if err := rawdb.WriteReceipts(tx, block.NumberU64(), nil); err != nil { + return nil, nil, err + } + + if err := rawdb.WriteCanonicalHash(tx, block.Hash(), block.NumberU64()); err != nil { + return nil, nil, err + } + + rawdb.WriteHeadBlockHash(tx, block.Hash()) + if err := rawdb.WriteHeadHeaderHash(tx, block.Hash()); err != nil { + return nil, nil, err + } + if err := rawdb.WriteChainConfig(tx, block.Hash(), config); err != nil { + return nil, nil, err + } + // We support ethash/serenity for issuance (for now) + if g.Config.Consensus != chain.EtHashConsensus { + return block, statedb, nil + } + // Issuance is the sum of allocs + genesisIssuance := big.NewInt(0) + for _, account := range g.Alloc { + genesisIssuance.Add(genesisIssuance, account.Balance) + } + + // BlockReward can be present at genesis + if block.Header().Difficulty.Cmp(serenity.SerenityDifficulty) == 0 { + // Proof-of-stake is 0.3 ether per block (TODO: revisit) + genesisIssuance.Add(genesisIssuance, serenity.RewardSerenity) } else { - return params.AllProtocolChanges + blockReward, _ := ethash.AccumulateRewards(g.Config, block.Header(), nil) + // Set BlockReward + genesisIssuance.Add(genesisIssuance, blockReward.ToBig()) + } + if err := rawdb.WriteTotalIssued(tx, 0, genesisIssuance); err != nil { + return nil, nil, err + } + return block, statedb, rawdb.WriteTotalBurnt(tx, 0, libcommon.Big0) +} + +// GenesisBlockForTesting creates and writes a block in which addr has the given wei balance. +func GenesisBlockForTesting(db kv.RwDB, addr libcommon.Address, balance *big.Int, tmpDir string) *types.Block { + g := types.Genesis{Alloc: types.GenesisAlloc{addr: {Balance: balance}}, Config: params.TestChainConfig} + block := MustCommitGenesis(&g, db, tmpDir) + return block +} + +type GenAccount struct { + Addr libcommon.Address + Balance *big.Int +} + +func GenesisWithAccounts(db kv.RwDB, accs []GenAccount, tmpDir string) *types.Block { + g := types.Genesis{Config: params.TestChainConfig} + allocs := make(map[libcommon.Address]types.GenesisAccount) + for _, acc := range accs { + allocs[acc.Addr] = types.GenesisAccount{Balance: acc.Balance} + } + g.Alloc = allocs + block := MustCommitGenesis(&g, db, tmpDir) + return block +} + +// MainnetGenesisBlock returns the Ethereum main net genesis block. +func MainnetGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.MainnetChainConfig, + Nonce: 66, + ExtraData: hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"), + GasLimit: 5000, + Difficulty: big.NewInt(17179869184), + Alloc: readPrealloc("allocs/mainnet.json"), } } -func sortedAllocKeys(m GenesisAlloc) []string { - keys := make([]string, len(m)) - i := 0 - for k := range m { - keys[i] = string(k.Bytes()) - i++ +// SepoliaGenesisBlock returns the Sepolia network genesis block. +func SepoliaGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.SepoliaChainConfig, + Nonce: 0, + ExtraData: []byte("Sepolia, Athens, Attica, Greece!"), + GasLimit: 30000000, + Difficulty: big.NewInt(131072), + Timestamp: 1633267481, + Alloc: readPrealloc("allocs/sepolia.json"), } - slices.Sort(keys) - return keys } +// RinkebyGenesisBlock returns the Rinkeby network genesis block. +func RinkebyGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.RinkebyChainConfig, + Timestamp: 1492009146, + ExtraData: hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), + GasLimit: 4700000, + Difficulty: big.NewInt(1), + Alloc: readPrealloc("allocs/rinkeby.json"), + } +} + +// GoerliGenesisBlock returns the Görli network genesis block. +func GoerliGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.GoerliChainConfig, + Timestamp: 1548854791, + ExtraData: hexutil.MustDecode("0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), + GasLimit: 10485760, + Difficulty: big.NewInt(1), + Alloc: readPrealloc("allocs/goerli.json"), + } +} + +func SokolGenesisBlock() *types.Genesis { + /* + header rlp: f9020da00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0fad4af258fd11939fae0c6c6eec9d340b1caac0b0196fd9a1bc3f489c5bf00b3a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200008083663be080808080b8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + */ + return &types.Genesis{ + Config: params.SokolChainConfig, + Timestamp: 0x0, + AuRaSeal: common.FromHex("0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), + GasLimit: 0x663BE0, + Difficulty: big.NewInt(0x20000), + Alloc: readPrealloc("allocs/sokol.json"), + } +} + +func BSCGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.BSCChainConfig, + Nonce: 0x00, + Timestamp: 0x5e9da7ce, + ExtraData: hexutil.MustDecode("0x00000000000000000000000000000000000000000000000000000000000000002a7cdd959bfe8d9487b2a43b33565295a698f7e26488aa4d1955ee33403f8ccb1d4de5fb97c7ade29ef9f4360c606c7ab4db26b016007d3ad0ab86a0ee01c3b1283aa067c58eab4709f85e99d46de5fe685b1ded8013785d6623cc18d214320b6bb6475978f3adfc719c99674c072166708589033e2d9afec2be4ec20253b8642161bc3f444f53679c1f3d472f7be8361c80a4c1e7e9aaf001d0877f1cfde218ce2fd7544e0b2cc94692d4a704debef7bcb61328b8f7166496996a7da21cf1f1b04d9b3e26a3d0772d4c407bbe49438ed859fe965b140dcf1aab71a96bbad7cf34b5fa511d8e963dbba288b1960e75d64430b3230294d12c6ab2aac5c2cd68e80b16b581ea0a6e3c511bbd10f4519ece37dc24887e11b55d7ae2f5b9e386cd1b50a4550696d957cb4900f03a82012708dafc9e1b880fd083b32182b869be8e0922b81f8e175ffde54d797fe11eb03f9e3bf75f1d68bf0b8b6fb4e317a0f9d6f03eaf8ce6675bc60d8c4d90829ce8f72d0163c1d5cf348a862d55063035e7a025f4da968de7e4d7e4004197917f4070f1d6caa02bbebaebb5d7e581e4b66559e635f805ff0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), + GasLimit: 0x2625a00, + Difficulty: big.NewInt(0x1), + Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), + Coinbase: libcommon.HexToAddress("0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE"), + Alloc: readPrealloc("allocs/bsc.json"), + Number: 0x00, + GasUsed: 0x00, + } +} + +func ChapelGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.ChapelChainConfig, + Nonce: 0x00, + Timestamp: 0x5e9da7ce, + ExtraData: hexutil.MustDecode("0x00000000000000000000000000000000000000000000000000000000000000001284214b9b9c85549ab3d2b972df0deef66ac2c9b71b214cb885500844365e95cd9942c7276e7fd8a2959d3f95eae5dc7d70144ce1b73b403b7eb6e0980a75ecd1309ea12fa2ed87a8744fbfc9b863d535552c16704d214347f29fa77f77da6d75d7c752f474cf03cceff28abc65c9cbae594f725c80e12d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), + GasLimit: 0x2625a00, + Difficulty: big.NewInt(0x1), + Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), + Coinbase: libcommon.HexToAddress("0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE"), + Alloc: readPrealloc("allocs/chapel.json"), + Number: 0x00, + GasUsed: 0x00, + } +} + +func RialtoGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.RialtoChainConfig, + Nonce: 0x00, + Timestamp: 0x5e9da7ce, + ExtraData: hexutil.MustDecode("0x00000000000000000000000000000000000000000000000000000000000000001284214b9b9c85549ab3d2b972df0deef66ac2c9b71b214cb885500844365e95cd9942c7276e7fd8a2959d3f95eae5dc7d70144ce1b73b403b7eb6e0980a75ecd1309ea12fa2ed87a8744fbfc9b863d535552c16704d214347f29fa77f77da6d75d7c752f474cf03cceff28abc65c9cbae594f725c80e12d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), + GasLimit: 0x2625a00, + Difficulty: big.NewInt(0x1), + Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), + Coinbase: libcommon.HexToAddress("0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE"), + Alloc: readPrealloc("allocs/bsc.json"), + Number: 0x00, + GasUsed: 0x00, + } +} + +func MumbaiGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.MumbaiChainConfig, + Nonce: 0, + Timestamp: 1558348305, + GasLimit: 10000000, + Difficulty: big.NewInt(1), + Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), + Coinbase: libcommon.HexToAddress("0x0000000000000000000000000000000000000000"), + Alloc: readPrealloc("allocs/mumbai.json"), + } +} + +// BorMainnetGenesisBlock returns the Bor Mainnet network genesis block. +func BorMainnetGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.BorMainnetChainConfig, + Nonce: 0, + Timestamp: 1590824836, + GasLimit: 10000000, + Difficulty: big.NewInt(1), + Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), + Coinbase: libcommon.HexToAddress("0x0000000000000000000000000000000000000000"), + Alloc: readPrealloc("allocs/bor_mainnet.json"), + } +} + +func BorDevnetGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.BorDevnetChainConfig, + Nonce: 0, + Timestamp: 1558348305, + GasLimit: 10000000, + Difficulty: big.NewInt(1), + Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), + Coinbase: libcommon.HexToAddress("0x0000000000000000000000000000000000000000"), + Alloc: readPrealloc("allocs/bor_devnet.json"), + } +} + +func GnosisGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.GnosisChainConfig, + Timestamp: 0, + AuRaSeal: common.FromHex("0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), + GasLimit: 0x989680, + Difficulty: big.NewInt(0x20000), + Alloc: readPrealloc("allocs/gnosis.json"), + } +} + +func ChiadoGenesisBlock() *types.Genesis { + return &types.Genesis{ + Config: params.ChiadoChainConfig, + Timestamp: 0, + AuRaSeal: common.FromHex("0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), + GasLimit: 0x989680, + Difficulty: big.NewInt(0x20000), + Alloc: readPrealloc("allocs/chiado.json"), + } +} + +// Pre-calculated version of: +// +// DevnetSignPrivateKey = crypto.HexToECDSA(sha256.Sum256([]byte("erigon devnet key"))) +// DevnetEtherbase=crypto.PubkeyToAddress(DevnetSignPrivateKey.PublicKey) +var DevnetSignPrivateKey, _ = crypto.HexToECDSA("26e86e45f6fc45ec6e2ecd128cec80fa1d1505e5507dcd2ae58c3130a7a97b48") +var DevnetEtherbase = libcommon.HexToAddress("67b1d87101671b127f5f8714789c7192f7ad340e") + +// DeveloperGenesisBlock returns the 'geth --dev' genesis block. +func DeveloperGenesisBlock(period uint64, faucet libcommon.Address) *types.Genesis { + // Override the default period to the user requested one + config := *params.AllCliqueProtocolChanges + config.Clique.Period = period + + // Assemble and return the genesis with the precompiles and faucet pre-funded + return &types.Genesis{ + Config: &config, + ExtraData: append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...), + GasLimit: 11500000, + Difficulty: big.NewInt(1), + Alloc: readPrealloc("allocs/dev.json"), + } +} + +var genesisTmpDB kv.RwDB +var genesisDBLock sync.Mutex + // ToBlock creates the genesis block and writes state of a genesis specification // to the given database (or discards it if nil). -func (g *Genesis) ToBlock(tmpDir string) (*types.Block, *state.IntraBlockState, error) { +func GenesisToBlock(g *types.Genesis, tmpDir string) (*types.Block, *state.IntraBlockState, error) { _ = g.Alloc //nil-check head := &types.Header{ @@ -449,354 +623,28 @@ func (g *Genesis) ToBlock(tmpDir string) (*types.Block, *state.IntraBlockState, return types.NewBlock(head, nil, nil, nil, withdrawals), statedb, nil } -func (g *Genesis) WriteGenesisState(tx kv.RwTx, tmpDir string) (*types.Block, *state.IntraBlockState, error) { - block, statedb, err := g.ToBlock(tmpDir) - if err != nil { - return nil, nil, err +func sortedAllocKeys(m types.GenesisAlloc) []string { + keys := make([]string, len(m)) + i := 0 + for k := range m { + keys[i] = string(k.Bytes()) + i++ } - for addr, account := range g.Alloc { - if len(account.Code) > 0 || len(account.Storage) > 0 { - // Special case for weird tests - inaccessible storage - var b [8]byte - binary.BigEndian.PutUint64(b[:], state.FirstContractIncarnation) - if err := tx.Put(kv.IncarnationMap, addr[:], b[:]); err != nil { - return nil, nil, err - } - } - } - - if block.Number().Sign() != 0 { - return nil, statedb, fmt.Errorf("can't commit genesis block with number > 0") - } - - blockWriter := state.NewPlainStateWriter(tx, tx, 0) - - if err := statedb.CommitBlock(&chain.Rules{}, blockWriter); err != nil { - return nil, statedb, fmt.Errorf("cannot write state: %w", err) - } - if err := blockWriter.WriteChangeSets(); err != nil { - return nil, statedb, fmt.Errorf("cannot write change sets: %w", err) - } - if err := blockWriter.WriteHistory(); err != nil { - return nil, statedb, fmt.Errorf("cannot write history: %w", err) - } - return block, statedb, nil + slices.Sort(keys) + return keys } -func (g *Genesis) MustWrite(tx kv.RwTx, tmpDir string, history bool) (*types.Block, *state.IntraBlockState) { - b, s, err := g.Write(tx, tmpDir) - if err != nil { - panic(err) - } - return b, s -} +//go:embed allocs +var allocs embed.FS -// Write writes the block and state of a genesis specification to the database. -// The block is committed as the canonical head block. -func (g *Genesis) Write(tx kv.RwTx, tmpDir string) (*types.Block, *state.IntraBlockState, error) { - block, statedb, err2 := g.WriteGenesisState(tx, tmpDir) - if err2 != nil { - return block, statedb, err2 - } - config := g.Config - if config == nil { - config = params.AllProtocolChanges - } - if err := config.CheckConfigForkOrder(); err != nil { - return nil, nil, err - } - if err := rawdb.WriteTd(tx, block.Hash(), block.NumberU64(), g.Difficulty); err != nil { - return nil, nil, err - } - if err := rawdb.WriteBlock(tx, block); err != nil { - return nil, nil, err - } - if err := rawdbv3.TxNums.WriteForGenesis(tx, 1); err != nil { - return nil, nil, err - } - if err := rawdb.WriteReceipts(tx, block.NumberU64(), nil); err != nil { - return nil, nil, err - } - - if err := rawdb.WriteCanonicalHash(tx, block.Hash(), block.NumberU64()); err != nil { - return nil, nil, err - } - - rawdb.WriteHeadBlockHash(tx, block.Hash()) - if err := rawdb.WriteHeadHeaderHash(tx, block.Hash()); err != nil { - return nil, nil, err - } - if err := rawdb.WriteChainConfig(tx, block.Hash(), config); err != nil { - return nil, nil, err - } - // We support ethash/serenity for issuance (for now) - if g.Config.Consensus != chain.EtHashConsensus { - return block, statedb, nil - } - // Issuance is the sum of allocs - genesisIssuance := big.NewInt(0) - for _, account := range g.Alloc { - genesisIssuance.Add(genesisIssuance, account.Balance) - } - - // BlockReward can be present at genesis - if block.Header().Difficulty.Cmp(serenity.SerenityDifficulty) == 0 { - // Proof-of-stake is 0.3 ether per block (TODO: revisit) - genesisIssuance.Add(genesisIssuance, serenity.RewardSerenity) - } else { - blockReward, _ := ethash.AccumulateRewards(g.Config, block.Header(), nil) - // Set BlockReward - genesisIssuance.Add(genesisIssuance, blockReward.ToBig()) - } - if err := rawdb.WriteTotalIssued(tx, 0, genesisIssuance); err != nil { - return nil, nil, err - } - return block, statedb, rawdb.WriteTotalBurnt(tx, 0, libcommon.Big0) -} - -// MustCommit writes the genesis block and state to db, panicking on error. -// The block is committed as the canonical head block. -func (g *Genesis) MustCommit(db kv.RwDB, tmpDir string) *types.Block { - tx, err := db.BeginRw(context.Background()) - if err != nil { - panic(err) - } - defer tx.Rollback() - block, _ := g.MustWrite(tx, tmpDir, true) - err = tx.Commit() - if err != nil { - panic(err) - } - return block -} - -// GenesisBlockForTesting creates and writes a block in which addr has the given wei balance. -func GenesisBlockForTesting(db kv.RwDB, addr libcommon.Address, balance *big.Int, tmpDir string) *types.Block { - g := Genesis{Alloc: GenesisAlloc{addr: {Balance: balance}}, Config: params.TestChainConfig} - block := g.MustCommit(db, tmpDir) - return block -} - -type GenAccount struct { - Addr libcommon.Address - Balance *big.Int -} - -func GenesisWithAccounts(db kv.RwDB, accs []GenAccount, tmpDir string) *types.Block { - g := Genesis{Config: params.TestChainConfig} - allocs := make(map[libcommon.Address]GenesisAccount) - for _, acc := range accs { - allocs[acc.Addr] = GenesisAccount{Balance: acc.Balance} - } - g.Alloc = allocs - block := g.MustCommit(db, tmpDir) - return block -} - -// MainnetGenesisBlock returns the Ethereum main net genesis block. -func MainnetGenesisBlock() *Genesis { - return &Genesis{ - Config: params.MainnetChainConfig, - Nonce: 66, - ExtraData: hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"), - GasLimit: 5000, - Difficulty: big.NewInt(17179869184), - Alloc: readPrealloc("allocs/mainnet.json"), - } -} - -// SepoliaGenesisBlock returns the Sepolia network genesis block. -func SepoliaGenesisBlock() *Genesis { - return &Genesis{ - Config: params.SepoliaChainConfig, - Nonce: 0, - ExtraData: []byte("Sepolia, Athens, Attica, Greece!"), - GasLimit: 30000000, - Difficulty: big.NewInt(131072), - Timestamp: 1633267481, - Alloc: readPrealloc("allocs/sepolia.json"), - } -} - -// RinkebyGenesisBlock returns the Rinkeby network genesis block. -func RinkebyGenesisBlock() *Genesis { - return &Genesis{ - Config: params.RinkebyChainConfig, - Timestamp: 1492009146, - ExtraData: hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), - GasLimit: 4700000, - Difficulty: big.NewInt(1), - Alloc: readPrealloc("allocs/rinkeby.json"), - } -} - -// GoerliGenesisBlock returns the Görli network genesis block. -func GoerliGenesisBlock() *Genesis { - return &Genesis{ - Config: params.GoerliChainConfig, - Timestamp: 1548854791, - ExtraData: hexutil.MustDecode("0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), - GasLimit: 10485760, - Difficulty: big.NewInt(1), - Alloc: readPrealloc("allocs/goerli.json"), - } -} - -func SokolGenesisBlock() *Genesis { - /* - header rlp: f9020da00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0fad4af258fd11939fae0c6c6eec9d340b1caac0b0196fd9a1bc3f489c5bf00b3a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200008083663be080808080b8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 - */ - return &Genesis{ - Config: params.SokolChainConfig, - Timestamp: 0x0, - AuRaSeal: common.FromHex("0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), - GasLimit: 0x663BE0, - Difficulty: big.NewInt(0x20000), - Alloc: readPrealloc("allocs/sokol.json"), - } -} - -func BSCGenesisBlock() *Genesis { - return &Genesis{ - Config: params.BSCChainConfig, - Nonce: 0x00, - Timestamp: 0x5e9da7ce, - ExtraData: hexutil.MustDecode("0x00000000000000000000000000000000000000000000000000000000000000002a7cdd959bfe8d9487b2a43b33565295a698f7e26488aa4d1955ee33403f8ccb1d4de5fb97c7ade29ef9f4360c606c7ab4db26b016007d3ad0ab86a0ee01c3b1283aa067c58eab4709f85e99d46de5fe685b1ded8013785d6623cc18d214320b6bb6475978f3adfc719c99674c072166708589033e2d9afec2be4ec20253b8642161bc3f444f53679c1f3d472f7be8361c80a4c1e7e9aaf001d0877f1cfde218ce2fd7544e0b2cc94692d4a704debef7bcb61328b8f7166496996a7da21cf1f1b04d9b3e26a3d0772d4c407bbe49438ed859fe965b140dcf1aab71a96bbad7cf34b5fa511d8e963dbba288b1960e75d64430b3230294d12c6ab2aac5c2cd68e80b16b581ea0a6e3c511bbd10f4519ece37dc24887e11b55d7ae2f5b9e386cd1b50a4550696d957cb4900f03a82012708dafc9e1b880fd083b32182b869be8e0922b81f8e175ffde54d797fe11eb03f9e3bf75f1d68bf0b8b6fb4e317a0f9d6f03eaf8ce6675bc60d8c4d90829ce8f72d0163c1d5cf348a862d55063035e7a025f4da968de7e4d7e4004197917f4070f1d6caa02bbebaebb5d7e581e4b66559e635f805ff0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), - GasLimit: 0x2625a00, - Difficulty: big.NewInt(0x1), - Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), - Coinbase: libcommon.HexToAddress("0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE"), - Alloc: readPrealloc("allocs/bsc.json"), - Number: 0x00, - GasUsed: 0x00, - } -} - -func ChapelGenesisBlock() *Genesis { - return &Genesis{ - Config: params.ChapelChainConfig, - Nonce: 0x00, - Timestamp: 0x5e9da7ce, - ExtraData: hexutil.MustDecode("0x00000000000000000000000000000000000000000000000000000000000000001284214b9b9c85549ab3d2b972df0deef66ac2c9b71b214cb885500844365e95cd9942c7276e7fd8a2959d3f95eae5dc7d70144ce1b73b403b7eb6e0980a75ecd1309ea12fa2ed87a8744fbfc9b863d535552c16704d214347f29fa77f77da6d75d7c752f474cf03cceff28abc65c9cbae594f725c80e12d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), - GasLimit: 0x2625a00, - Difficulty: big.NewInt(0x1), - Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), - Coinbase: libcommon.HexToAddress("0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE"), - Alloc: readPrealloc("allocs/chapel.json"), - Number: 0x00, - GasUsed: 0x00, - } -} - -func RialtoGenesisBlock() *Genesis { - return &Genesis{ - Config: params.RialtoChainConfig, - Nonce: 0x00, - Timestamp: 0x5e9da7ce, - ExtraData: hexutil.MustDecode("0x00000000000000000000000000000000000000000000000000000000000000001284214b9b9c85549ab3d2b972df0deef66ac2c9b71b214cb885500844365e95cd9942c7276e7fd8a2959d3f95eae5dc7d70144ce1b73b403b7eb6e0980a75ecd1309ea12fa2ed87a8744fbfc9b863d535552c16704d214347f29fa77f77da6d75d7c752f474cf03cceff28abc65c9cbae594f725c80e12d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), - GasLimit: 0x2625a00, - Difficulty: big.NewInt(0x1), - Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), - Coinbase: libcommon.HexToAddress("0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE"), - Alloc: readPrealloc("allocs/bsc.json"), - Number: 0x00, - GasUsed: 0x00, - } -} - -func MumbaiGenesisBlock() *Genesis { - return &Genesis{ - Config: params.MumbaiChainConfig, - Nonce: 0, - Timestamp: 1558348305, - GasLimit: 10000000, - Difficulty: big.NewInt(1), - Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), - Coinbase: libcommon.HexToAddress("0x0000000000000000000000000000000000000000"), - Alloc: readPrealloc("allocs/mumbai.json"), - } -} - -// BorMainnetGenesisBlock returns the Bor Mainnet network genesis block. -func BorMainnetGenesisBlock() *Genesis { - return &Genesis{ - Config: params.BorMainnetChainConfig, - Nonce: 0, - Timestamp: 1590824836, - GasLimit: 10000000, - Difficulty: big.NewInt(1), - Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), - Coinbase: libcommon.HexToAddress("0x0000000000000000000000000000000000000000"), - Alloc: readPrealloc("allocs/bor_mainnet.json"), - } -} - -func BorDevnetGenesisBlock() *Genesis { - return &Genesis{ - Config: params.BorDevnetChainConfig, - Nonce: 0, - Timestamp: 1558348305, - GasLimit: 10000000, - Difficulty: big.NewInt(1), - Mixhash: libcommon.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000"), - Coinbase: libcommon.HexToAddress("0x0000000000000000000000000000000000000000"), - Alloc: readPrealloc("allocs/bor_devnet.json"), - } -} - -func GnosisGenesisBlock() *Genesis { - return &Genesis{ - Config: params.GnosisChainConfig, - Timestamp: 0, - AuRaSeal: common.FromHex("0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), - GasLimit: 0x989680, - Difficulty: big.NewInt(0x20000), - Alloc: readPrealloc("allocs/gnosis.json"), - } -} - -func ChiadoGenesisBlock() *Genesis { - return &Genesis{ - Config: params.ChiadoChainConfig, - Timestamp: 0, - AuRaSeal: common.FromHex("0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), - GasLimit: 0x989680, - Difficulty: big.NewInt(0x20000), - Alloc: readPrealloc("allocs/chiado.json"), - } -} - -// Pre-calculated version of: -// -// DevnetSignPrivateKey = crypto.HexToECDSA(sha256.Sum256([]byte("erigon devnet key"))) -// DevnetEtherbase=crypto.PubkeyToAddress(DevnetSignPrivateKey.PublicKey) -var DevnetSignPrivateKey, _ = crypto.HexToECDSA("26e86e45f6fc45ec6e2ecd128cec80fa1d1505e5507dcd2ae58c3130a7a97b48") -var DevnetEtherbase = libcommon.HexToAddress("67b1d87101671b127f5f8714789c7192f7ad340e") - -// DeveloperGenesisBlock returns the 'geth --dev' genesis block. -func DeveloperGenesisBlock(period uint64, faucet libcommon.Address) *Genesis { - // Override the default period to the user requested one - config := *params.AllCliqueProtocolChanges - config.Clique.Period = period - - // Assemble and return the genesis with the precompiles and faucet pre-funded - return &Genesis{ - Config: &config, - ExtraData: append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...), - GasLimit: 11500000, - Difficulty: big.NewInt(1), - Alloc: readPrealloc("allocs/dev.json"), - } -} - -func readPrealloc(filename string) GenesisAlloc { +func readPrealloc(filename string) types.GenesisAlloc { f, err := allocs.Open(filename) if err != nil { panic(fmt.Sprintf("Could not open genesis preallocation for %s: %v", filename, err)) } defer f.Close() decoder := json.NewDecoder(f) - ga := make(GenesisAlloc) + ga := make(types.GenesisAlloc) err = decoder.Decode(&ga) if err != nil { panic(fmt.Sprintf("Could not parse genesis preallocation for %s: %v", filename, err)) @@ -804,7 +652,7 @@ func readPrealloc(filename string) GenesisAlloc { return ga } -func GenesisBlockByChainName(chain string) *Genesis { +func GenesisBlockByChainName(chain string) *types.Genesis { switch chain { case networkname.MainnetChainName: return MainnetGenesisBlock() diff --git a/core/mkalloc.go b/core/mkalloc.go index bb941e805..bc131af16 100644 --- a/core/mkalloc.go +++ b/core/mkalloc.go @@ -32,7 +32,7 @@ import ( "sort" "strconv" - "github.com/ledgerwatch/erigon/core" + "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/erigon/rlp" ) @@ -44,7 +44,7 @@ func (a allocList) Len() int { return len(a) } func (a allocList) Less(i, j int) bool { return a[i].Addr.Cmp(a[j].Addr) < 0 } func (a allocList) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func makelist(g *core.Genesis) allocList { +func makelist(g *types.Genesis) allocList { a := make(allocList, 0, len(g.Alloc)) for addr, account := range g.Alloc { if len(account.Storage) > 0 || len(account.Code) > 0 || account.Nonce != 0 { @@ -57,7 +57,7 @@ func makelist(g *core.Genesis) allocList { return a } -func makealloc(g *core.Genesis) string { +func makealloc(g *types.Genesis) string { a := makelist(g) data, err := rlp.EncodeToBytes(a) if err != nil { @@ -72,7 +72,7 @@ func main() { os.Exit(1) } - g := new(core.Genesis) + g := new(types.Genesis) file, err := os.Open(os.Args[1]) if err != nil { panic(err) diff --git a/core/rawdb/rawdbreset/reset_stages.go b/core/rawdb/rawdbreset/reset_stages.go index e8bb68c78..185ad2108 100644 --- a/core/rawdb/rawdbreset/reset_stages.go +++ b/core/rawdb/rawdbreset/reset_stages.go @@ -171,7 +171,7 @@ func ResetExec(ctx context.Context, db kv.RwDB, chain string, tmpDir string) (er } if !historyV3 { genesis := core.GenesisBlockByChainName(chain) - if _, _, err := genesis.WriteGenesisState(tx, tmpDir); err != nil { + if _, _, err := core.WriteGenesisState(genesis, tx, tmpDir); err != nil { return err } } diff --git a/core/rlp_test.go b/core/rlp_test.go index e179816c8..22536d409 100644 --- a/core/rlp_test.go +++ b/core/rlp_test.go @@ -45,11 +45,11 @@ func getBlock(transactions int, uncles int, dataSize int, tmpDir string) *types. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, - Alloc: GenesisAlloc{address: {Balance: funds}}, + Alloc: types.GenesisAlloc{address: {Balance: funds}}, } - genesis = gspec.MustCommit(db, tmpDir) + genesis = MustCommitGenesis(gspec, db, tmpDir) ) // We need to generate as many blocks +1 as uncles diff --git a/core/state/database_test.go b/core/state/database_test.go index e498b97fe..b172aa3e7 100644 --- a/core/state/database_test.go +++ b/core/state/database_test.go @@ -55,7 +55,7 @@ func TestCreate2Revive(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), @@ -64,8 +64,8 @@ func TestCreate2Revive(t *testing.T) { ByzantiumBlock: big.NewInt(1), ConstantinopleBlock: big.NewInt(1), }, - Alloc: core.GenesisAlloc{ - address: core.GenesisAccount{Balance: funds}, + Alloc: types.GenesisAlloc{ + address: types.GenesisAccount{Balance: funds}, }, } signer = types.LatestSignerForChainID(nil) @@ -226,7 +226,7 @@ func TestCreate2Polymorth(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), @@ -235,8 +235,8 @@ func TestCreate2Polymorth(t *testing.T) { ByzantiumBlock: big.NewInt(1), ConstantinopleBlock: big.NewInt(1), }, - Alloc: core.GenesisAlloc{ - address: core.GenesisAccount{Balance: funds}, + Alloc: types.GenesisAlloc{ + address: types.GenesisAccount{Balance: funds}, }, } signer = types.LatestSignerForChainID(nil) @@ -443,7 +443,7 @@ func TestReorgOverSelfDestruct(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), @@ -452,8 +452,8 @@ func TestReorgOverSelfDestruct(t *testing.T) { ByzantiumBlock: big.NewInt(1), ConstantinopleBlock: big.NewInt(1), }, - Alloc: core.GenesisAlloc{ - address: core.GenesisAccount{Balance: funds}, + Alloc: types.GenesisAlloc{ + address: types.GenesisAccount{Balance: funds}, }, } ) @@ -591,7 +591,7 @@ func TestReorgOverStateChange(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), @@ -600,7 +600,7 @@ func TestReorgOverStateChange(t *testing.T) { ByzantiumBlock: big.NewInt(1), ConstantinopleBlock: big.NewInt(1), }, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, }, } @@ -741,7 +741,7 @@ func TestCreateOnExistingStorage(t *testing.T) { // Address of the contract that will be deployed contractAddr = libcommon.HexToAddress("0x3a220f351252089d385b29beca14e27f204c296a") funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), @@ -750,7 +750,7 @@ func TestCreateOnExistingStorage(t *testing.T) { ByzantiumBlock: big.NewInt(1), ConstantinopleBlock: big.NewInt(1), }, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, // Pre-existing storage item in an account without code contractAddr: {Balance: funds, Storage: map[libcommon.Hash]libcommon.Hash{{}: libcommon.HexToHash("0x42")}}, @@ -870,7 +870,7 @@ func TestEip2200Gas(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), @@ -881,7 +881,7 @@ func TestEip2200Gas(t *testing.T) { ConstantinopleBlock: big.NewInt(1), IstanbulBlock: big.NewInt(1), }, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, }, } @@ -965,15 +965,15 @@ func TestWrongIncarnation(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), TangerineWhistleBlock: new(big.Int), SpuriousDragonBlock: big.NewInt(1), }, - Alloc: core.GenesisAlloc{ - address: core.GenesisAccount{Balance: funds}, + Alloc: types.GenesisAlloc{ + address: types.GenesisAccount{Balance: funds}, }, } ) @@ -1077,15 +1077,15 @@ func TestWrongIncarnation2(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), TangerineWhistleBlock: new(big.Int), SpuriousDragonBlock: big.NewInt(1), }, - Alloc: core.GenesisAlloc{ - address: core.GenesisAccount{Balance: funds}, + Alloc: types.GenesisAlloc{ + address: types.GenesisAccount{Balance: funds}, }, } signer = types.LatestSignerForChainID(nil) @@ -1337,10 +1337,10 @@ func TestRecreateAndRewind(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ - address: core.GenesisAccount{Balance: funds}, + Alloc: types.GenesisAlloc{ + address: types.GenesisAccount{Balance: funds}, }, } ) @@ -1535,7 +1535,7 @@ func TestTxLookupUnwind(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), @@ -1544,8 +1544,8 @@ func TestTxLookupUnwind(t *testing.T) { ByzantiumBlock: big.NewInt(1), ConstantinopleBlock: big.NewInt(1), }, - Alloc: core.GenesisAlloc{ - address: core.GenesisAccount{Balance: funds}, + Alloc: types.GenesisAlloc{ + address: types.GenesisAccount{Balance: funds}, }, } signer = types.LatestSignerForChainID(nil) diff --git a/core/state/temporal/kv_temporal.go b/core/state/temporal/kv_temporal.go index 03d31bb29..3ef3fb132 100644 --- a/core/state/temporal/kv_temporal.go +++ b/core/state/temporal/kv_temporal.go @@ -15,6 +15,7 @@ import ( "github.com/ledgerwatch/erigon-lib/kv/order" "github.com/ledgerwatch/erigon-lib/kv/rawdbv3" "github.com/ledgerwatch/erigon-lib/state" + "github.com/ledgerwatch/erigon/eth/ethconfig" ) //Variables Naming: @@ -286,6 +287,9 @@ func (tx *Tx) DomainRange(name kv.Domain, fromKey, toKey []byte, asOfTs uint64, return it, nil } func (tx *Tx) DomainGet(name kv.Domain, key, key2 []byte) (v []byte, ok bool, err error) { + if ethconfig.EnableHistoryV4InTest { + panic("implement me") + } switch name { case AccountsDomain: v, err = tx.GetOne(kv.PlainState, key) @@ -301,6 +305,9 @@ func (tx *Tx) DomainGet(name kv.Domain, key, key2 []byte) (v []byte, ok bool, er } } func (tx *Tx) DomainGetAsOf(name kv.Domain, key, key2 []byte, ts uint64) (v []byte, ok bool, err error) { + if ethconfig.EnableHistoryV4InTest { + panic("implement me") + } switch name { case AccountsDomain: v, ok, err = tx.HistoryGet(AccountsHistory, key, ts) diff --git a/core/gen_genesis.go b/core/types/gen_genesis.go similarity index 99% rename from core/gen_genesis.go rename to core/types/gen_genesis.go index 2a51c5d45..df619e1ec 100644 --- a/core/gen_genesis.go +++ b/core/types/gen_genesis.go @@ -1,6 +1,6 @@ // Code generated by github.com/fjl/gencodec. DO NOT EDIT. -package core +package types import ( "encoding/json" diff --git a/core/gen_genesis_account.go b/core/types/gen_genesis_account.go similarity index 99% rename from core/gen_genesis_account.go rename to core/types/gen_genesis_account.go index 49abcea1c..e50f57670 100644 --- a/core/gen_genesis_account.go +++ b/core/types/gen_genesis_account.go @@ -1,6 +1,6 @@ // Code generated by github.com/fjl/gencodec. DO NOT EDIT. -package core +package types import ( "encoding/json" diff --git a/core/types/genesis.go b/core/types/genesis.go new file mode 100644 index 000000000..dc67d7ff4 --- /dev/null +++ b/core/types/genesis.go @@ -0,0 +1,164 @@ +// Copyright 2014 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 . + +package types + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "math/big" + + "github.com/ledgerwatch/erigon-lib/chain" + "github.com/ledgerwatch/erigon-lib/common" + common2 "github.com/ledgerwatch/erigon/common" + "github.com/ledgerwatch/erigon/common/hexutil" + "github.com/ledgerwatch/erigon/common/math" + "github.com/ledgerwatch/erigon/params" +) + +//go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go +//go:generate gencodec -type GenesisAccount -field-override genesisAccountMarshaling -out gen_genesis_account.go + +var ErrGenesisNoConfig = errors.New("genesis has no chain configuration") + +// Genesis specifies the header fields, state of a genesis block. It also defines hard +// fork switch-over blocks through the chain configuration. +type Genesis struct { + Config *chain.Config `json:"config"` + Nonce uint64 `json:"nonce"` + Timestamp uint64 `json:"timestamp"` + ExtraData []byte `json:"extraData"` + GasLimit uint64 `json:"gasLimit" gencodec:"required"` + Difficulty *big.Int `json:"difficulty" gencodec:"required"` + Mixhash common.Hash `json:"mixHash"` + Coinbase common.Address `json:"coinbase"` + Alloc GenesisAlloc `json:"alloc" gencodec:"required"` + AuRaStep uint64 `json:"auRaStep"` + AuRaSeal []byte `json:"auRaSeal"` + + // These fields are used for consensus tests. Please don't use them + // in actual genesis blocks. + Number uint64 `json:"number"` + GasUsed uint64 `json:"gasUsed"` + ParentHash common.Hash `json:"parentHash"` + BaseFee *big.Int `json:"baseFeePerGas"` + ExcessDataGas *big.Int `json:"excessDataGas"` +} + +// GenesisAlloc specifies the initial state that is part of the genesis block. +type GenesisAlloc map[common.Address]GenesisAccount + +type AuthorityRoundSeal struct { + /// Seal step. + Step uint64 `json:"step"` + /// Seal signature. + Signature common.Hash `json:"signature"` +} + +func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error { + m := make(map[common2.UnprefixedAddress]GenesisAccount) + if err := json.Unmarshal(data, &m); err != nil { + return err + } + *ga = make(GenesisAlloc) + for addr, a := range m { + (*ga)[common.Address(addr)] = a + } + return nil +} + +// GenesisAccount is an account in the state of the genesis block. +// Either use "constructor" for deployment code or "code" directly for the final code. +type GenesisAccount struct { + Constructor []byte `json:"constructor,omitempty"` // deployment code + Code []byte `json:"code,omitempty"` // final contract code + Storage map[common.Hash]common.Hash `json:"storage,omitempty"` + Balance *big.Int `json:"balance" gencodec:"required"` + Nonce uint64 `json:"nonce,omitempty"` + PrivateKey []byte `json:"secretKey,omitempty"` // for tests +} + +// field type overrides for gencodec +type genesisSpecMarshaling struct { + Nonce math.HexOrDecimal64 + Timestamp math.HexOrDecimal64 + ExtraData hexutil.Bytes + GasLimit math.HexOrDecimal64 + GasUsed math.HexOrDecimal64 + Number math.HexOrDecimal64 + Difficulty *math.HexOrDecimal256 + BaseFee *math.HexOrDecimal256 + ExcessDataGas *math.HexOrDecimal256 + Alloc map[common2.UnprefixedAddress]GenesisAccount +} + +type genesisAccountMarshaling struct { + Constructor hexutil.Bytes + Code hexutil.Bytes + Balance *math.HexOrDecimal256 + Nonce math.HexOrDecimal64 + Storage map[storageJSON]storageJSON + PrivateKey hexutil.Bytes +} + +// storageJSON represents a 256 bit byte array, but allows less than 256 bits when +// unmarshaling from hex. +type storageJSON common.Hash + +func (h *storageJSON) UnmarshalText(text []byte) error { + text = bytes.TrimPrefix(text, []byte("0x")) + if len(text) > 64 { + return fmt.Errorf("too many hex characters in storage key/value %q", text) + } + offset := len(h) - len(text)/2 // pad on the left + if _, err := hex.Decode(h[offset:], text); err != nil { + return fmt.Errorf("invalid hex storage key/value %q", text) + } + return nil +} + +func (h storageJSON) MarshalText() ([]byte, error) { + return hexutil.Bytes(h[:]).MarshalText() +} + +// GenesisMismatchError is raised when trying to overwrite an existing +// genesis block with an incompatible one. +type GenesisMismatchError struct { + Stored, New common.Hash +} + +func (e *GenesisMismatchError) Error() string { + config := params.ChainConfigByGenesisHash(e.Stored) + if config == nil { + return fmt.Sprintf("database contains incompatible genesis (have %x, new %x)", e.Stored, e.New) + } + return fmt.Sprintf("database contains incompatible genesis (try with --chain=%s)", config.ChainName) +} +func (g *Genesis) ConfigOrDefault(genesisHash common.Hash) *chain.Config { + if g != nil { + return g.Config + } + + config := params.ChainConfigByGenesisHash(genesisHash) + if config != nil { + return config + } else { + return params.AllProtocolChanges + } +} diff --git a/eth/ethconfig/config.go b/eth/ethconfig/config.go index 254eb152f..ab0570543 100644 --- a/eth/ethconfig/config.go +++ b/eth/ethconfig/config.go @@ -28,15 +28,15 @@ import ( "github.com/c2h5oh/datasize" "github.com/ledgerwatch/erigon-lib/chain" - libcommon "github.com/ledgerwatch/erigon-lib/common" + "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/common/datadir" "github.com/ledgerwatch/erigon-lib/downloader/downloadercfg" - txpool2 "github.com/ledgerwatch/erigon-lib/txpool" + "github.com/ledgerwatch/erigon-lib/txpool/txpoolcfg" - "github.com/ledgerwatch/erigon/consensus/ethash" - "github.com/ledgerwatch/erigon/core" + "github.com/ledgerwatch/erigon/consensus/ethash/ethashcfg" + "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/erigon/eth/ethconfig/estimate" - "github.com/ledgerwatch/erigon/eth/gasprice" + "github.com/ledgerwatch/erigon/eth/gasprice/gaspricecfg" "github.com/ledgerwatch/erigon/ethdb/prune" "github.com/ledgerwatch/erigon/params" "github.com/ledgerwatch/erigon/params/networkname" @@ -47,24 +47,24 @@ const HistoryV3AggregationStep = 3_125_000 // 100M / 32 //const HistoryV3AggregationStep = 3_125_000 / 100 // use this to reduce step size for dev/debug // FullNodeGPO contains default gasprice oracle settings for full node. -var FullNodeGPO = gasprice.Config{ +var FullNodeGPO = gaspricecfg.Config{ Blocks: 20, Default: big.NewInt(0), Percentile: 60, MaxHeaderHistory: 0, MaxBlockHistory: 0, - MaxPrice: gasprice.DefaultMaxPrice, - IgnorePrice: gasprice.DefaultIgnorePrice, + MaxPrice: gaspricecfg.DefaultMaxPrice, + IgnorePrice: gaspricecfg.DefaultIgnorePrice, } // LightClientGPO contains default gasprice oracle settings for light client. -var LightClientGPO = gasprice.Config{ +var LightClientGPO = gaspricecfg.Config{ Blocks: 2, Percentile: 60, MaxHeaderHistory: 300, MaxBlockHistory: 5, - MaxPrice: gasprice.DefaultMaxPrice, - IgnorePrice: gasprice.DefaultIgnorePrice, + MaxPrice: gaspricecfg.DefaultMaxPrice, + IgnorePrice: gaspricecfg.DefaultIgnorePrice, } // Defaults contains default settings for use on the Ethereum main net. @@ -76,7 +76,7 @@ var Defaults = Config{ BodyCacheLimit: 256 * 1024 * 1024, BodyDownloadTimeoutSeconds: 30, }, - Ethash: ethash.Config{ + Ethash: ethashcfg.Config{ CachesInMem: 2, CachesLockMmap: false, DatasetsInMem: 1, @@ -90,7 +90,7 @@ var Defaults = Config{ GasPrice: big.NewInt(params.GWei), Recommit: 3 * time.Second, }, - DeprecatedTxPool: core.DeprecatedDefaultTxPoolConfig, + DeprecatedTxPool: DeprecatedDefaultTxPoolConfig, RPCGasCap: 50000000, GPO: FullNodeGPO, RPCTxFeeCap: 1, // 1 ether @@ -168,7 +168,7 @@ type Config struct { // The genesis block, which is inserted if the database is empty. // If nil, the Ethereum main net block is used. - Genesis *core.Genesis `toml:",omitempty"` + Genesis *types.Genesis `toml:",omitempty"` // Protocol options NetworkID uint64 // Network ID to use for selecting peers to connect to @@ -184,7 +184,7 @@ type Config struct { ImportMode bool - BadBlockHash libcommon.Hash // hash of the block marked as bad + BadBlockHash common.Hash // hash of the block marked as bad Snapshot Snapshot Downloader *downloadercfg.Cfg @@ -196,13 +196,13 @@ type Config struct { ExternalSnapshotDownloaderAddr string // Whitelist of required block number -> hash values to accept - Whitelist map[uint64]libcommon.Hash `toml:"-"` + Whitelist map[uint64]common.Hash `toml:"-"` // Mining options Miner params.MiningConfig // Ethash options - Ethash ethash.Config + Ethash ethashcfg.Config Clique params.ConsensusSnapshotConfig Aura chain.AuRaConfig @@ -210,11 +210,11 @@ type Config struct { Bor chain.BorConfig // Transaction pool options - DeprecatedTxPool core.TxPoolConfig - TxPool txpool2.Config + DeprecatedTxPool DeprecatedTxPoolConfig + TxPool txpoolcfg.Config // Gas Price Oracle options - GPO gasprice.Config + GPO gaspricecfg.Config // RPCGasCap is the global gas cap for eth-call variants. RPCGasCap uint64 `toml:",omitempty"` diff --git a/eth/ethconfig/gen_config.go b/eth/ethconfig/gen_config.go index 502603d1d..05e2faf4a 100644 --- a/eth/ethconfig/gen_config.go +++ b/eth/ethconfig/gen_config.go @@ -8,10 +8,10 @@ import ( "github.com/c2h5oh/datasize" "github.com/ledgerwatch/erigon-lib/chain" libcommon "github.com/ledgerwatch/erigon-lib/common" + "github.com/ledgerwatch/erigon/consensus/ethash/ethashcfg" + "github.com/ledgerwatch/erigon/core/types" + "github.com/ledgerwatch/erigon/eth/gasprice/gaspricecfg" - "github.com/ledgerwatch/erigon/consensus/ethash" - "github.com/ledgerwatch/erigon/core" - "github.com/ledgerwatch/erigon/eth/gasprice" "github.com/ledgerwatch/erigon/ethdb/prune" "github.com/ledgerwatch/erigon/params" ) @@ -19,7 +19,7 @@ import ( // MarshalTOML marshals as TOML. func (c Config) MarshalTOML() (interface{}, error) { type Config struct { - Genesis *core.Genesis `toml:",omitempty"` + Genesis *types.Genesis `toml:",omitempty"` NetworkID uint64 EthDiscoveryURLs []string P2PEnabled bool @@ -32,12 +32,12 @@ func (c Config) MarshalTOML() (interface{}, error) { ExternalSnapshotDownloaderAddr string Whitelist map[uint64]libcommon.Hash `toml:"-"` Miner params.MiningConfig - Ethash ethash.Config + Ethash ethashcfg.Config Clique params.ConsensusSnapshotConfig Aura chain.AuRaConfig Parlia chain.ParliaConfig - TxPool core.TxPoolConfig - GPO gasprice.Config + TxPool DeprecatedTxPoolConfig + GPO gaspricecfg.Config RPCGasCap uint64 `toml:",omitempty"` RPCTxFeeCap float64 `toml:",omitempty"` StateStream bool @@ -72,7 +72,7 @@ func (c Config) MarshalTOML() (interface{}, error) { // UnmarshalTOML unmarshals from TOML. func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error { type Config struct { - Genesis *core.Genesis `toml:",omitempty"` + Genesis *types.Genesis `toml:",omitempty"` NetworkID *uint64 EthDiscoveryURLs []string P2PEnabled *bool @@ -85,12 +85,12 @@ func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error { ExternalSnapshotDownloaderAddr *string Whitelist map[uint64]libcommon.Hash `toml:"-"` Miner *params.MiningConfig - Ethash *ethash.Config + Ethash *ethashcfg.Config Clique *params.ConsensusSnapshotConfig Aura *chain.AuRaConfig Parlia *chain.ParliaConfig - TxPool *core.TxPoolConfig - GPO *gasprice.Config + TxPool *DeprecatedTxPoolConfig + GPO *gaspricecfg.Config RPCGasCap *uint64 `toml:",omitempty"` RPCTxFeeCap *float64 `toml:",omitempty"` StateStream *bool diff --git a/core/tx_pool.go b/eth/ethconfig/tx_pool.go similarity index 55% rename from core/tx_pool.go rename to eth/ethconfig/tx_pool.go index e7811229a..e345b8083 100644 --- a/core/tx_pool.go +++ b/eth/ethconfig/tx_pool.go @@ -14,55 +14,20 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . -package core +package ethconfig import ( - "errors" "time" - libcommon "github.com/ledgerwatch/erigon-lib/common" - "github.com/ledgerwatch/erigon-lib/txpool" + "github.com/ledgerwatch/erigon-lib/common" + "github.com/ledgerwatch/erigon-lib/txpool/txpoolcfg" ) -var ( - // ErrAlreadyKnown is returned if the transactions is already contained - // within the pool. - ErrAlreadyKnown = errors.New("already known") - - // ErrInvalidSender is returned if the transaction contains an invalid signature. - ErrInvalidSender = errors.New("invalid sender") - - // ErrUnderpriced is returned if a transaction's gas price is below the minimum - // configured for the transaction pool. - ErrUnderpriced = errors.New("transaction underpriced") - - // ErrTxPoolOverflow is returned if the transaction pool is full and can't accpet - // another remote transaction. - ErrTxPoolOverflow = errors.New("txpool is full") - - // ErrReplaceUnderpriced is returned if a transaction is attempted to be replaced - // with a different one without the required price bump. - ErrReplaceUnderpriced = errors.New("replacement transaction underpriced") - - // ErrGasLimit is returned if a transaction's requested gas limit exceeds the - // maximum allowance of the current block. - ErrGasLimit = errors.New("exceeds block gas limit") - - // ErrNegativeValue is a sanity error to ensure no one is able to specify a - // transaction with a negative value. - ErrNegativeValue = errors.New("negative value") - - // ErrOversizedData is returned if the input data of a transaction is greater - // than some meaningful limit a user might use. This is not a consensus error - // making the transaction invalid, rather a DOS protection. - ErrOversizedData = errors.New("oversized data") -) - -// TxPoolConfig are the configuration parameters of the transaction pool. -type TxPoolConfig struct { +// DeprecatedTxPoolConfig are the configuration parameters of the transaction pool. +type DeprecatedTxPoolConfig struct { Disable bool - Locals []libcommon.Address // Addresses that should be treated by default as local - NoLocals bool // Whether local transaction handling should be disabled + Locals []common.Address // Addresses that should be treated by default as local + NoLocals bool // Whether local transaction handling should be disabled PriceLimit uint64 // Minimum gas price to enforce for acceptance into the pool PriceBump uint64 // Minimum price bump percentage to replace an already existing transaction (nonce) @@ -82,7 +47,7 @@ type TxPoolConfig struct { // DeprecatedDefaultTxPoolConfig contains the default configurations for the transaction // pool. -var DeprecatedDefaultTxPoolConfig = TxPoolConfig{ +var DeprecatedDefaultTxPoolConfig = DeprecatedTxPoolConfig{ PriceLimit: 1, PriceBump: 10, @@ -95,8 +60,8 @@ var DeprecatedDefaultTxPoolConfig = TxPoolConfig{ Lifetime: 3 * time.Hour, } -var DefaultTxPool2Config = func(pool1Cfg TxPoolConfig) txpool.Config { - cfg := txpool.DefaultConfig +var DefaultTxPool2Config = func(pool1Cfg DeprecatedTxPoolConfig) txpoolcfg.Config { + cfg := txpoolcfg.DefaultConfig cfg.PendingSubPoolLimit = int(pool1Cfg.GlobalSlots) cfg.BaseFeeSubPoolLimit = int(pool1Cfg.GlobalBaseFeeQueue) cfg.QueuedSubPoolLimit = int(pool1Cfg.GlobalQueue) diff --git a/eth/ethconsensusconfig/config.go b/eth/ethconsensusconfig/config.go index 1ae814745..a9babffac 100644 --- a/eth/ethconsensusconfig/config.go +++ b/eth/ethconsensusconfig/config.go @@ -5,6 +5,7 @@ import ( "github.com/ledgerwatch/erigon-lib/chain" "github.com/ledgerwatch/erigon-lib/kv" + "github.com/ledgerwatch/erigon/consensus/ethash/ethashcfg" "github.com/davecgh/go-spew/spew" "github.com/ledgerwatch/log/v3" @@ -30,19 +31,19 @@ func CreateConsensusEngine(chainConfig *chain.Config, logger log.Logger, config var eng consensus.Engine switch consensusCfg := config.(type) { - case *ethash.Config: + case *ethashcfg.Config: switch consensusCfg.PowMode { - case ethash.ModeFake: + case ethashcfg.ModeFake: log.Warn("Ethash used in fake mode") eng = ethash.NewFaker() - case ethash.ModeTest: + case ethashcfg.ModeTest: log.Warn("Ethash used in test mode") eng = ethash.NewTester(nil, noverify) - case ethash.ModeShared: + case ethashcfg.ModeShared: log.Warn("Ethash used in shared mode") eng = ethash.NewShared() default: - eng = ethash.New(ethash.Config{ + eng = ethash.New(ethashcfg.Config{ CachesInMem: consensusCfg.CachesInMem, CachesLockMmap: consensusCfg.CachesLockMmap, DatasetDir: consensusCfg.DatasetDir, diff --git a/eth/gasprice/feehistory_test.go b/eth/gasprice/feehistory_test.go index 04c09eb3e..be48d9976 100644 --- a/eth/gasprice/feehistory_test.go +++ b/eth/gasprice/feehistory_test.go @@ -23,6 +23,7 @@ import ( "github.com/ledgerwatch/erigon/cmd/rpcdaemon/commands" "github.com/ledgerwatch/erigon/eth/gasprice" + "github.com/ledgerwatch/erigon/eth/gasprice/gaspricecfg" "github.com/ledgerwatch/erigon/rpc" ) @@ -53,7 +54,7 @@ func TestFeeHistory(t *testing.T) { //{true, 0, 0, 2, rpc.PendingBlockNumber, []float64{0, 10}, 32, 2, nil}, } for i, c := range cases { - config := gasprice.Config{ + config := gaspricecfg.Config{ MaxHeaderHistory: c.maxHeader, MaxBlockHistory: c.maxBlock, } diff --git a/eth/gasprice/gasprice.go b/eth/gasprice/gasprice.go index e9e76b322..bb3298563 100644 --- a/eth/gasprice/gasprice.go +++ b/eth/gasprice/gasprice.go @@ -25,30 +25,15 @@ import ( "github.com/holiman/uint256" "github.com/ledgerwatch/erigon-lib/chain" libcommon "github.com/ledgerwatch/erigon-lib/common" + "github.com/ledgerwatch/erigon/eth/gasprice/gaspricecfg" "github.com/ledgerwatch/log/v3" "github.com/ledgerwatch/erigon/core/types" - "github.com/ledgerwatch/erigon/params" "github.com/ledgerwatch/erigon/rpc" ) const sampleNumber = 3 // Number of transactions sampled in a block -var ( - DefaultMaxPrice = big.NewInt(500 * params.GWei) - DefaultIgnorePrice = big.NewInt(2 * params.Wei) -) - -type Config struct { - Blocks int - Percentile int - MaxHeaderHistory int - MaxBlockHistory int - Default *big.Int `toml:",omitempty"` - MaxPrice *big.Int `toml:",omitempty"` - IgnorePrice *big.Int `toml:",omitempty"` -} - // OracleBackend includes all necessary background APIs for oracle. type OracleBackend interface { HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) @@ -81,7 +66,7 @@ type Oracle struct { // NewOracle returns a new gasprice oracle which can recommend suitable // gasprice for newly created transaction. -func NewOracle(backend OracleBackend, params Config, cache Cache) *Oracle { +func NewOracle(backend OracleBackend, params gaspricecfg.Config, cache Cache) *Oracle { blocks := params.Blocks if blocks < 1 { blocks = 1 @@ -98,12 +83,12 @@ func NewOracle(backend OracleBackend, params Config, cache Cache) *Oracle { } maxPrice := params.MaxPrice if maxPrice == nil || maxPrice.Int64() <= 0 { - maxPrice = DefaultMaxPrice + maxPrice = gaspricecfg.DefaultMaxPrice log.Warn("Sanitizing invalid gasprice oracle price cap", "provided", params.MaxPrice, "updated", maxPrice) } ignorePrice := params.IgnorePrice if ignorePrice == nil || ignorePrice.Int64() < 0 { - ignorePrice = DefaultIgnorePrice + ignorePrice = gaspricecfg.DefaultIgnorePrice log.Warn("Sanitizing invalid gasprice oracle ignore price", "provided", params.IgnorePrice, "updated", ignorePrice) } return &Oracle{ diff --git a/eth/gasprice/gasprice_test.go b/eth/gasprice/gasprice_test.go index cd58c40f9..fb73a02e7 100644 --- a/eth/gasprice/gasprice_test.go +++ b/eth/gasprice/gasprice_test.go @@ -26,6 +26,7 @@ import ( "github.com/ledgerwatch/erigon-lib/chain" libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/kv" + "github.com/ledgerwatch/erigon/eth/gasprice/gaspricecfg" "github.com/ledgerwatch/erigon/cmd/rpcdaemon/commands" "github.com/ledgerwatch/erigon/core" @@ -91,9 +92,9 @@ func newTestBackend(t *testing.T) *testBackend { var ( key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") addr = crypto.PubkeyToAddress(key.PublicKey) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{addr: {Balance: big.NewInt(math.MaxInt64)}}, + Alloc: types.GenesisAlloc{addr: {Balance: big.NewInt(math.MaxInt64)}}, } signer = types.LatestSigner(gspec.Config) ) @@ -141,7 +142,7 @@ func (b *testBackend) GetBlockByNumber(number uint64) *types.Block { } func TestSuggestPrice(t *testing.T) { - config := gasprice.Config{ + config := gaspricecfg.Config{ Blocks: 2, Percentile: 60, Default: big.NewInt(params.GWei), diff --git a/eth/gasprice/gaspricecfg/gaspricecfg.go b/eth/gasprice/gaspricecfg/gaspricecfg.go new file mode 100644 index 000000000..af364b0a2 --- /dev/null +++ b/eth/gasprice/gaspricecfg/gaspricecfg.go @@ -0,0 +1,23 @@ +package gaspricecfg + +import ( + "math/big" + + "github.com/ledgerwatch/erigon/params" +) + +var DefaultIgnorePrice = big.NewInt(2 * params.Wei) + +var ( + DefaultMaxPrice = big.NewInt(500 * params.GWei) +) + +type Config struct { + Blocks int + Percentile int + MaxHeaderHistory int + MaxBlockHistory int + Default *big.Int `toml:",omitempty"` + MaxPrice *big.Int `toml:",omitempty"` + IgnorePrice *big.Int `toml:",omitempty"` +} diff --git a/eth/protocols/eth/handler_test.go b/eth/protocols/eth/handler_test.go index 0dff3a07b..f632d133d 100644 --- a/eth/protocols/eth/handler_test.go +++ b/eth/protocols/eth/handler_test.go @@ -132,9 +132,9 @@ func TestGetBlockReceipts(t *testing.T) { // newTestBackend creates a chain with a number of explicitly defined blocks and // wraps it into a mock backend. func mockWithGenerator(t *testing.T, blocks int, generator func(int, *core.BlockGen)) *stages.MockSentry { - m := stages.MockWithGenesis(t, &core.Genesis{ + m := stages.MockWithGenesis(t, &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{testAddr: {Balance: big.NewInt(1000000)}}, + Alloc: types.GenesisAlloc{testAddr: {Balance: big.NewInt(1000000)}}, }, testKey, false) if blocks > 0 { chain, _ := core.GenerateChain(m.ChainConfig, m.Genesis, m.Engine, m.DB, blocks, generator, true) diff --git a/eth/stagedsync/exec3.go b/eth/stagedsync/exec3.go index f438b5678..d3f6302d2 100644 --- a/eth/stagedsync/exec3.go +++ b/eth/stagedsync/exec3.go @@ -811,7 +811,7 @@ func processResultQueue(rws *exec22.TxTaskQueue, outputTxNumIn uint64, rs *state func reconstituteStep(last bool, workerCount int, ctx context.Context, db kv.RwDB, txNum uint64, dirs datadir.Dirs, as *libstate.AggregatorStep, chainDb kv.RwDB, blockReader services.FullBlockReader, - chainConfig *chain.Config, logger log.Logger, genesis *core.Genesis, engine consensus.Engine, + chainConfig *chain.Config, logger log.Logger, genesis *types.Genesis, engine consensus.Engine, batchSize datasize.ByteSize, s *StageState, blockNum uint64, total uint64, ) error { var startOk, endOk bool @@ -1331,7 +1331,7 @@ func safeCloseTxTaskCh(ch chan *exec22.TxTask) { func ReconstituteState(ctx context.Context, s *StageState, dirs datadir.Dirs, workerCount int, batchSize datasize.ByteSize, chainDb kv.RwDB, blockReader services.FullBlockReader, logger log.Logger, agg *state2.AggregatorV3, engine consensus.Engine, - chainConfig *chain.Config, genesis *core.Genesis) (err error) { + chainConfig *chain.Config, genesis *types.Genesis) (err error) { startTime := time.Now() defer agg.EnableMadvNormal().DisableReadAhead() blockSnapshots := blockReader.(WithSnapshots).Snapshots() diff --git a/eth/stagedsync/stage_execute.go b/eth/stagedsync/stage_execute.go index d66d9ec00..298f1136a 100644 --- a/eth/stagedsync/stage_execute.go +++ b/eth/stagedsync/stage_execute.go @@ -85,7 +85,7 @@ type ExecuteBlockCfg struct { dirs datadir.Dirs historyV3 bool syncCfg ethconfig.Sync - genesis *core.Genesis + genesis *types.Genesis agg *libstate.AggregatorV3 } @@ -105,7 +105,7 @@ func StageExecuteBlocksCfg( dirs datadir.Dirs, blockReader services.FullBlockReader, hd headerDownloader, - genesis *core.Genesis, + genesis *types.Genesis, syncCfg ethconfig.Sync, agg *libstate.AggregatorV3, ) ExecuteBlockCfg { diff --git a/eth/tracers/internal/tracetest/calltrace_test.go b/eth/tracers/internal/tracetest/calltrace_test.go index af249c90d..0d89de1f8 100644 --- a/eth/tracers/internal/tracetest/calltrace_test.go +++ b/eth/tracers/internal/tracetest/calltrace_test.go @@ -29,7 +29,6 @@ import ( "github.com/ledgerwatch/erigon-lib/chain" libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/kv/memdb" - "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/common/hexutil" "github.com/ledgerwatch/erigon/common/math" @@ -82,7 +81,7 @@ type callTrace struct { // callTracerTest defines a single test to check the call tracer against. type callTracerTest struct { - Genesis *core.Genesis `json:"genesis"` + Genesis *types.Genesis `json:"genesis"` Context *callContext `json:"context"` Input string `json:"input"` TracerConfig json.RawMessage `json:"tracerConfig"` @@ -315,12 +314,12 @@ func TestZeroValueToNotExitCall(t *testing.T) { byte(vm.DUP1), byte(vm.PUSH1), 0xff, byte(vm.GAS), // value=0,address=0xff, gas=GAS byte(vm.CALL), } - var alloc = core.GenesisAlloc{ - to: core.GenesisAccount{ + var alloc = types.GenesisAlloc{ + to: types.GenesisAccount{ Nonce: 1, Code: code, }, - origin: core.GenesisAccount{ + origin: types.GenesisAccount{ Nonce: 0, Balance: big.NewInt(500000000000000), }, diff --git a/eth/tracers/internal/tracetest/prestate_test.go b/eth/tracers/internal/tracetest/prestate_test.go index 987aee88d..aed2fa1fe 100644 --- a/eth/tracers/internal/tracetest/prestate_test.go +++ b/eth/tracers/internal/tracetest/prestate_test.go @@ -25,7 +25,6 @@ import ( "testing" "github.com/holiman/uint256" - libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/kv/memdb" @@ -50,7 +49,7 @@ type account struct { // testcase defines a single test to check the stateDiff tracer against. type testcase struct { - Genesis *core.Genesis `json:"genesis"` + Genesis *types.Genesis `json:"genesis"` Context *callContext `json:"context"` Input string `json:"input"` TracerConfig json.RawMessage `json:"tracerConfig"` diff --git a/eth/tracers/tracers_test.go b/eth/tracers/tracers_test.go index 6e4deaa2f..2665bf2d8 100644 --- a/eth/tracers/tracers_test.go +++ b/eth/tracers/tracers_test.go @@ -25,7 +25,6 @@ import ( libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/kv/memdb" - "github.com/ledgerwatch/erigon/common/hexutil" "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/types" @@ -80,16 +79,16 @@ func TestPrestateTracerCreate2(t *testing.T) { GasLimit: uint64(6000000), } context.BaseFee = uint256.NewInt(0) - alloc := core.GenesisAlloc{} + alloc := types.GenesisAlloc{} // The code pushes 'deadbeef' into memory, then the other params, and calls CREATE2, then returns // the address - alloc[libcommon.HexToAddress("0x00000000000000000000000000000000deadbeef")] = core.GenesisAccount{ + alloc[libcommon.HexToAddress("0x00000000000000000000000000000000deadbeef")] = types.GenesisAccount{ Nonce: 1, Code: hexutil.MustDecode("0x63deadbeef60005263cafebabe6004601c6000F560005260206000F3"), Balance: big.NewInt(1), } - alloc[origin] = core.GenesisAccount{ + alloc[origin] = types.GenesisAccount{ Nonce: 1, Code: []byte{}, Balance: big.NewInt(500000000000000), diff --git a/go.mod b/go.mod index 2db845b76..66d1b5c76 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/ledgerwatch/erigon go 1.19 require ( - github.com/ledgerwatch/erigon-lib v0.0.0-20230327103053-23fe5e817bfa + github.com/ledgerwatch/erigon-lib v0.0.0-20230329064727-480d8eea509e github.com/ledgerwatch/erigon-snapshot v1.1.1-0.20230306083105-1391330d62a3 github.com/ledgerwatch/log/v3 v3.7.0 github.com/ledgerwatch/secp256k1 v1.0.0 diff --git a/go.sum b/go.sum index 1589b5090..2337898b7 100644 --- a/go.sum +++ b/go.sum @@ -519,8 +519,8 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v0.0.0-20170224010052-a616ab194758 h1:0D5M2HQSGD3PYPwICLl+/9oulQauOuETfgFvhBDffs0= github.com/leanovate/gopter v0.2.9 h1:fQjYxZaynp97ozCzfOyOuAGOU4aU/z37zf/tOujFk7c= github.com/leanovate/gopter v0.2.9/go.mod h1:U2L/78B+KVFIx2VmW6onHJQzXtFb+p5y3y2Sh+Jxxv8= -github.com/ledgerwatch/erigon-lib v0.0.0-20230327103053-23fe5e817bfa h1:2d7REYLaoY5tqhdP4qH6P7QNl7SbNO7JjTEUMq5x7s4= -github.com/ledgerwatch/erigon-lib v0.0.0-20230327103053-23fe5e817bfa/go.mod h1:JCt4IGL5ZAS1XGTFgSs2RSOxiTw3XX5PrkKjwhiI8Mo= +github.com/ledgerwatch/erigon-lib v0.0.0-20230329064727-480d8eea509e h1:wa/IlxQU1jS4hYRaW1UvqeMgRgntStWD/mwMNZlS8Sg= +github.com/ledgerwatch/erigon-lib v0.0.0-20230329064727-480d8eea509e/go.mod h1:JCt4IGL5ZAS1XGTFgSs2RSOxiTw3XX5PrkKjwhiI8Mo= github.com/ledgerwatch/erigon-snapshot v1.1.1-0.20230306083105-1391330d62a3 h1:tfzawK1gIIgRjVZeANXOr0Ziu+kqCIBuKMe0TXfl5Aw= github.com/ledgerwatch/erigon-snapshot v1.1.1-0.20230306083105-1391330d62a3/go.mod h1:3AuPxZc85jkehh/HA9h8gabv5MSi3kb/ddtzBsTVJFo= github.com/ledgerwatch/log/v3 v3.7.0 h1:aFPEZdwZx4jzA3+/Pf8wNDN5tCI0cIolq/kfvgcM+og= diff --git a/tests/block_test_util.go b/tests/block_test_util.go index 26951a822..e79e5e231 100644 --- a/tests/block_test_util.go +++ b/tests/block_test_util.go @@ -30,7 +30,6 @@ import ( "github.com/ledgerwatch/erigon-lib/chain" libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/kv" - "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/common/hexutil" "github.com/ledgerwatch/erigon/common/math" @@ -58,8 +57,8 @@ func (bt *BlockTest) UnmarshalJSON(in []byte) error { type btJSON struct { Blocks []btBlock `json:"blocks"` Genesis btHeader `json:"genesisBlockHeader"` - Pre core.GenesisAlloc `json:"pre"` - Post core.GenesisAlloc `json:"postState"` + Pre types.GenesisAlloc `json:"pre"` + Post types.GenesisAlloc `json:"postState"` BestBlock common.UnprefixedHash `json:"lastblockhash"` Network string `json:"network"` SealEngine string `json:"sealEngine"` @@ -149,8 +148,8 @@ func (bt *BlockTest) Run(t *testing.T, _ bool) error { return bt.validateImportedHeaders(tx, validBlocks) } -func (bt *BlockTest) genesis(config *chain.Config) *core.Genesis { - return &core.Genesis{ +func (bt *BlockTest) genesis(config *chain.Config) *types.Genesis { + return &types.Genesis{ Config: config, Nonce: bt.json.Genesis.Nonce.Uint64(), Timestamp: bt.json.Genesis.Timestamp, diff --git a/tests/state_test_util.go b/tests/state_test_util.go index 7a9ed0304..8ea699aab 100644 --- a/tests/state_test_util.go +++ b/tests/state_test_util.go @@ -63,7 +63,7 @@ func (t *StateTest) UnmarshalJSON(in []byte) error { type stJSON struct { Env stEnv `json:"env"` - Pre core.GenesisAlloc `json:"pre"` + Pre types.GenesisAlloc `json:"pre"` Tx stTransactionMarshaling `json:"transaction"` Out hexutil.Bytes `json:"out"` Post map[string][]stPostState `json:"post"` @@ -178,7 +178,7 @@ func (t *StateTest) RunNoVerify(tx kv.RwTx, subtest StateSubtest, vmconfig vm.Co return nil, libcommon.Hash{}, UnsupportedForkError{subtest.Fork} } vmconfig.ExtraEips = eips - block, _, err := t.genesis(config).ToBlock("") + block, _, err := core.GenesisToBlock(t.genesis(config), "") if err != nil { return nil, libcommon.Hash{}, UnsupportedForkError{subtest.Fork} } @@ -295,7 +295,7 @@ func (t *StateTest) RunNoVerify(tx kv.RwTx, subtest StateSubtest, vmconfig vm.Co return statedb, root, nil } -func MakePreState(rules *chain.Rules, tx kv.RwTx, accounts core.GenesisAlloc, blockNr uint64) (*state.IntraBlockState, error) { +func MakePreState(rules *chain.Rules, tx kv.RwTx, accounts types.GenesisAlloc, blockNr uint64) (*state.IntraBlockState, error) { r := state.NewPlainStateReader(tx) statedb := state.New(r) for addr, a := range accounts { @@ -333,8 +333,8 @@ func MakePreState(rules *chain.Rules, tx kv.RwTx, accounts core.GenesisAlloc, bl return statedb, nil } -func (t *StateTest) genesis(config *chain.Config) *core.Genesis { - return &core.Genesis{ +func (t *StateTest) genesis(config *chain.Config) *types.Genesis { + return &types.Genesis{ Config: config, Coinbase: t.json.Env.Coinbase, Difficulty: t.json.Env.Difficulty, diff --git a/tests/statedb_chain_test.go b/tests/statedb_chain_test.go index a10e348a9..2c84bc4b8 100644 --- a/tests/statedb_chain_test.go +++ b/tests/statedb_chain_test.go @@ -43,7 +43,7 @@ func TestSelfDestructReceive(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), @@ -52,7 +52,7 @@ func TestSelfDestructReceive(t *testing.T) { TangerineWhistleBlock: new(big.Int), SpuriousDragonBlock: new(big.Int), }, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, }, } diff --git a/tests/statedb_insert_chain_transaction_test.go b/tests/statedb_insert_chain_transaction_test.go index e50d28bd8..235b1a0ac 100644 --- a/tests/statedb_insert_chain_transaction_test.go +++ b/tests/statedb_insert_chain_transaction_test.go @@ -686,7 +686,7 @@ type initialData struct { keys []*ecdsa.PrivateKey addresses []libcommon.Address transactOpts []*bind.TransactOpts - genesisSpec *core.Genesis + genesisSpec *types.Genesis } func getGenesis(funds ...*big.Int) initialData { @@ -702,7 +702,7 @@ func getGenesis(funds ...*big.Int) initialData { addresses := make([]libcommon.Address, 0, len(keys)) transactOpts := make([]*bind.TransactOpts, 0, len(keys)) - allocs := core.GenesisAlloc{} + allocs := types.GenesisAlloc{} for _, key := range keys { addr := crypto.PubkeyToAddress(key.PublicKey) addresses = append(addresses, addr) @@ -712,14 +712,14 @@ func getGenesis(funds ...*big.Int) initialData { } transactOpts = append(transactOpts, to) - allocs[addr] = core.GenesisAccount{Balance: accountFunds} + allocs[addr] = types.GenesisAccount{Balance: accountFunds} } return initialData{ keys: keys, addresses: addresses, transactOpts: transactOpts, - genesisSpec: &core.Genesis{ + genesisSpec: &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), @@ -738,7 +738,7 @@ type tx struct { key *ecdsa.PrivateKey } -func genBlocks(t *testing.T, gspec *core.Genesis, txs map[int]tx) (*stages.MockSentry, *core.ChainPack, error) { +func genBlocks(t *testing.T, gspec *types.Genesis, txs map[int]tx) (*stages.MockSentry, *core.ChainPack, error) { key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") m := stages.MockWithGenesis(t, gspec, key, false) diff --git a/tests/testdata b/tests/testdata index 291118cf6..b6247b008 160000 --- a/tests/testdata +++ b/tests/testdata @@ -1 +1 @@ -Subproject commit 291118cf69f33a4a89f2f61c7bf5fe0e62c9c2f8 +Subproject commit b6247b008e934adf981a9d0d5f903477004f9d7d diff --git a/turbo/app/init.go b/turbo/app/init.go index 9c7f516d5..d444097a5 100644 --- a/turbo/app/init.go +++ b/turbo/app/init.go @@ -4,6 +4,7 @@ import ( "encoding/json" "os" + "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/log/v3" "github.com/urfave/cli/v2" @@ -45,7 +46,7 @@ func initGenesis(ctx *cli.Context) error { } defer file.Close() - genesis := new(core.Genesis) + genesis := new(types.Genesis) if err := json.NewDecoder(file).Decode(genesis); err != nil { utils.Fatalf("invalid genesis file: %v", err) } diff --git a/turbo/cli/flags.go b/turbo/cli/flags.go index 09acebc0f..1db38c217 100644 --- a/turbo/cli/flags.go +++ b/turbo/cli/flags.go @@ -2,10 +2,11 @@ package cli import ( "fmt" - "github.com/ledgerwatch/erigon-lib/txpool" "strings" "time" + "github.com/ledgerwatch/erigon-lib/txpool/txpoolcfg" + libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon/rpc/rpccfg" @@ -199,7 +200,7 @@ var ( TxPoolCommitEvery = cli.DurationFlag{ Name: "txpool.commit.every", Usage: "How often transactions should be committed to the storage", - Value: txpool.DefaultConfig.CommitEvery, + Value: txpoolcfg.DefaultConfig.CommitEvery, } ) diff --git a/turbo/stages/blockchain_test.go b/turbo/stages/blockchain_test.go index e349fd9f4..e95aefa51 100644 --- a/turbo/stages/blockchain_test.go +++ b/turbo/stages/blockchain_test.go @@ -392,10 +392,10 @@ func TestChainTxReorgs(t *testing.T) { addr1 = crypto.PubkeyToAddress(key1.PublicKey) addr2 = crypto.PubkeyToAddress(key2.PublicKey) addr3 = crypto.PubkeyToAddress(key3.PublicKey) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, GasLimit: 3141592, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ addr1: {Balance: big.NewInt(1000000)}, addr2: {Balance: big.NewInt(1000000)}, addr3: {Balance: big.NewInt(1000000)}, @@ -572,9 +572,9 @@ func TestEIP155Transition(t *testing.T) { address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) deleteAddr = libcommon.Address{1} - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ChainID: big.NewInt(1), TangerineWhistleBlock: big.NewInt(0), SpuriousDragonBlock: big.NewInt(2), HomesteadBlock: new(big.Int)}, - Alloc: core.GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}}, + Alloc: types.GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}}, } ) m := stages.MockWithGenesis(t, gspec, key, false) @@ -695,9 +695,9 @@ func doModesTest(t *testing.T, pm prune.Mode) error { address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) deleteAddr = libcommon.Address{1} - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ChainID: big.NewInt(1), TangerineWhistleBlock: big.NewInt(0), SpuriousDragonBlock: big.NewInt(2), HomesteadBlock: new(big.Int)}, - Alloc: core.GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}}, + Alloc: types.GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}}, } ) m := stages.MockWithGenesisPruneMode(t, gspec, key, pm, false) @@ -889,14 +889,14 @@ func TestEIP161AccountRemoval(t *testing.T) { address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) theAddr = libcommon.Address{1} - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: &chain.Config{ ChainID: big.NewInt(1), HomesteadBlock: new(big.Int), TangerineWhistleBlock: new(big.Int), SpuriousDragonBlock: big.NewInt(2), }, - Alloc: core.GenesisAlloc{address: {Balance: funds}}, + Alloc: types.GenesisAlloc{address: {Balance: funds}}, } ) m := stages.MockWithGenesis(t, gspec, key, false) @@ -970,9 +970,9 @@ func TestDoubleAccountRemoval(t *testing.T) { contract = hexutil.MustDecode("0x60606040526040516102eb3803806102eb8339016040526060805160600190602001505b33600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff02191690830217905550806001600050908051906020019082805482825590600052602060002090601f01602090048101928215609c579182015b82811115609b578251826000505591602001919060010190607f565b5b50905060c3919060a7565b8082111560bf576000818150600090555060010160a7565b5090565b50505b50610215806100d66000396000f30060606040526000357c01000000000000000000000000000000000000000000000000000000009004806341c0e1b51461004f578063adbd84651461005c578063cfae32171461007d5761004d565b005b61005a6004506100f6565b005b610067600450610208565b6040518082815260200191505060405180910390f35b61008860045061018a565b60405180806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600302600f01f150905090810190601f1680156100e85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018757600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b5b565b60206040519081016040528060008152602001506001600050805480601f016020809104026020016040519081016040528092919081815260200182805480156101f957820191906000526020600020905b8154815290600101906020018083116101dc57829003601f168201915b50505050509050610205565b90565b6000439050610212565b90560000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000d5468697320697320437972757300000000000000000000000000000000000000") input = hexutil.MustDecode("0xadbd8465") kill = hexutil.MustDecode("0x41c0e1b5") - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{bankAddress: {Balance: bankFunds}}, + Alloc: types.GenesisAlloc{bankAddress: {Balance: bankFunds}}, } ) m := stages.MockWithGenesis(t, gspec, bankKey, false) @@ -1231,9 +1231,9 @@ func TestDeleteCreateRevert(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, // The address 0xAAAAA selfdestructs if called aa: { @@ -1347,9 +1347,9 @@ func TestDeleteRecreateSlots(t *testing.T) { aa := crypto.CreateAddress2(bb, [32]byte{}, initHash[:]) t.Logf("Destination address: %x\n", aa) - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, // The address 0xAAAAA selfdestructs if called aa: { @@ -1462,9 +1462,9 @@ func TestCVE2020_26265(t *testing.T) { byte(vm.RETURN), } // Code for CALLER ) - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, // The address 0xAAAAA selfdestructs if called aa: { @@ -1536,9 +1536,9 @@ func TestDeleteRecreateAccount(t *testing.T) { aaStorage[libcommon.HexToHash("01")] = libcommon.HexToHash("01") aaStorage[libcommon.HexToHash("02")] = libcommon.HexToHash("02") - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, // The address 0xAAAAA selfdestructs if called aa: { @@ -1657,9 +1657,9 @@ func TestDeleteRecreateSlotsAcrossManyBlocks(t *testing.T) { initHash := crypto.Keccak256Hash(initCode) aa := crypto.CreateAddress2(bb, [32]byte{}, initHash[:]) t.Logf("Destination address: %x\n", aa) - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, // The address 0xAAAAA selfdestructs if called aa: { @@ -1852,9 +1852,9 @@ func TestInitThenFailCreateContract(t *testing.T) { aa := crypto.CreateAddress2(bb, [32]byte{}, initHash[:]) t.Logf("Destination address: %x\n", aa) - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, // The address aa has some funds aa: {Balance: big.NewInt(100000)}, @@ -1924,9 +1924,9 @@ func TestEIP2718Transition(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, // The address 0xAAAA sloads 0x00 and 0x01 aa: { @@ -2017,9 +2017,9 @@ func TestEIP1559Transition(t *testing.T) { addr1 = crypto.PubkeyToAddress(key1.PublicKey) addr2 = crypto.PubkeyToAddress(key2.PublicKey) funds = new(uint256.Int).Mul(u256.Num1, new(uint256.Int).SetUint64(params.Ether)) - gspec = &core.Genesis{ + gspec = &types.Genesis{ Config: params.GoerliChainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ addr1: {Balance: funds.ToBig()}, addr2: {Balance: funds.ToBig()}, // The address 0xAAAA sloads 0x00 and 0x01 diff --git a/turbo/stages/chain_makers_test.go b/turbo/stages/chain_makers_test.go index 986588002..19c0d2e2f 100644 --- a/turbo/stages/chain_makers_test.go +++ b/turbo/stages/chain_makers_test.go @@ -23,7 +23,6 @@ import ( "github.com/holiman/uint256" "github.com/ledgerwatch/erigon-lib/chain" - "github.com/ledgerwatch/erigon/turbo/stages" "github.com/ledgerwatch/log/v3" @@ -52,9 +51,9 @@ func TestGenerateChain(t *testing.T) { log.Root().SetHandler(log.DiscardHandler()) // Ensure that key1 has some funds in the genesis block. - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: &chain.Config{HomesteadBlock: new(big.Int), ChainID: big.NewInt(1)}, - Alloc: core.GenesisAlloc{addr1: {Balance: big.NewInt(1000000)}}, + Alloc: types.GenesisAlloc{addr1: {Balance: big.NewInt(1000000)}}, } m := stages.MockWithGenesis(t, gspec, key1, false) diff --git a/turbo/stages/genesis_test.go b/turbo/stages/genesis_test.go index 3519c132f..273968689 100644 --- a/turbo/stages/genesis_test.go +++ b/turbo/stages/genesis_test.go @@ -27,7 +27,6 @@ import ( libcommon "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon-lib/kv/memdb" - "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/rawdb" "github.com/ledgerwatch/erigon/core/types" @@ -39,9 +38,9 @@ import ( func TestSetupGenesis(t *testing.T) { var ( customghash = libcommon.HexToHash("0x89c99d90b79719238d2645c7642f2c9295246e80775b38cfd162b696817fbd50") - customg = core.Genesis{ + customg = types.Genesis{ Config: &chain.Config{ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(3)}, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ {1}: {Balance: big.NewInt(1), Storage: map[libcommon.Hash]libcommon.Hash{{1}: {1}}}, }, } @@ -59,9 +58,9 @@ func TestSetupGenesis(t *testing.T) { { name: "genesis without ChainConfig", fn: func(db kv.RwDB) (*chain.Config, *types.Block, error) { - return core.CommitGenesisBlock(db, new(core.Genesis), tmpdir) + return core.CommitGenesisBlock(db, new(types.Genesis), tmpdir) }, - wantErr: core.ErrGenesisNoConfig, + wantErr: types.ErrGenesisNoConfig, wantConfig: params.AllProtocolChanges, }, { @@ -83,7 +82,7 @@ func TestSetupGenesis(t *testing.T) { { name: "custom block in DB, genesis == nil", fn: func(db kv.RwDB) (*chain.Config, *types.Block, error) { - customg.MustCommit(db, tmpdir) + core.MustCommitGenesis(&customg, db, tmpdir) return core.CommitGenesisBlock(db, nil, tmpdir) }, wantHash: customghash, @@ -92,17 +91,17 @@ func TestSetupGenesis(t *testing.T) { { name: "custom block in DB, genesis == sepolia", fn: func(db kv.RwDB) (*chain.Config, *types.Block, error) { - customg.MustCommit(db, tmpdir) + core.MustCommitGenesis(&customg, db, tmpdir) return core.CommitGenesisBlock(db, core.SepoliaGenesisBlock(), tmpdir) }, - wantErr: &core.GenesisMismatchError{Stored: customghash, New: params.SepoliaGenesisHash}, + wantErr: &types.GenesisMismatchError{Stored: customghash, New: params.SepoliaGenesisHash}, wantHash: params.SepoliaGenesisHash, wantConfig: params.SepoliaChainConfig, }, { name: "compatible config in DB", fn: func(db kv.RwDB) (*chain.Config, *types.Block, error) { - oldcustomg.MustCommit(db, tmpdir) + core.MustCommitGenesis(&oldcustomg, db, tmpdir) return core.CommitGenesisBlock(db, &customg, tmpdir) }, wantHash: customghash, diff --git a/turbo/stages/headerdownload/header_algo_test.go b/turbo/stages/headerdownload/header_algo_test.go index 8b168bbd7..55cc29e30 100644 --- a/turbo/stages/headerdownload/header_algo_test.go +++ b/turbo/stages/headerdownload/header_algo_test.go @@ -23,9 +23,9 @@ func TestInserter1(t *testing.T) { key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address := crypto.PubkeyToAddress(key.PublicKey) chainConfig := params.AllProtocolChanges - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: chainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, }, } diff --git a/turbo/stages/mock_sentry.go b/turbo/stages/mock_sentry.go index 6a980bbd4..b5bc5f53d 100644 --- a/turbo/stages/mock_sentry.go +++ b/turbo/stages/mock_sentry.go @@ -27,6 +27,7 @@ import ( "github.com/ledgerwatch/erigon-lib/kv/remotedbserver" libstate "github.com/ledgerwatch/erigon-lib/state" "github.com/ledgerwatch/erigon-lib/txpool" + "github.com/ledgerwatch/erigon-lib/txpool/txpoolcfg" types2 "github.com/ledgerwatch/erigon-lib/types" "github.com/ledgerwatch/log/v3" "google.golang.org/protobuf/types/known/emptypb" @@ -71,7 +72,7 @@ type MockSentry struct { DB kv.RwDB Dirs datadir.Dirs Engine consensus.Engine - gspec *core.Genesis + gspec *types.Genesis ChainConfig *chain.Config Sync *stagedsync.Sync MiningSync *stagedsync.Sync @@ -202,20 +203,20 @@ func (ms *MockSentry) NodeInfo(context.Context, *emptypb.Empty) (*ptypes.NodeInf return nil, nil } -func MockWithGenesis(t *testing.T, gspec *core.Genesis, key *ecdsa.PrivateKey, withPosDownloader bool) *MockSentry { +func MockWithGenesis(t *testing.T, gspec *types.Genesis, key *ecdsa.PrivateKey, withPosDownloader bool) *MockSentry { return MockWithGenesisPruneMode(t, gspec, key, prune.DefaultMode, withPosDownloader) } -func MockWithGenesisEngine(t *testing.T, gspec *core.Genesis, engine consensus.Engine, withPosDownloader bool) *MockSentry { +func MockWithGenesisEngine(t *testing.T, gspec *types.Genesis, engine consensus.Engine, withPosDownloader bool) *MockSentry { key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") return MockWithEverything(t, gspec, key, prune.DefaultMode, engine, false, withPosDownloader) } -func MockWithGenesisPruneMode(t *testing.T, gspec *core.Genesis, key *ecdsa.PrivateKey, prune prune.Mode, withPosDownloader bool) *MockSentry { +func MockWithGenesisPruneMode(t *testing.T, gspec *types.Genesis, key *ecdsa.PrivateKey, prune prune.Mode, withPosDownloader bool) *MockSentry { return MockWithEverything(t, gspec, key, prune, ethash.NewFaker(), false, withPosDownloader) } -func MockWithEverything(t *testing.T, gspec *core.Genesis, key *ecdsa.PrivateKey, prune prune.Mode, engine consensus.Engine, withTxPool bool, withPosDownloader bool) *MockSentry { +func MockWithEverything(t *testing.T, gspec *types.Genesis, key *ecdsa.PrivateKey, prune prune.Mode, engine consensus.Engine, withTxPool bool, withPosDownloader bool) *MockSentry { var tmpdir string if t != nil { tmpdir = t.TempDir() @@ -305,7 +306,7 @@ func MockWithEverything(t *testing.T, gspec *core.Genesis, key *ecdsa.PrivateKey blockPropagator := func(Ctx context.Context, header *types.Header, body *types.RawBody, td *big.Int) {} if !cfg.DeprecatedTxPool.Disable { - poolCfg := txpool.DefaultConfig + poolCfg := txpoolcfg.DefaultConfig newTxs := make(chan types2.Announcements, 1024) if t != nil { t.Cleanup(func() { @@ -519,9 +520,9 @@ func Mock(t *testing.T) *MockSentry { key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address := crypto.PubkeyToAddress(key.PublicKey) chainConfig := params.TestChainConfig - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: chainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, }, } @@ -533,9 +534,9 @@ func MockWithTxPool(t *testing.T) *MockSentry { key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address := crypto.PubkeyToAddress(key.PublicKey) chainConfig := params.TestChainConfig - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: chainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, }, } @@ -549,9 +550,9 @@ func MockWithZeroTTD(t *testing.T, withPosDownloader bool) *MockSentry { address := crypto.PubkeyToAddress(key.PublicKey) chainConfig := params.AllProtocolChanges chainConfig.TerminalTotalDifficulty = libcommon.Big0 - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: chainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, }, } @@ -565,9 +566,9 @@ func MockWithZeroTTDGnosis(t *testing.T, withPosDownloader bool) *MockSentry { chainConfig := params.TestChainAuraConfig chainConfig.TerminalTotalDifficulty = libcommon.Big0 chainConfig.TerminalTotalDifficultyPassed = true - gspec := &core.Genesis{ + gspec := &types.Genesis{ Config: chainConfig, - Alloc: core.GenesisAlloc{ + Alloc: types.GenesisAlloc{ address: {Balance: funds}, }, }