diff --git a/core/bench_test.go b/core/bench_test.go index 3b914af726a2..652c14df406a 100644 --- a/core/bench_test.go +++ b/core/bench_test.go @@ -158,15 +158,13 @@ func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) { } defer db.Close() } - // Generate a chain of b.N blocks using the supplied block // generator function. gspec := &Genesis{ Alloc: types.GenesisAlloc{benchRootAddr: {Balance: benchRootFunds}}, Config: params.TestChainConfig, } - genesis := gspec.MustCommit(db) - chain, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, b.N, gen) + _, chain, _ := GenerateChainWithGenesis(gspec, ethash.NewFaker(), b.N, gen) // Time the insertion of the new chain. // State and blocks are stored in the same DB. diff --git a/core/block_validator_test.go b/core/block_validator_test.go index b53f60152059..ac335ed7a75d 100644 --- a/core/block_validator_test.go +++ b/core/block_validator_test.go @@ -33,17 +33,15 @@ import ( func TestHeaderVerification(t *testing.T) { // Create a simple chain to verify var ( - testdb = rawdb.NewMemoryDatabase() - gspec = &Genesis{Config: params.TestChainConfig} - genesis = gspec.MustCommit(testdb) - blocks, _ = GenerateChain(gspec.Config, genesis, ethash.NewFaker(), testdb, 8, nil) + gspec = &Genesis{Config: params.TestChainConfig} + _, blocks, _ = GenerateChainWithGenesis(gspec, ethash.NewFaker(), 8, nil) ) headers := make([]*types.Header, len(blocks)) for i, block := range blocks { headers[i] = block.Header() } // Run the header checker for blocks one-by-one, checking for both valid and invalid nonces - chain, err := NewBlockChain(testdb, nil, gspec, ethash.NewFaker(), vm.Config{}) + chain, err := NewBlockChain(rawdb.NewMemoryDatabase(), nil, gspec, ethash.NewFaker(), vm.Config{}) defer chain.Stop() if err != nil { t.Fatal(err) diff --git a/core/blockchain.go b/core/blockchain.go index bf8e1aa49324..6c7440477394 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -101,7 +101,7 @@ const ( receiptsCacheLimit = 32 maxFutureBlocks = 256 maxTimeFutureBlocks = 30 - triesInMemory = 128 + TriesInMemory = 128 // BlockChainVersion ensures that an incompatible database forces a resync from scratch. // @@ -900,7 +900,7 @@ func (bc *BlockChain) saveData() { lendingTriedb = lendingService.GetStateCache().TrieDB() } } - for _, offset := range []uint64{0, 1, triesInMemory - 1} { + for _, offset := range []uint64{0, 1, TriesInMemory - 1} { if number := bc.CurrentBlock().Number.Uint64(); number > offset { recent := bc.GetBlockByNumber(number - offset) @@ -1319,9 +1319,9 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types. if lendingService != nil { lendingService.GetTriegc().Push(lendingRoot, -int64(block.NumberU64())) } - if current := block.NumberU64(); current > triesInMemory { + if current := block.NumberU64(); current > TriesInMemory { // Find the next state trie we need to commit - chosen := current - triesInMemory + chosen := current - TriesInMemory // Only write to disk if we exceeded our memory allowance *and* also have at // least a given number of tries gapped. // @@ -1338,7 +1338,7 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types. if nodes > limit || imgs > 4*1024*1024 { bc.triedb.Cap(limit - ethdb.IdealBatchSize) } - if bc.gcproc > bc.cacheConfig.TrieTimeLimit || chosen > lastWrite+triesInMemory { + if bc.gcproc > bc.cacheConfig.TrieTimeLimit || chosen > lastWrite+TriesInMemory { // If the header is missing (canonical chain behind), we're reorging a low // diff sidechain. Suspend committing until this operation is completed. header := bc.GetHeaderByNumber(chosen) @@ -1347,15 +1347,15 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types. } else { // If we're exceeding limits but haven't reached a large enough memory gap, // warn the user that the system is becoming unstable. - if chosen < lastWrite+triesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit { - log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/triesInMemory) + if chosen < lastWrite+TriesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit { + log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/TriesInMemory) } // Flush an entire trie and restart the counters bc.triedb.Commit(header.Root, true) lastWrite = chosen bc.gcproc = 0 if tradingTrieDb != nil && lendingTrieDb != nil { - b := bc.GetBlock(header.Hash(), current-triesInMemory) + b := bc.GetBlock(header.Hash(), current-TriesInMemory) author, _ := bc.Engine().Author(b.Header()) oldTradingRoot, _ := tradingService.GetTradingStateRoot(b, author) oldLendingRoot, _ := lendingService.GetLendingStateRoot(b, author) diff --git a/core/blockchain_test.go b/core/blockchain_test.go index c8b742f19133..fa1c0ef67044 100644 --- a/core/blockchain_test.go +++ b/core/blockchain_test.go @@ -18,7 +18,6 @@ package core import ( "errors" - "fmt" "math/big" "math/rand" "sync" @@ -42,39 +41,36 @@ import ( // chain. Depending on the full flag, it creates either a full block chain or a // header only chain. The database and genesis specification for block generation // are also returned in case more test blocks are needed later. -func newCanonical(engine consensus.Engine, n int, full bool) (ethdb.Database, *BlockChain, error) { +func newCanonical(engine consensus.Engine, n int, full bool) (ethdb.Database, *Genesis, *BlockChain, error) { var ( - db = rawdb.NewMemoryDatabase() - gspec = &Genesis{ + genesis = &Genesis{ BaseFee: big.NewInt(params.InitialBaseFee), Config: params.AllEthashProtocolChanges, } - genesis = gspec.MustCommit(db) ) - // Initialize a fresh chain with only a genesis block - blockchain, _ := NewBlockChain(db, nil, gspec, engine, vm.Config{}) + blockchain, _ := NewBlockChain(rawdb.NewMemoryDatabase(), nil, genesis, engine, vm.Config{}) // Create and inject the requested chain if n == 0 { - return db, blockchain, nil + return rawdb.NewMemoryDatabase(), genesis, blockchain, nil } if full { // Full block-chain requested - blocks := makeBlockChain(genesis, n, engine, db, canonicalSeed) + genDb, blocks := makeBlockChainWithGenesis(genesis, n, engine, canonicalSeed) _, err := blockchain.InsertChain(blocks) - return db, blockchain, err + return genDb, genesis, blockchain, err } // Header-only chain requested - headers := makeHeaderChain(genesis.Header(), n, engine, db, canonicalSeed) + genDb, headers := makeHeaderChainWithGenesis(genesis, n, engine, canonicalSeed) _, err := blockchain.InsertHeaderChain(headers, 1) - return db, blockchain, err + return genDb, genesis, blockchain, err } // Test fork of length N starting from block i func testFork(t *testing.T, blockchain *BlockChain, i, n int, full bool, comparator func(td1, td2 *big.Int)) { - // Copy old chain up to #i into a new db - db, blockchain2, err := newCanonical(ethash.NewFaker(), i, full) + // Copy old chain up to #i into a new genDb + genDb, _, blockchain2, err := newCanonical(ethash.NewFaker(), i, full) if err != nil { t.Fatal("could not make new canonical in testFork", err) } @@ -98,12 +94,12 @@ func testFork(t *testing.T, blockchain *BlockChain, i, n int, full bool, compara headerChainB []*types.Header ) if full { - blockChainB = makeBlockChain(blockchain2.GetBlockByHash(blockchain2.CurrentBlock().Hash()), n, ethash.NewFaker(), db, forkSeed) + blockChainB = makeBlockChain(blockchain2.chainConfig, blockchain2.GetBlockByHash(blockchain2.CurrentBlock().Hash()), n, ethash.NewFaker(), genDb, forkSeed) if _, err := blockchain2.InsertChain(blockChainB); err != nil { t.Fatalf("failed to insert forking chain: %v", err) } } else { - headerChainB = makeHeaderChain(blockchain2.CurrentHeader(), n, ethash.NewFaker(), db, forkSeed) + headerChainB = makeHeaderChain(blockchain2.chainConfig, blockchain2.CurrentHeader(), n, ethash.NewFaker(), genDb, forkSeed) if _, err := blockchain2.InsertHeaderChain(headerChainB, 1); err != nil { t.Fatalf("failed to insert forking chain: %v", err) } @@ -128,13 +124,6 @@ func testFork(t *testing.T, blockchain *BlockChain, i, n int, full bool, compara comparator(tdPre, tdPost) } -func printChain(bc *BlockChain) { - for i := bc.CurrentBlock().Number.Uint64(); i > 0; i-- { - b := bc.GetBlockByNumber(i) - fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty()) - } -} - // testBlockChainImport tries to process a chain of blocks, writing them into // the database if successful. func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error { @@ -190,22 +179,14 @@ func testHeaderChainImport(chain []*types.Header, blockchain *BlockChain) error return nil } -func insertChain(done chan bool, blockchain *BlockChain, chain types.Blocks, t *testing.T) { - _, err := blockchain.InsertChain(chain) - if err != nil { - t.Fatal(err) - } - done <- true -} - func TestLastBlock(t *testing.T) { - _, blockchain, err := newCanonical(ethash.NewFaker(), 0, true) + genDb, _, blockchain, err := newCanonical(ethash.NewFaker(), 0, true) if err != nil { t.Fatalf("failed to create pristine chain: %v", err) } defer blockchain.Stop() - blocks := makeBlockChain(blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), 1, ethash.NewFullFaker(), blockchain.db, 0) + blocks := makeBlockChain(blockchain.chainConfig, blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), 1, ethash.NewFullFaker(), genDb, 0) if _, err := blockchain.InsertChain(blocks); err != nil { t.Fatalf("Failed to insert block: %v", err) } @@ -223,7 +204,7 @@ func testExtendCanonical(t *testing.T, full bool) { length := 5 // Make first chain starting from genesis - _, processor, err := newCanonical(ethash.NewFaker(), length, full) + _, _, processor, err := newCanonical(ethash.NewFaker(), length, full) if err != nil { t.Fatalf("failed to make new canonical chain: %v", err) } @@ -251,7 +232,7 @@ func testShorterFork(t *testing.T, full bool) { length := 10 // Make first chain starting from genesis - _, processor, err := newCanonical(ethash.NewFaker(), length, full) + _, _, processor, err := newCanonical(ethash.NewFaker(), length, full) if err != nil { t.Fatalf("failed to make new canonical chain: %v", err) } @@ -281,7 +262,7 @@ func testLongerFork(t *testing.T, full bool) { length := 10 // Make first chain starting from genesis - _, processor, err := newCanonical(ethash.NewFaker(), length, full) + _, _, processor, err := newCanonical(ethash.NewFaker(), length, full) if err != nil { t.Fatalf("failed to make new canonical chain: %v", err) } @@ -311,7 +292,7 @@ func testEqualFork(t *testing.T, full bool) { length := 10 // Make first chain starting from genesis - _, processor, err := newCanonical(ethash.NewFaker(), length, full) + _, _, processor, err := newCanonical(ethash.NewFaker(), length, full) if err != nil { t.Fatalf("failed to make new canonical chain: %v", err) } @@ -338,7 +319,7 @@ func TestBrokenBlockChain(t *testing.T) { testBrokenChain(t, true) } func testBrokenChain(t *testing.T, full bool) { // Make chain starting from genesis - db, blockchain, err := newCanonical(ethash.NewFaker(), 10, full) + genDb, _, blockchain, err := newCanonical(ethash.NewFaker(), 10, full) if err != nil { t.Fatalf("failed to make new canonical chain: %v", err) } @@ -346,12 +327,12 @@ func testBrokenChain(t *testing.T, full bool) { // Create a forked chain, and try to insert with a missing link if full { - chain := makeBlockChain(blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), 5, ethash.NewFaker(), db, forkSeed)[1:] + chain := makeBlockChain(blockchain.chainConfig, blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), 5, ethash.NewFaker(), genDb, forkSeed)[1:] if err := testBlockChainImport(chain, blockchain); err == nil { t.Errorf("broken block chain not reported") } } else { - chain := makeHeaderChain(blockchain.CurrentHeader(), 5, ethash.NewFaker(), db, forkSeed)[1:] + chain := makeHeaderChain(blockchain.chainConfig, blockchain.CurrentHeader(), 5, ethash.NewFaker(), genDb, forkSeed)[1:] if err := testHeaderChainImport(chain, blockchain); err == nil { t.Errorf("broken header chain not reported") } @@ -385,7 +366,7 @@ func testReorgShort(t *testing.T, full bool) { diff[i] = -9 } if full { - testReorg(t, easy, diff, 12451840, full) + testReorg(t, easy, diff, 12615120, full) } else { testReorg(t, easy, diff, 12615120, full) } @@ -393,17 +374,17 @@ func testReorgShort(t *testing.T, full bool) { func testReorg(t *testing.T, first, second []int64, td int64, full bool) { // Create a pristine chain and database - db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full) + genDb, _, blockchain, err := newCanonical(ethash.NewFaker(), 0, full) if err != nil { t.Fatalf("failed to create pristine chain: %v", err) } defer blockchain.Stop() // Insert an easy and a difficult chain afterwards - easyBlocks, _ := GenerateChain(params.TestChainConfig, blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), ethash.NewFaker(), db, len(first), func(i int, b *BlockGen) { + easyBlocks, _ := GenerateChain(blockchain.chainConfig, blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), ethash.NewFaker(), genDb, len(first), func(i int, b *BlockGen) { b.OffsetTime(first[i]) }) - diffBlocks, _ := GenerateChain(params.TestChainConfig, blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), ethash.NewFaker(), db, len(second), func(i int, b *BlockGen) { + diffBlocks, _ := GenerateChain(blockchain.chainConfig, blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), ethash.NewFaker(), genDb, len(second), func(i int, b *BlockGen) { b.OffsetTime(second[i]) }) if full { @@ -445,6 +426,19 @@ func testReorg(t *testing.T, first, second []int64, td int64, full bool) { } } } + // Make sure the chain total difficulty is the correct one + want := new(big.Int).Add(blockchain.genesisBlock.Difficulty(), big.NewInt(td)) + if full { + cur := blockchain.CurrentBlock() + if have := blockchain.GetTd(cur.Hash(), cur.Number.Uint64()); have.Cmp(want) != 0 { + t.Errorf("total difficulty mismatch: have %v, want %v", have, want) + } + } else { + cur := blockchain.CurrentHeader() + if have := blockchain.GetTd(cur.Hash(), cur.Number.Uint64()); have.Cmp(want) != 0 { + t.Errorf("total difficulty mismatch: have %v, want %v", have, want) + } + } } // Tests that the insertion functions detect banned hashes. @@ -453,7 +447,7 @@ func TestBadBlockHashes(t *testing.T) { testBadHashes(t, true) } func testBadHashes(t *testing.T, full bool) { // Create a pristine chain and database - db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full) + genDb, _, blockchain, err := newCanonical(ethash.NewFaker(), 0, full) if err != nil { t.Fatalf("failed to create pristine chain: %v", err) } @@ -461,14 +455,14 @@ func testBadHashes(t *testing.T, full bool) { // Create a chain, ban a hash and try to import if full { - blocks := makeBlockChain(blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), 3, ethash.NewFaker(), db, 10) + blocks := makeBlockChain(blockchain.chainConfig, blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), 3, ethash.NewFaker(), genDb, 10) BadHashes[blocks[2].Header().Hash()] = true defer func() { delete(BadHashes, blocks[2].Header().Hash()) }() _, err = blockchain.InsertChain(blocks) } else { - headers := makeHeaderChain(blockchain.CurrentHeader(), 3, ethash.NewFaker(), db, 10) + headers := makeHeaderChain(blockchain.chainConfig, blockchain.CurrentHeader(), 3, ethash.NewFaker(), genDb, 10) BadHashes[headers[2].Hash()] = true defer func() { delete(BadHashes, headers[2].Hash()) }() @@ -487,13 +481,13 @@ func TestReorgBadBlockHashes(t *testing.T) { testReorgBadHashes(t, true) } func testReorgBadHashes(t *testing.T, full bool) { // Create a pristine chain and database - db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full) + genDb, gspec, blockchain, err := newCanonical(ethash.NewFaker(), 0, full) if err != nil { t.Fatalf("failed to create pristine chain: %v", err) } // Create a chain, import and ban afterwards - headers := makeHeaderChain(blockchain.CurrentHeader(), 4, ethash.NewFaker(), db, 10) - blocks := makeBlockChain(blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), 4, ethash.NewFaker(), db, 10) + headers := makeHeaderChain(blockchain.chainConfig, blockchain.CurrentHeader(), 4, ethash.NewFaker(), genDb, 10) + blocks := makeBlockChain(blockchain.chainConfig, blockchain.GetBlockByHash(blockchain.CurrentBlock().Hash()), 4, ethash.NewFaker(), genDb, 10) if full { if _, err = blockchain.InsertChain(blocks); err != nil { @@ -517,10 +511,6 @@ func testReorgBadHashes(t *testing.T, full bool) { blockchain.Stop() // Create a new BlockChain and check that it rolled back the state. - gspec := &Genesis{ - BaseFee: big.NewInt(params.InitialBaseFee), - Config: params.AllEthashProtocolChanges, - } ncm, err := NewBlockChain(blockchain.db, nil, gspec, ethash.NewFaker(), vm.Config{}) if err != nil { t.Fatalf("failed to create new chain manager: %v", err) @@ -547,7 +537,7 @@ func TestBlocksInsertNonceError(t *testing.T) { testInsertNonceError(t, true) } func testInsertNonceError(t *testing.T, full bool) { for i := 1; i < 25 && !t.Failed(); i++ { // Create a pristine chain and database - db, blockchain, err := newCanonical(ethash.NewFaker(), 0, full) + genDb, _, blockchain, err := newCanonical(ethash.NewFaker(), 0, full) if err != nil { t.Fatalf("failed to create pristine chain: %v", err) } @@ -559,7 +549,7 @@ func testInsertNonceError(t *testing.T, full bool) { failRes int failNum uint64 ) - headers := makeHeaderChain(blockchain.CurrentHeader(), i, ethash.NewFaker(), db, 0) + headers := makeHeaderChain(blockchain.chainConfig, blockchain.CurrentHeader(), i, ethash.NewFaker(), genDb, 0) failAt = rand.Int() % len(headers) failNum = headers[failAt].Number.Uint64() @@ -591,19 +581,17 @@ func testInsertNonceError(t *testing.T, full bool) { func TestFastVsFullChains(t *testing.T) { // Configure and generate a sample block chain var ( - gendb = rawdb.NewMemoryDatabase() key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) - funds = big.NewInt(1000000000000000) + funds = big.NewInt(1000000000000000000) gspec = &Genesis{ Alloc: types.GenesisAlloc{address: {Balance: funds}}, BaseFee: big.NewInt(params.InitialBaseFee), Config: params.TestChainConfig, } - genesis = gspec.MustCommit(gendb) - signer = types.LatestSigner(gspec.Config) + signer = types.LatestSigner(gspec.Config) ) - blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, 1024, func(i int, block *BlockGen) { + _, blocks, receipts := GenerateChainWithGenesis(gspec, ethash.NewFaker(), 1024, func(i int, block *BlockGen) { block.SetCoinbase(common.Address{0x00}) // If the block number is multiple of 3, send a few bonus transactions to the miner @@ -623,7 +611,6 @@ func TestFastVsFullChains(t *testing.T) { }) // Import the chain as an archive node for the comparison baseline archiveDb := rawdb.NewMemoryDatabase() - gspec.MustCommit(archiveDb) archive, _ := NewBlockChain(archiveDb, nil, gspec, ethash.NewFaker(), vm.Config{}) defer archive.Stop() @@ -632,7 +619,6 @@ func TestFastVsFullChains(t *testing.T) { } // Fast import the chain as a non-archive node to test fastDb := rawdb.NewMemoryDatabase() - gspec.MustCommit(fastDb) fast, _ := NewBlockChain(fastDb, nil, gspec, ethash.NewFaker(), vm.Config{}) defer fast.Stop() @@ -680,7 +666,6 @@ func TestFastVsFullChains(t *testing.T) { func TestLightVsFastVsFullChainHeads(t *testing.T) { // Configure and generate a sample block chain var ( - gendb = rawdb.NewMemoryDatabase() key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000000000) @@ -689,10 +674,9 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) { BaseFee: big.NewInt(params.InitialBaseFee), Config: params.TestChainConfig, } - genesis = gspec.MustCommit(gendb) ) height := uint64(1024) - blocks, receipts := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), gendb, int(height), nil) + _, blocks, receipts := GenerateChainWithGenesis(gspec, ethash.NewFaker(), int(height), nil) // Configure a subchain to roll back remove := []common.Hash{} @@ -713,7 +697,6 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) { } // Import the chain as an archive node and ensure all pointers are updated archiveDb := rawdb.NewMemoryDatabase() - gspec.MustCommit(archiveDb) archive, _ := NewBlockChain(archiveDb, nil, gspec, ethash.NewFaker(), vm.Config{}) if n, err := archive.InsertChain(blocks); err != nil { @@ -727,7 +710,6 @@ func TestLightVsFastVsFullChainHeads(t *testing.T) { // Import the chain as a non-archive node and ensure all pointers are updated fastDb := rawdb.NewMemoryDatabase() - gspec.MustCommit(fastDb) fast, _ := NewBlockChain(fastDb, nil, gspec, ethash.NewFaker(), vm.Config{}) defer fast.Stop() @@ -769,7 +751,6 @@ func TestChainTxReorgs(t *testing.T) { addr1 = crypto.PubkeyToAddress(key1.PublicKey) addr2 = crypto.PubkeyToAddress(key2.PublicKey) addr3 = crypto.PubkeyToAddress(key3.PublicKey) - db = rawdb.NewMemoryDatabase() gspec = &Genesis{ GasLimit: 3141592, Alloc: types.GenesisAlloc{ @@ -779,8 +760,7 @@ func TestChainTxReorgs(t *testing.T) { }, Config: params.TestChainConfig, } - genesis = gspec.MustCommit(db) - signer = types.LatestSigner(gspec.Config) + signer = types.LatestSigner(gspec.Config) ) // Create two transactions shared between the chains: @@ -800,7 +780,7 @@ func TestChainTxReorgs(t *testing.T) { // - futureAdd: transaction added after the reorg has already finished var pastAdd, freshAdd, futureAdd *types.Transaction - chain, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) { + _, chain, _ := GenerateChainWithGenesis(gspec, ethash.NewFaker(), 3, func(i int, gen *BlockGen) { switch i { case 0: pastDrop, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr2, big.NewInt(1000), params.TxGas, gen.header.BaseFee, nil), signer, key2) @@ -818,6 +798,7 @@ func TestChainTxReorgs(t *testing.T) { } }) // Import the chain. This runs all block validation rules. + db := rawdb.NewMemoryDatabase() blockchain, _ := NewBlockChain(db, nil, gspec, ethash.NewFaker(), vm.Config{}) if i, err := blockchain.InsertChain(chain); err != nil { t.Fatalf("failed to insert original chain[%d]: %v", i, err) @@ -825,7 +806,7 @@ func TestChainTxReorgs(t *testing.T) { defer blockchain.Stop() // overwrite the old chain - chain, _ = GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 5, func(i int, gen *BlockGen) { + _, chain, _ = GenerateChainWithGenesis(gspec, ethash.NewFaker(), 5, func(i int, gen *BlockGen) { switch i { case 0: pastAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, big.NewInt(1000), params.TxGas, gen.header.BaseFee, nil), signer, key3) @@ -880,23 +861,22 @@ func TestLogReorgs(t *testing.T) { var ( key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") addr1 = crypto.PubkeyToAddress(key1.PublicKey) - db = rawdb.NewMemoryDatabase() + // this code generates a log code = common.Hex2Bytes("60606040525b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405180905060405180910390a15b600a8060416000396000f360606040526008565b00") gspec = &Genesis{ - Alloc: types.GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000000)}}, + Alloc: types.GenesisAlloc{addr1: {Balance: big.NewInt(100000000000000000)}}, Config: params.TestChainConfig, } - genesis = gspec.MustCommit(db) - signer = types.LatestSigner(gspec.Config) + signer = types.LatestSigner(gspec.Config) ) - blockchain, _ := NewBlockChain(db, nil, gspec, ethash.NewFaker(), vm.Config{}) + blockchain, _ := NewBlockChain(rawdb.NewMemoryDatabase(), nil, gspec, ethash.NewFaker(), vm.Config{}) defer blockchain.Stop() rmLogsCh := make(chan RemovedLogsEvent) blockchain.SubscribeRemovedLogsEvent(rmLogsCh) - chain, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 2, func(i int, gen *BlockGen) { + _, chain, _ := GenerateChainWithGenesis(gspec, ethash.NewFaker(), 2, func(i int, gen *BlockGen) { if i == 1 { tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, gen.header.BaseFee, code), signer, key1) if err != nil { @@ -909,7 +889,7 @@ func TestLogReorgs(t *testing.T) { t.Fatalf("failed to insert chain: %v", err) } - chain, _ = GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {}) + _, chain, _ = GenerateChainWithGenesis(gspec, ethash.NewFaker(), 3, func(i int, gen *BlockGen) {}) if _, err := blockchain.InsertChain(chain); err != nil { t.Fatalf("failed to insert forked chain: %v", err) } @@ -925,98 +905,15 @@ func TestLogReorgs(t *testing.T) { } } -//func TestReorgSideEvent(t *testing.T) { -// var ( -// db, _ = rawdb.NewMemoryDatabase() -// key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") -// addr1 = crypto.PubkeyToAddress(key1.PublicKey) -// gspec = &Genesis{ -// Config: params.TestChainConfig, -// Alloc: GenesisAlloc{addr1: {Balance: big.NewInt(10000000000000000)}}, -// } -// genesis = gspec.MustCommit(db) -// signer = types.LatestSigner(gspec.Config) -// ) -// -// blockchain, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}) -// defer blockchain.Stop() -// -// chain, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, gen *BlockGen) {}) -// if _, err := blockchain.InsertChain(chain); err != nil { -// t.Fatalf("failed to insert chain: %v", err) -// } -// -// replacementBlocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 4, func(i int, gen *BlockGen) { -// tx, err := types.SignTx(types.NewContractCreation(gen.TxNonce(addr1), new(big.Int), 1000000, gen.header.BaseFee, nil), signer, key1) -// if i == 2 { -// gen.OffsetTime(-9) -// } -// if err != nil { -// t.Fatalf("failed to create tx: %v", err) -// } -// gen.AddTx(tx) -// }) -// chainSideCh := make(chan ChainSideEvent, 64) -// blockchain.SubscribeChainSideEvent(chainSideCh) -// if _, err := blockchain.InsertChain(replacementBlocks); err != nil { -// t.Fatalf("failed to insert chain: %v", err) -// } -// -// // first two block of the secondary chain are for a brief moment considered -// // side chains because up to that point the first one is considered the -// // heavier chain. -// expectedSideHashes := map[common.Hash]bool{ -// replacementBlocks[0].Hash(): true, -// replacementBlocks[1].Hash(): true, -// chain[0].Hash(): true, -// chain[1].Hash(): true, -// chain[2].Hash(): true, -// } -// -// i := 0 -// -// const timeoutDura = 10 * time.Second -// timeout := time.NewTimer(timeoutDura) -//done: -// for { -// select { -// case ev := <-chainSideCh: -// block := ev.Block -// if _, ok := expectedSideHashes[block.Hash()]; !ok { -// t.Errorf("%d: didn't expect %x to be in side chain", i, block.Hash()) -// } -// i++ -// -// if i == len(expectedSideHashes) { -// timeout.Stop() -// -// break done -// } -// timeout.Reset(timeoutDura) -// -// case <-timeout.C: -// t.Fatal("Timeout. Possibly not all blocks were triggered for sideevent") -// } -// } -// -// // make sure no more events are fired -// select { -// case e := <-chainSideCh: -// t.Errorf("unexpected event fired: %v", e) -// case <-time.After(250 * time.Millisecond): -// } -// -//} - // Tests if the canonical block can be fetched from the database during chain insertion. func TestCanonicalBlockRetrieval(t *testing.T) { - _, blockchain, err := newCanonical(ethash.NewFaker(), 0, true) + _, gspec, blockchain, err := newCanonical(ethash.NewFaker(), 0, true) if err != nil { t.Fatalf("failed to create pristine chain: %v", err) } defer blockchain.Stop() - chain, _ := GenerateChain(blockchain.chainConfig, blockchain.genesisBlock, ethash.NewFaker(), blockchain.db, 10, func(i int, gen *BlockGen) {}) + _, chain, _ := GenerateChainWithGenesis(gspec, ethash.NewFaker(), 10, func(i int, gen *BlockGen) {}) var pend sync.WaitGroup pend.Add(len(chain)) @@ -1058,22 +955,21 @@ func TestCanonicalBlockRetrieval(t *testing.T) { func TestEIP155Transition(t *testing.T) { // Configure and generate a sample block chain var ( - db = rawdb.NewMemoryDatabase() key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) deleteAddr = common.Address{1} gspec = &Genesis{ - Config: ¶ms.ChainConfig{ChainID: big.NewInt(1), EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)}, - Alloc: types.GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}}, + Config: ¶ms.ChainConfig{ + ChainID: big.NewInt(1), + EIP150Block: big.NewInt(0), + EIP155Block: big.NewInt(2), + HomesteadBlock: new(big.Int), + }, + Alloc: types.GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}}, } - genesis = gspec.MustCommit(db) ) - - blockchain, _ := NewBlockChain(db, nil, gspec, ethash.NewFaker(), vm.Config{}) - defer blockchain.Stop() - - blocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 4, func(i int, block *BlockGen) { + genDb, blocks, _ := GenerateChainWithGenesis(gspec, ethash.NewFaker(), 4, func(i int, block *BlockGen) { var ( tx *types.Transaction err error @@ -1115,6 +1011,9 @@ func TestEIP155Transition(t *testing.T) { } }) + blockchain, _ := NewBlockChain(rawdb.NewMemoryDatabase(), nil, gspec, ethash.NewFaker(), vm.Config{}) + defer blockchain.Stop() + if _, err := blockchain.InsertChain(blocks); err != nil { t.Fatal(err) } @@ -1135,8 +1034,13 @@ func TestEIP155Transition(t *testing.T) { } // generate an invalid chain id transaction - config := ¶ms.ChainConfig{ChainID: big.NewInt(2), EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(2), HomesteadBlock: new(big.Int)} - blocks, _ = GenerateChain(config, blocks[len(blocks)-1], ethash.NewFaker(), db, 4, func(i int, block *BlockGen) { + config := ¶ms.ChainConfig{ + ChainID: big.NewInt(2), + EIP150Block: big.NewInt(0), + EIP155Block: big.NewInt(2), + HomesteadBlock: new(big.Int), + } + blocks, _ = GenerateChain(config, blocks[len(blocks)-1], ethash.NewFaker(), genDb, 4, func(i int, block *BlockGen) { var ( tx *types.Transaction err error @@ -1161,7 +1065,6 @@ func TestEIP155Transition(t *testing.T) { func TestEIP161AccountRemoval(t *testing.T) { // Configure and generate a sample block chain var ( - db = rawdb.NewMemoryDatabase() key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) funds = big.NewInt(1000000000) @@ -1175,12 +1078,8 @@ func TestEIP161AccountRemoval(t *testing.T) { }, Alloc: types.GenesisAlloc{address: {Balance: funds}}, } - genesis = gspec.MustCommit(db) ) - blockchain, _ := NewBlockChain(db, nil, gspec, ethash.NewFaker(), vm.Config{}) - defer blockchain.Stop() - - blocks, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 3, func(i int, block *BlockGen) { + _, blocks, _ := GenerateChainWithGenesis(gspec, ethash.NewFaker(), 3, func(i int, block *BlockGen) { var ( tx *types.Transaction err error @@ -1200,6 +1099,9 @@ func TestEIP161AccountRemoval(t *testing.T) { block.AddTx(tx) }) // account must exist pre eip 161 + blockchain, _ := NewBlockChain(rawdb.NewMemoryDatabase(), nil, gspec, ethash.NewFaker(), vm.Config{}) + defer blockchain.Stop() + if _, err := blockchain.InsertChain(types.Blocks{blocks[0]}); err != nil { t.Fatal(err) } @@ -1232,31 +1134,25 @@ func TestEIP161AccountRemoval(t *testing.T) { func TestBlockchainHeaderchainReorgConsistency(t *testing.T) { // Generate a canonical chain to act as the main dataset engine := ethash.NewFaker() - - db := rawdb.NewMemoryDatabase() - gspec := &Genesis{ + genesis := &Genesis{ BaseFee: big.NewInt(params.InitialBaseFee), Config: params.TestChainConfig, } - genesis := gspec.MustCommit(db) - blocks, _ := GenerateChain(gspec.Config, genesis, engine, db, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) }) + genDb, blocks, _ := GenerateChainWithGenesis(genesis, engine, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) }) // Generate a bunch of fork blocks, each side forking from the canonical chain forks := make([]*types.Block, len(blocks)) for i := 0; i < len(forks); i++ { - parent := genesis + parent := genesis.ToBlock() if i > 0 { parent = blocks[i-1] } - fork, _ := GenerateChain(gspec.Config, parent, engine, db, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) }) + fork, _ := GenerateChain(genesis.Config, parent, engine, genDb, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) }) forks[i] = fork[0] } // Import the canonical and fork chain side by side, verifying the current block // and current header consistency - diskdb := rawdb.NewMemoryDatabase() - gspec.MustCommit(diskdb) - - chain, err := NewBlockChain(diskdb, nil, gspec, engine, vm.Config{}) + chain, err := NewBlockChain(rawdb.NewMemoryDatabase(), nil, genesis, engine, vm.Config{}) if err != nil { t.Fatalf("failed to create tester chain: %v", err) } @@ -1281,33 +1177,29 @@ func TestBlockchainHeaderchainReorgConsistency(t *testing.T) { func TestTrieForkGC(t *testing.T) { // Generate a canonical chain to act as the main dataset engine := ethash.NewFaker() - - db := rawdb.NewMemoryDatabase() - gspec := &Genesis{ + genesis := &Genesis{ BaseFee: big.NewInt(params.InitialBaseFee), Config: params.TestChainConfig, } - genesis := gspec.MustCommit(db) - blocks, _ := GenerateChain(gspec.Config, genesis, engine, db, 2*triesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) }) + genDb, blocks, _ := GenerateChainWithGenesis(genesis, engine, 2*TriesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) }) // Generate a bunch of fork blocks, each side forking from the canonical chain forks := make([]*types.Block, len(blocks)) for i := 0; i < len(forks); i++ { - parent := genesis + parent := genesis.ToBlock() if i > 0 { parent = blocks[i-1] } - fork, _ := GenerateChain(gspec.Config, parent, engine, db, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) }) + fork, _ := GenerateChain(genesis.Config, parent, engine, genDb, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) }) forks[i] = fork[0] } // Import the canonical and fork chain side by side, forcing the trie cache to cache both - diskdb := rawdb.NewMemoryDatabase() - gspec.MustCommit(diskdb) - - chain, err := NewBlockChain(diskdb, nil, gspec, engine, vm.Config{}) + chain, err := NewBlockChain(rawdb.NewMemoryDatabase(), nil, genesis, engine, vm.Config{}) if err != nil { t.Fatalf("failed to create tester chain: %v", err) } + defer chain.Stop() + for i := 0; i < len(blocks); i++ { if _, err := chain.InsertChain(blocks[i : i+1]); err != nil { t.Fatalf("block %d: failed to insert into chain: %v", i, err) @@ -1317,7 +1209,7 @@ func TestTrieForkGC(t *testing.T) { } } // Dereference all the recent tries and ensure no past trie is left in - for i := 0; i < triesInMemory; i++ { + for i := 0; i < TriesInMemory; i++ { chain.stateCache.TrieDB().Dereference(blocks[len(blocks)-1-i].Root()) chain.stateCache.TrieDB().Dereference(forks[len(blocks)-1-i].Root()) } @@ -1331,26 +1223,21 @@ func TestTrieForkGC(t *testing.T) { func TestLargeReorgTrieGC(t *testing.T) { // Generate the original common chain segment and the two competing forks engine := ethash.NewFaker() - - db := rawdb.NewMemoryDatabase() - gspec := &Genesis{ + genesis := &Genesis{ BaseFee: big.NewInt(params.InitialBaseFee), Config: params.TestChainConfig, } - genesis := gspec.MustCommit(db) - - shared, _ := GenerateChain(gspec.Config, genesis, engine, db, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) }) - original, _ := GenerateChain(gspec.Config, shared[len(shared)-1], engine, db, 2*triesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) }) - competitor, _ := GenerateChain(gspec.Config, shared[len(shared)-1], engine, db, 2*triesInMemory+1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{3}) }) + genDb, shared, _ := GenerateChainWithGenesis(genesis, engine, 64, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) }) + original, _ := GenerateChain(genesis.Config, shared[len(shared)-1], engine, genDb, 2*TriesInMemory, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{2}) }) + competitor, _ := GenerateChain(genesis.Config, shared[len(shared)-1], engine, genDb, 2*TriesInMemory+1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{3}) }) // Import the shared chain and the original canonical one - diskdb := rawdb.NewMemoryDatabase() - gspec.MustCommit(diskdb) - - chain, err := NewBlockChain(diskdb, nil, gspec, engine, vm.Config{}) + chain, err := NewBlockChain(rawdb.NewMemoryDatabase(), nil, genesis, engine, vm.Config{}) if err != nil { t.Fatalf("failed to create tester chain: %v", err) } + defer chain.Stop() + if _, err := chain.InsertChain(shared); err != nil { t.Fatalf("failed to insert shared chain: %v", err) } @@ -1376,7 +1263,7 @@ func TestLargeReorgTrieGC(t *testing.T) { if _, err := chain.InsertChain(competitor[len(competitor)-2:]); err != nil { t.Fatalf("failed to finalize competitor chain: %v", err) } - for i, block := range competitor[:len(competitor)-triesInMemory] { + for i, block := range competitor[:len(competitor)-TriesInMemory] { if node, _ := chain.stateCache.TrieDB().Node(block.Root()); node != nil { t.Fatalf("competitor %d: competing chain state missing", i) } @@ -1404,8 +1291,6 @@ func benchmarkLargeNumberOfValueToNonexisting(b *testing.B, numTxs, numBlocks in ) // Generate the original common chain segment and the two competing forks engine := ethash.NewFaker() - db := rawdb.NewMemoryDatabase() - genesis := gspec.MustCommit(db) blockGenerator := func(i int, block *BlockGen) { block.SetCoinbase(common.Address{1}) @@ -1421,15 +1306,12 @@ func benchmarkLargeNumberOfValueToNonexisting(b *testing.B, numTxs, numBlocks in } } - shared, _ := GenerateChain(gspec.Config, genesis, engine, db, numBlocks, blockGenerator) + _, shared, _ := GenerateChainWithGenesis(gspec, engine, numBlocks, blockGenerator) b.StopTimer() b.ResetTimer() for i := 0; i < b.N; i++ { // Import the shared chain and the original canonical one - diskdb := rawdb.NewMemoryDatabase() - gspec.MustCommit(diskdb) - - chain, err := NewBlockChain(diskdb, nil, gspec, engine, vm.Config{}) + chain, err := NewBlockChain(rawdb.NewMemoryDatabase(), nil, gspec, engine, vm.Config{}) if err != nil { b.Fatalf("failed to create tester chain: %v", err) } @@ -1495,18 +1377,16 @@ func BenchmarkBlockChain_1x1000Executions(b *testing.B) { } /* - Collection test for BlocksHashCache - cases - 1. When init new chain - 2. when insertChain - 3. when insertFork - 4. When adding new block by mining - 5. When adding new block by syncing with other nodes - +Collection test for BlocksHashCache +cases + 1. When init new chain + 2. when insertChain + 3. when insertFork + 4. When adding new block by mining + 5. When adding new block by syncing with other nodes */ - func TestBlocksHashCacheUpdate(t *testing.T) { - _, chain, err := newCanonical(ethash.NewFaker(), 0, true) + _, _, chain, err := newCanonical(ethash.NewFaker(), 0, true) if err != nil { t.Fatalf("failed to make new canonical chain: %v", err) } @@ -1522,7 +1402,7 @@ func TestBlocksHashCacheUpdate(t *testing.T) { }) t.Run("Expect BlocksHashCache has 4 cached keys after concat a 4-length-chain", func(t *testing.T) { - concatedChain := makeBlockChain(chain.GetBlockByHash(chain.CurrentBlock().Hash()), 4, ethash.NewFullFaker(), chain.db, 0) + concatedChain := makeBlockChain(chain.chainConfig, chain.GetBlockByHash(chain.CurrentBlock().Hash()), 4, ethash.NewFullFaker(), chain.db, 0) if _, err := chain.InsertChain(concatedChain); err != nil { t.Fatalf("failed to insert shared chain: %v", err) } @@ -1533,7 +1413,7 @@ func TestBlocksHashCacheUpdate(t *testing.T) { }) t.Run("Expect BlocksHashCache caches work for fork case", func(t *testing.T) { - concatedChain := makeBlockChain(chain.GetBlockByNumber(uint64(2)), 3, ethash.NewFullFaker(), chain.db, 3) + concatedChain := makeBlockChain(chain.chainConfig, chain.GetBlockByNumber(uint64(2)), 3, ethash.NewFullFaker(), chain.db, 3) if _, err := chain.InsertChain(concatedChain); err != nil { t.Fatalf("failed to insert forked chain: %v", err) } @@ -1546,7 +1426,7 @@ func TestBlocksHashCacheUpdate(t *testing.T) { t.Run("Expect BlocksHashCache caches when inserting block on syncing", func(t *testing.T) { currentCachedLength := len(chain.blocksHashCache.Keys()) - singleBlockChain := makeBlockChain(chain.GetBlockByHash(chain.CurrentBlock().Hash()), 1, ethash.NewFaker(), chain.db, 0) + singleBlockChain := makeBlockChain(chain.chainConfig, chain.GetBlockByHash(chain.CurrentBlock().Hash()), 1, ethash.NewFaker(), chain.db, 0) chain.insertBlock(singleBlockChain[0]) if len(chain.blocksHashCache.Keys()) != currentCachedLength+1 { @@ -1556,14 +1436,11 @@ func TestBlocksHashCacheUpdate(t *testing.T) { } func TestAreTwoBlocksSamePath(t *testing.T) { - _, chain, err := newCanonical(ethash.NewFaker(), 10, true) + genDb, _, chain, err := newCanonical(ethash.NewFaker(), 10, true) if err != nil { t.Fatalf("failed to make new canonical chain: %v", err) } defer chain.Stop() - if err != nil { - t.Fatalf("failed to create tester chain: %v", err) - } t.Run("Expect return true with two canonical blocks", func(t *testing.T) { if !chain.AreTwoBlockSamePath(chain.CurrentBlock().Hash(), chain.GetBlockByNumber(uint64(2)).Hash()) { @@ -1572,7 +1449,7 @@ func TestAreTwoBlocksSamePath(t *testing.T) { }) t.Run("Expect return fail with canonical-fork paths", func(t *testing.T) { - concatedChain := makeBlockChain(chain.GetBlockByNumber(uint64(2)), 3, ethash.NewFullFaker(), chain.db, 3) + concatedChain := makeBlockChain(chain.chainConfig, chain.GetBlockByNumber(uint64(2)), 3, ethash.NewFullFaker(), genDb, 3) if _, err := chain.InsertChain(concatedChain); err != nil { t.Fatalf("failed to insert forked chain: %v", err) } @@ -1589,18 +1466,14 @@ func TestAreTwoBlocksSamePath(t *testing.T) { // correctly. func TestEIP2718Transition(t *testing.T) { var ( - aa = common.HexToAddress("0x000000000000000000000000000000000000aaaa") - - // Generate a canonical chain to act as the main dataset + aa = common.HexToAddress("0x000000000000000000000000000000000000aaaa") engine = ethash.NewFaker() - db = rawdb.NewMemoryDatabase() // A sender who makes transactions, has some funds key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) - // funds = big.NewInt(math.MaxInt64) - funds = big.NewInt(1000000000000000) - gspec = &Genesis{ + funds = big.NewInt(1000000000000000) + gspec = &Genesis{ Config: ¶ms.ChainConfig{ ChainID: new(big.Int).SetBytes([]byte("eip1559")), HomesteadBlock: big.NewInt(0), @@ -1630,10 +1503,9 @@ func TestEIP2718Transition(t *testing.T) { }, }, } - genesis = gspec.MustCommit(db) ) - - blocks, _ := GenerateChain(gspec.Config, genesis, engine, db, 1, func(i int, b *BlockGen) { + // Generate blocks + _, blocks, _ := GenerateChainWithGenesis(gspec, engine, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) // One transaction to 0xAAAA @@ -1653,13 +1525,12 @@ func TestEIP2718Transition(t *testing.T) { }) // Import the canonical chain - diskdb := rawdb.NewMemoryDatabase() - gspec.MustCommit(diskdb) - - chain, err := NewBlockChain(diskdb, nil, gspec, engine, vm.Config{}) + chain, err := NewBlockChain(rawdb.NewMemoryDatabase(), nil, gspec, engine, vm.Config{}) if err != nil { t.Fatalf("failed to create tester chain: %v", err) } + defer chain.Stop() + if n, err := chain.InsertChain(blocks); err != nil { t.Fatalf("block %d: failed to insert into chain: %v", n, err) } @@ -1682,7 +1553,7 @@ func TestTransientStorageReset(t *testing.T) { key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) destAddress = crypto.CreateAddress(address, 0) - funds = big.NewInt(1000000000000000) + funds = big.NewInt(100000000000000000) vmConfig = vm.Config{ ExtraEips: []int{1153}, // Enable transient storage EIP } @@ -1747,11 +1618,8 @@ func TestTransientStorageReset(t *testing.T) { nonce++ }) - diskdb := rawdb.NewMemoryDatabase() - gspec.MustCommit(diskdb) - // Initialize the blockchain with 1153 enabled. - chain, err := NewBlockChain(diskdb, nil, gspec, engine, vmConfig) + chain, err := NewBlockChain(rawdb.NewMemoryDatabase(), nil, gspec, engine, vmConfig) if err != nil { t.Fatalf("failed to create tester chain: %v", err) } @@ -1821,8 +1689,8 @@ func TestEIP3651(t *testing.T) { } ) - gspec.Config.Eip1559Block = common.Big0 signer := types.LatestSigner(gspec.Config) + gspec.Config.Eip1559Block = common.Big0 _, blocks, _ := GenerateChainWithGenesis(gspec, engine, 1, func(i int, b *BlockGen) { b.SetCoinbase(aa) @@ -1843,10 +1711,7 @@ func TestEIP3651(t *testing.T) { b.AddTx(tx) }) - diskdb := rawdb.NewMemoryDatabase() - gspec.MustCommit(diskdb) - - chain, err := NewBlockChain(diskdb, nil, gspec, engine, vm.Config{}) + chain, err := NewBlockChain(rawdb.NewMemoryDatabase(), nil, gspec, engine, vm.Config{}) if err != nil { t.Fatalf("failed to create tester chain: %v", err) } @@ -1897,7 +1762,6 @@ func TestDeleteCreateRevert(t *testing.T) { bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb") // Generate a canonical chain to act as the main dataset engine = ethash.NewFaker() - db = rawdb.NewMemoryDatabase() // A sender who makes transactions, has some funds key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") @@ -1931,10 +1795,9 @@ func TestDeleteCreateRevert(t *testing.T) { }, Config: params.TestChainConfig, } - genesis = gspec.MustCommit(db) ) - blocks, _ := GenerateChain(gspec.Config, genesis, engine, db, 1, func(i int, b *BlockGen) { + _, blocks, _ := GenerateChainWithGenesis(gspec, engine, 1, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{1}) // One transaction to AAAA tx, _ := types.SignTx(types.NewTransaction(0, aa, @@ -1946,13 +1809,12 @@ func TestDeleteCreateRevert(t *testing.T) { b.AddTx(tx) }) // Import the canonical chain - diskdb := rawdb.NewMemoryDatabase() - gspec.MustCommit(diskdb) - - chain, err := NewBlockChain(diskdb, nil, gspec, engine, vm.Config{}) + chain, err := NewBlockChain(rawdb.NewMemoryDatabase(), nil, gspec, engine, vm.Config{}) if err != nil { t.Fatalf("failed to create tester chain: %v", err) } + defer chain.Stop() + if n, err := chain.InsertChain(blocks); err != nil { t.Fatalf("block %d: failed to insert into chain: %v", n, err) } diff --git a/core/chain_makers.go b/core/chain_makers.go index c0bb4e1c55f3..f9a6cb1a69c8 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -148,6 +148,9 @@ func (b *BlockGen) Number() *big.Int { // BaseFee returns the EIP-1559 base fee of the block being generated. func (b *BlockGen) BaseFee() *big.Int { + if b.header.BaseFee == nil { + return nil + } return new(big.Int).Set(b.header.BaseFee) } @@ -315,8 +318,8 @@ func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.S } // makeHeaderChain creates a deterministic chain of headers rooted at parent. -func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Header { - blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed) +func makeHeaderChain(chainConfig *params.ChainConfig, parent *types.Header, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Header { + blocks := makeBlockChain(chainConfig, types.NewBlockWithHeader(parent), n, engine, db, seed) headers := make([]*types.Header, len(blocks)) for i, block := range blocks { headers[i] = block.Header() @@ -324,14 +327,32 @@ func makeHeaderChain(parent *types.Header, n int, engine consensus.Engine, db et return headers } +// makeHeaderChainWithGenesis creates a deterministic chain of headers from genesis. +func makeHeaderChainWithGenesis(genesis *Genesis, n int, engine consensus.Engine, seed int) (ethdb.Database, []*types.Header) { + db, blocks := makeBlockChainWithGenesis(genesis, n, engine, seed) + headers := make([]*types.Header, len(blocks)) + for i, block := range blocks { + headers[i] = block.Header() + } + return db, headers +} + // makeBlockChain creates a deterministic chain of blocks rooted at parent. -func makeBlockChain(parent *types.Block, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Block { - blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) { +func makeBlockChain(chainConfig *params.ChainConfig, parent *types.Block, n int, engine consensus.Engine, db ethdb.Database, seed int) []*types.Block { + blocks, _ := GenerateChain(chainConfig, parent, engine, db, n, func(i int, b *BlockGen) { b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)}) }) return blocks } +// makeBlockChainWithGenesis creates a deterministic chain of blocks from genesis +func makeBlockChainWithGenesis(genesis *Genesis, n int, engine consensus.Engine, seed int) (ethdb.Database, []*types.Block) { + db, blocks, _ := GenerateChainWithGenesis(genesis, engine, n, func(i int, b *BlockGen) { + b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)}) + }) + return db, blocks +} + type fakeChainReader struct { config *params.ChainConfig engine consensus.Engine diff --git a/core/dao_test.go b/core/dao_test.go index 7498fb635e99..db3fdaa920dc 100644 --- a/core/dao_test.go +++ b/core/dao_test.go @@ -30,40 +30,38 @@ import ( // blocks based on their extradata fields. func TestDAOForkRangeExtradata(t *testing.T) { forkBlock := big.NewInt(32) + chainConfig := *params.TestChainConfig + chainConfig.HomesteadBlock = big.NewInt(0) // Generate a common prefix for both pro-forkers and non-forkers - db := rawdb.NewMemoryDatabase() gspec := &Genesis{ BaseFee: big.NewInt(params.InitialBaseFee), - Config: params.TestChainConfig, + Config: &chainConfig, } - genesis := gspec.MustCommit(db) - prefix, _ := GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, int(forkBlock.Int64()-1), func(i int, gen *BlockGen) {}) + genDb, prefix, _ := GenerateChainWithGenesis(gspec, ethash.NewFaker(), int(forkBlock.Int64()-1), func(i int, gen *BlockGen) {}) // Create the concurrent, conflicting two nodes proDb := rawdb.NewMemoryDatabase() proConf := *params.TestChainConfig + proConf.HomesteadBlock = big.NewInt(0) proConf.DAOForkBlock = forkBlock proConf.DAOForkSupport = true progspec := &Genesis{ BaseFee: big.NewInt(params.InitialBaseFee), Config: &proConf, } - gspec.MustCommit(proDb) - proBc, _ := NewBlockChain(proDb, nil, progspec, ethash.NewFaker(), vm.Config{}) defer proBc.Stop() conDb := rawdb.NewMemoryDatabase() conConf := *params.TestChainConfig + conConf.HomesteadBlock = big.NewInt(0) conConf.DAOForkBlock = forkBlock conConf.DAOForkSupport = false congspec := &Genesis{ BaseFee: big.NewInt(params.InitialBaseFee), Config: &conConf, } - gspec.MustCommit(conDb) - conBc, _ := NewBlockChain(conDb, nil, congspec, ethash.NewFaker(), vm.Config{}) defer conBc.Stop() @@ -76,9 +74,7 @@ func TestDAOForkRangeExtradata(t *testing.T) { // Try to expand both pro-fork and non-fork chains iteratively with other camp's blocks for i := int64(0); i < params.DAOForkExtraRange.Int64(); i++ { // Create a pro-fork block, and try to feed into the no-fork chain - db = rawdb.NewMemoryDatabase() - congspec.MustCommit(db) - bc, _ := NewBlockChain(db, nil, congspec, ethash.NewFaker(), vm.Config{}) + bc, _ := NewBlockChain(rawdb.NewMemoryDatabase(), nil, congspec, ethash.NewFaker(), vm.Config{}) blocks := conBc.GetBlocksFromHash(conBc.CurrentBlock().Hash(), int(conBc.CurrentBlock().Number.Uint64())) for j := 0; j < len(blocks)/2; j++ { @@ -91,19 +87,17 @@ func TestDAOForkRangeExtradata(t *testing.T) { t.Fatalf("failed to commit contra-fork head for expansion: %v", err) } bc.Stop() - blocks, _ = GenerateChain(&proConf, conBc.GetBlockByHash(conBc.CurrentBlock().Hash()), ethash.NewFaker(), db, 1, func(i int, gen *BlockGen) {}) + blocks, _ = GenerateChain(&proConf, conBc.GetBlockByHash(conBc.CurrentBlock().Hash()), ethash.NewFaker(), genDb, 1, func(i int, gen *BlockGen) {}) if _, err := conBc.InsertChain(blocks); err == nil { t.Fatalf("contra-fork chain accepted pro-fork block: %v", blocks[0]) } // Create a proper no-fork block for the contra-forker - blocks, _ = GenerateChain(&conConf, conBc.GetBlockByHash(conBc.CurrentBlock().Hash()), ethash.NewFaker(), db, 1, func(i int, gen *BlockGen) {}) + blocks, _ = GenerateChain(&conConf, conBc.GetBlockByHash(conBc.CurrentBlock().Hash()), ethash.NewFaker(), genDb, 1, func(i int, gen *BlockGen) {}) if _, err := conBc.InsertChain(blocks); err != nil { t.Fatalf("contra-fork chain didn't accepted no-fork block: %v", err) } // Create a no-fork block, and try to feed into the pro-fork chain - db = rawdb.NewMemoryDatabase() - progspec.MustCommit(db) - bc, _ = NewBlockChain(db, nil, progspec, ethash.NewFaker(), vm.Config{}) + bc, _ = NewBlockChain(rawdb.NewMemoryDatabase(), nil, progspec, ethash.NewFaker(), vm.Config{}) blocks = proBc.GetBlocksFromHash(proBc.CurrentBlock().Hash(), int(proBc.CurrentBlock().Number.Uint64())) for j := 0; j < len(blocks)/2; j++ { @@ -116,20 +110,18 @@ func TestDAOForkRangeExtradata(t *testing.T) { t.Fatalf("failed to commit pro-fork head for expansion: %v", err) } bc.Stop() - blocks, _ = GenerateChain(&conConf, proBc.GetBlockByHash(proBc.CurrentBlock().Hash()), ethash.NewFaker(), db, 1, func(i int, gen *BlockGen) {}) + blocks, _ = GenerateChain(&conConf, proBc.GetBlockByHash(proBc.CurrentBlock().Hash()), ethash.NewFaker(), genDb, 1, func(i int, gen *BlockGen) {}) if _, err := proBc.InsertChain(blocks); err == nil { t.Fatalf("pro-fork chain accepted contra-fork block: %v", blocks[0]) } // Create a proper pro-fork block for the pro-forker - blocks, _ = GenerateChain(&proConf, proBc.GetBlockByHash(proBc.CurrentBlock().Hash()), ethash.NewFaker(), db, 1, func(i int, gen *BlockGen) {}) + blocks, _ = GenerateChain(&proConf, proBc.GetBlockByHash(proBc.CurrentBlock().Hash()), ethash.NewFaker(), genDb, 1, func(i int, gen *BlockGen) {}) if _, err := proBc.InsertChain(blocks); err != nil { t.Fatalf("pro-fork chain didn't accepted pro-fork block: %v", err) } } // Verify that contra-forkers accept pro-fork extra-datas after forking finishes - db = rawdb.NewMemoryDatabase() - congspec.MustCommit(db) - bc, _ := NewBlockChain(db, nil, congspec, ethash.NewFaker(), vm.Config{}) + bc, _ := NewBlockChain(rawdb.NewMemoryDatabase(), nil, congspec, ethash.NewFaker(), vm.Config{}) defer bc.Stop() blocks := conBc.GetBlocksFromHash(conBc.CurrentBlock().Hash(), int(conBc.CurrentBlock().Number.Uint64())) @@ -142,14 +134,12 @@ func TestDAOForkRangeExtradata(t *testing.T) { if err := bc.stateCache.TrieDB().Commit(bc.CurrentHeader().Root, false); err != nil { t.Fatalf("failed to commit contra-fork head for expansion: %v", err) } - blocks, _ = GenerateChain(&proConf, conBc.GetBlockByHash(conBc.CurrentBlock().Hash()), ethash.NewFaker(), db, 1, func(i int, gen *BlockGen) {}) + blocks, _ = GenerateChain(&proConf, conBc.GetBlockByHash(conBc.CurrentBlock().Hash()), ethash.NewFaker(), genDb, 1, func(i int, gen *BlockGen) {}) if _, err := conBc.InsertChain(blocks); err != nil { t.Fatalf("contra-fork chain didn't accept pro-fork block post-fork: %v", err) } // Verify that pro-forkers accept contra-fork extra-datas after forking finishes - db = rawdb.NewMemoryDatabase() - progspec.MustCommit(db) - bc, _ = NewBlockChain(db, nil, progspec, ethash.NewFaker(), vm.Config{}) + bc, _ = NewBlockChain(rawdb.NewMemoryDatabase(), nil, progspec, ethash.NewFaker(), vm.Config{}) defer bc.Stop() blocks = proBc.GetBlocksFromHash(proBc.CurrentBlock().Hash(), int(proBc.CurrentBlock().Number.Uint64())) @@ -162,7 +152,7 @@ func TestDAOForkRangeExtradata(t *testing.T) { if err := bc.stateCache.TrieDB().Commit(bc.CurrentHeader().Root, false); err != nil { t.Fatalf("failed to commit pro-fork head for expansion: %v", err) } - blocks, _ = GenerateChain(&conConf, proBc.GetBlockByHash(proBc.CurrentBlock().Hash()), ethash.NewFaker(), db, 1, func(i int, gen *BlockGen) {}) + blocks, _ = GenerateChain(&conConf, proBc.GetBlockByHash(proBc.CurrentBlock().Hash()), ethash.NewFaker(), genDb, 1, func(i int, gen *BlockGen) {}) if _, err := proBc.InsertChain(blocks); err != nil { t.Fatalf("pro-fork chain didn't accept contra-fork block post-fork: %v", err) } diff --git a/core/state_processor_test.go b/core/state_processor_test.go index 611cf5d663b9..09604b0c4afd 100644 --- a/core/state_processor_test.go +++ b/core/state_processor_test.go @@ -127,10 +127,8 @@ func TestStateProcessorErrors(t *testing.T) { }, }, } - genesis = gspec.MustCommit(db) blockchain, _ = NewBlockChain(db, nil, gspec, ethash.NewFaker(), vm.Config{}) ) - defer blockchain.Stop() num := big.NewInt(1) rules := config.Rules(num) @@ -282,7 +280,7 @@ func TestStateProcessorErrors(t *testing.T) { want: "could not apply tx 0 [0xb49a1f798a865850a62b4deb6a71efb9150e5bf11a46b3f331fec62baa0547b4]: transaction gas limit too high (cap: 16777216, tx: 16777217)", }, } { - block := GenerateBadBlock(t, genesis, ethash.NewFaker(), tt.txs, gspec.Config) + block := GenerateBadBlock(t, gspec.ToBlock(), ethash.NewFaker(), tt.txs, gspec.Config) _, err := blockchain.InsertChain(types.Blocks{block}) if err == nil { t.Fatal("block imported without errors") @@ -316,7 +314,6 @@ func TestStateProcessorErrors(t *testing.T) { }, }, } - genesis = gspec.MustCommit(db) blockchain, _ = NewBlockChain(db, nil, gspec, ethash.NewFaker(), vm.Config{}) ) defer blockchain.Stop() @@ -331,7 +328,7 @@ func TestStateProcessorErrors(t *testing.T) { want: "transaction type not supported", }, } { - block := GenerateBadBlock(t, genesis, ethash.NewFaker(), tt.txs, gspec.Config) + block := GenerateBadBlock(t, gspec.ToBlock(), ethash.NewFaker(), tt.txs, gspec.Config) _, err := blockchain.InsertChain(types.Blocks{block}) if err == nil { t.Fatal("block imported without errors") diff --git a/core/txpool/locals/tx_tracker_test.go b/core/txpool/locals/tx_tracker_test.go index c07f76823a76..41c058592c4f 100644 --- a/core/txpool/locals/tx_tracker_test.go +++ b/core/txpool/locals/tx_tracker_test.go @@ -42,7 +42,7 @@ import ( var ( key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") address = crypto.PubkeyToAddress(key.PublicKey) - funds = big.NewInt(1000000000000000) + funds = big.NewInt(1000000000000000000) gspec = &core.Genesis{ Config: params.TestChainConfig, Alloc: types.GenesisAlloc{ @@ -62,7 +62,11 @@ type testEnv struct { func newTestEnv(t *testing.T, n int, gasTip uint64, journal string) *testEnv { genDb, blocks, _ := core.GenerateChainWithGenesis(gspec, ethash.NewFaker(), n, func(i int, gen *core.BlockGen) { - tx, err := types.SignTx(types.NewTransaction(gen.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, big.NewInt(params.GWei), nil), signer, key) + gasPrice := big.NewInt(params.InitialBaseFee) + if baseFee := gen.BaseFee(); baseFee != nil { + gasPrice = new(big.Int).Set(baseFee) + } + tx, err := types.SignTx(types.NewTransaction(gen.TxNonce(address), common.Address{0x00}, big.NewInt(1000), params.TxGas, gasPrice, nil), signer, key) if err != nil { panic(err) } @@ -105,10 +109,14 @@ func (env *testEnv) makeTxs(n int) []*types.Transaction { head := env.chain.CurrentHeader() state, _ := env.chain.StateAt(head.Root) nonce := state.GetNonce(address) + gasPrice := big.NewInt(params.InitialBaseFee) + if head.BaseFee != nil { + gasPrice = new(big.Int).Set(head.BaseFee) + } var txs []*types.Transaction for i := 0; i < n; i++ { - tx, _ := types.SignTx(types.NewTransaction(nonce+uint64(i), common.Address{0x00}, big.NewInt(1000), params.TxGas, big.NewInt(params.GWei), nil), signer, key) + tx, _ := types.SignTx(types.NewTransaction(nonce+uint64(i), common.Address{0x00}, big.NewInt(1000), params.TxGas, gasPrice, nil), signer, key) txs = append(txs, tx) } return txs diff --git a/eth/downloader/downloader_test.go b/eth/downloader/downloader_test.go index 9fe9bdaf02e6..f4bb837aa900 100644 --- a/eth/downloader/downloader_test.go +++ b/eth/downloader/downloader_test.go @@ -345,7 +345,6 @@ func (dl *downloadTester) handleProposedBlock(header *types.Header) error { // Config retrieves the blockchain's chain configuration. func (dl *downloadTester) Config() *params.ChainConfig { config := *params.TestChainConfig - config.Eip1559Block = big.NewInt(0) return &config } diff --git a/eth/downloader/queue_test.go b/eth/downloader/queue_test.go index 3d0fdd7f01ab..094a48fbac7a 100644 --- a/eth/downloader/queue_test.go +++ b/eth/downloader/queue_test.go @@ -44,7 +44,11 @@ func makeChain(n int, seed byte, parent *types.Block, empty bool) ([]*types.Bloc // Add one tx to every secondblock if !empty && i%2 == 0 { signer := types.MakeSigner(params.TestChainConfig, block.Number()) - tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, nil, nil), signer, testKey) + fee := block.BaseFee() + if fee == nil { + fee = big.NewInt(params.InitialBaseFee) + } + tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, fee, nil), signer, testKey) if err != nil { panic(err) } diff --git a/eth/downloader/testchain_test.go b/eth/downloader/testchain_test.go index c75ead7b0814..0125ef566cee 100644 --- a/eth/downloader/testchain_test.go +++ b/eth/downloader/testchain_test.go @@ -37,7 +37,7 @@ var ( testAddress = crypto.PubkeyToAddress(testKey.PublicKey) testDB = rawdb.NewMemoryDatabase() - testGspec = core.Genesis{ + testGspec = &core.Genesis{ Alloc: types.GenesisAlloc{testAddress: {Balance: big.NewInt(1000000000000000000)}}, BaseFee: big.NewInt(params.InitialBaseFee), Config: params.TestChainConfig, @@ -130,10 +130,7 @@ func (tc *testChain) copy(newlen int) *testChain { // contains a transaction and every 5th an uncle to allow testing correct block // reassembly. func (tc *testChain) generate(n int, seed byte, parent *types.Block, heavy bool) { - chainConfig := *params.TestChainConfig - chainConfig.Eip1559Block = big.NewInt((0)) - - blocks, receipts := core.GenerateChain(&chainConfig, parent, ethash.NewFaker(), testDB, n, func(i int, block *core.BlockGen) { + blocks, receipts := core.GenerateChain(testGspec.Config, parent, ethash.NewFaker(), testDB, n, func(i int, block *core.BlockGen) { block.SetCoinbase(common.Address{seed}) // If a heavy chain is requested, delay blocks to raise difficulty if heavy { @@ -141,7 +138,7 @@ func (tc *testChain) generate(n int, seed byte, parent *types.Block, heavy bool) } // Include transactions to the miner to make blocks more interesting. if parent == tc.genesis && i%22 == 0 { - signer := types.MakeSigner(&chainConfig, block.Number()) + signer := types.MakeSigner(params.TestChainConfig, block.Number()) tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, block.BaseFee(), nil), signer, testKey) if err != nil { panic(err) diff --git a/eth/fetcher/fetcher_test.go b/eth/fetcher/fetcher_test.go index 7c887af98041..a368c254f0c0 100644 --- a/eth/fetcher/fetcher_test.go +++ b/eth/fetcher/fetcher_test.go @@ -41,7 +41,7 @@ var ( testAddress = crypto.PubkeyToAddress(testKey.PublicKey) gspec = core.Genesis{ - Alloc: types.GenesisAlloc{testAddress: {Balance: big.NewInt(1000000000)}}, + Alloc: types.GenesisAlloc{testAddress: {Balance: big.NewInt(1000000000000000000)}}, BaseFee: big.NewInt(params.InitialBaseFee), Config: params.TestChainConfig, } @@ -61,7 +61,11 @@ func makeChain(n int, seed byte, parent *types.Block) ([]common.Hash, map[common // If the block number is multiple of 3, send a bonus transaction to the miner if parent == genesis && i%3 == 0 { signer := types.MakeSigner(params.TestChainConfig, block.Number()) - tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, nil, nil), signer, testKey) + fee := block.BaseFee() + if fee == nil { + fee = big.NewInt(params.InitialBaseFee) + } + tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, fee, nil), signer, testKey) if err != nil { panic(err) } diff --git a/eth/filters/filter_system_test.go b/eth/filters/filter_system_test.go index 374fd9efbcca..843928dac617 100644 --- a/eth/filters/filter_system_test.go +++ b/eth/filters/filter_system_test.go @@ -189,12 +189,11 @@ func TestBlockSubscription(t *testing.T) { db = rawdb.NewMemoryDatabase() backend, sys = newTestFilterSystem(t, db, Config{}) api = NewFilterAPI(sys, false) - gspec = &core.Genesis{ + genesis = &core.Genesis{ BaseFee: big.NewInt(params.InitialBaseFee), Config: params.TestChainConfig, } - genesis = gspec.MustCommit(db) - chain, _ = core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 10, func(i int, gen *core.BlockGen) {}) + _, chain, _ = core.GenerateChainWithGenesis(genesis, ethash.NewFaker(), 10, func(i int, gen *core.BlockGen) {}) chainEvents = []core.ChainEvent{} ) @@ -815,7 +814,11 @@ func TestLightFilterLogs(t *testing.T) { } receipts[i-1].Bloom = types.CreateBloom(types.Receipts{receipts[i-1]}) b.AddUncheckedReceipt(receipts[i-1]) - tx, _ := types.SignTx(types.NewTx(&types.LegacyTx{Nonce: uint64(i - 1), To: &common.Address{}, Value: big.NewInt(1000), Gas: params.TxGas, GasPrice: big.NewInt(2100), Data: nil}), signer, key) + fee := b.BaseFee() + if fee == nil { + fee = big.NewInt(params.InitialBaseFee) + } + tx, _ := types.SignTx(types.NewTx(&types.LegacyTx{Nonce: uint64(i - 1), To: &common.Address{}, Value: big.NewInt(1000), Gas: params.TxGas, GasPrice: fee, Data: nil}), signer, key) b.AddTx(tx) }) for i, block := range blocks { diff --git a/eth/filters/filter_test.go b/eth/filters/filter_test.go index bf296de8baf8..e7ae052dc736 100644 --- a/eth/filters/filter_test.go +++ b/eth/filters/filter_test.go @@ -46,10 +46,8 @@ func makeReceipt(addr common.Address) *types.Receipt { } func BenchmarkFilters(b *testing.B) { - dir := b.TempDir() - var ( - db, _ = rawdb.NewLevelDBDatabase(dir, 0, 0, "", false) + db, _ = rawdb.NewLevelDBDatabase(b.TempDir(), 0, 0, "", false) _, sys = newTestFilterSystem(b, db, Config{}) key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") addr1 = crypto.PubkeyToAddress(key1.PublicKey) @@ -57,18 +55,15 @@ func BenchmarkFilters(b *testing.B) { addr3 = common.BytesToAddress([]byte("ethereum")) addr4 = common.BytesToAddress([]byte("random addresses please")) - gspec = core.Genesis{ + gspec = &core.Genesis{ Alloc: types.GenesisAlloc{addr1: {Balance: big.NewInt(1000000)}}, BaseFee: big.NewInt(params.InitialBaseFee), Config: params.TestChainConfig, } - genesis = gspec.ToBlock() ) defer db.Close() - gspec.MustCommit(db) - - chain, receipts := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 100010, func(i int, gen *core.BlockGen) { + _, chain, receipts := core.GenerateChainWithGenesis(gspec, ethash.NewFaker(), 100010, func(i int, gen *core.BlockGen) { switch i { case 2403: receipt := makeReceipt(addr1) @@ -170,18 +165,20 @@ func TestFilters(t *testing.T) { }, BaseFee: big.NewInt(params.InitialBaseFee), } - genesis = gspec.ToBlock() ) - defer db.Close() - - gspec.MustCommit(db) contractABI, err := abi.JSON(strings.NewReader(abiStr)) if err != nil { t.Fatal(err) } - chain, _ := core.GenerateChain(&config, genesis, ethash.NewFaker(), db, 1000, func(i int, gen *core.BlockGen) { + // Hack: GenerateChainWithGenesis creates a new db. + // Commit the genesis manually and use GenerateChain. + _, err = gspec.Commit(db) + if err != nil { + t.Fatal(err) + } + chain, _ := core.GenerateChain(gspec.Config, gspec.ToBlock(), ethash.NewFaker(), db, 1000, func(i int, gen *core.BlockGen) { switch i { case 1: data, err := contractABI.Pack("log1", hash1.Big()) @@ -245,7 +242,6 @@ func TestFilters(t *testing.T) { gen.AddTx(tx) } }) - bc, err := core.NewBlockChain(db, nil, gspec, ethash.NewFaker(), vm.Config{}) if err != nil { t.Fatal(err) @@ -370,8 +366,11 @@ func TestRangeLimit(t *testing.T) { BaseFee: big.NewInt(params.InitialBaseFee), Config: params.TestChainConfig, } - genesis := gspec.MustCommit(db) - chain, _ := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 10, func(i int, gen *core.BlockGen) {}) + _, err := gspec.Commit(db) + if err != nil { + t.Fatal(err) + } + chain, _ := core.GenerateChain(gspec.Config, gspec.ToBlock(), ethash.NewFaker(), db, 10, func(i int, gen *core.BlockGen) {}) bc, err := core.NewBlockChain(db, nil, gspec, ethash.NewFaker(), vm.Config{}) if err != nil { t.Fatal(err) diff --git a/eth/gasprice/gasprice_test.go b/eth/gasprice/gasprice_test.go index 3f4d2213e60c..8942f473bf7d 100644 --- a/eth/gasprice/gasprice_test.go +++ b/eth/gasprice/gasprice_test.go @@ -121,11 +121,9 @@ func newTestBackend(t *testing.T, eip1559Block *big.Int, pending bool) *testBack signer = types.LatestSigner(gspec.Config) ) engine := ethash.NewFaker() - db := rawdb.NewMemoryDatabase() - genesis := gspec.MustCommit(db) // Generate testing blocks - blocks, _ := core.GenerateChain(gspec.Config, genesis, engine, db, testHead+1, func(i int, b *core.BlockGen) { + _, blocks, _ := core.GenerateChainWithGenesis(gspec, engine, testHead+1, func(i int, b *core.BlockGen) { b.SetCoinbase(common.Address{1}) var txdata types.TxData @@ -152,9 +150,7 @@ func newTestBackend(t *testing.T, eip1559Block *big.Int, pending bool) *testBack b.AddTx(types.MustSignNewTx(key, signer, txdata)) }) // Construct testing chain - diskdb := rawdb.NewMemoryDatabase() - gspec.MustCommit(diskdb) - chain, err := core.NewBlockChain(diskdb, nil, gspec, engine, vm.Config{}) + chain, err := core.NewBlockChain(rawdb.NewMemoryDatabase(), nil, gspec, engine, vm.Config{}) if err != nil { t.Fatalf("Failed to create local chain, %v", err) } diff --git a/eth/handler_test.go b/eth/handler_test.go index 7a7f3be83a86..07437a1cda87 100644 --- a/eth/handler_test.go +++ b/eth/handler_test.go @@ -311,16 +311,20 @@ func testGetNodeData(t *testing.T, protocol int) { signer := types.HomesteadSigner{} // Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_markets_test) generator := func(i int, block *core.BlockGen) { + fee := block.BaseFee() + if fee == nil { + fee = big.NewInt(params.InitialBaseFee) + } switch i { case 0: // In block 1, the test bank sends account #1 some ether. - tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey) + tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, new(big.Int).SetUint64(1_000_000_000_000_000_000), params.TxGas, fee, nil), signer, testBankKey) block.AddTx(tx) case 1: // In block 2, the test bank sends some more ether to account #1. // acc1Addr passes it on to account #2. - tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey) - tx2, _ := types.SignTx(types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key) + tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, new(big.Int).SetUint64(1_000_000_000_000_000_000), params.TxGas, fee, nil), signer, testBankKey) + tx2, _ := types.SignTx(types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, new(big.Int).SetUint64(1_000_000_000_000_000_000), params.TxGas, fee, nil), signer, acc1Key) block.AddTx(tx1) block.AddTx(tx2) case 2: @@ -405,16 +409,20 @@ func testGetReceipt(t *testing.T, protocol int) { signer := types.HomesteadSigner{} // Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_markets_test) generator := func(i int, block *core.BlockGen) { + fee := block.BaseFee() + if fee == nil { + fee = big.NewInt(params.InitialBaseFee) + } switch i { case 0: // In block 1, the test bank sends account #1 some ether. - tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey) + tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, new(big.Int).SetUint64(1_000_000_000_000_000_000), params.TxGas, fee, nil), signer, testBankKey) block.AddTx(tx) case 1: // In block 2, the test bank sends some more ether to account #1. // acc1Addr passes it on to account #2. - tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey) - tx2, _ := types.SignTx(types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key) + tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, new(big.Int).SetUint64(1_000_000_000_000_000_000), params.TxGas, fee, nil), signer, testBankKey) + tx2, _ := types.SignTx(types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, new(big.Int).SetUint64(1_000_000_000_000_000_000), params.TxGas, fee, nil), signer, acc1Key) block.AddTx(tx1) block.AddTx(tx2) case 2: @@ -478,7 +486,6 @@ func testDAOChallenge(t *testing.T, localForked, remoteForked bool, timeout bool DAOForkSupport: localForked, }, } - genesis = gspec.MustCommit(db) blockchain, _ = core.NewBlockChain(db, nil, gspec, pow, vm.Config{}) ) pm, err := NewProtocolManager(gspec.Config, downloader.FullSync, ethconfig.Defaults.NetworkId, evmux, new(testTxPool), pow, blockchain, db) @@ -503,9 +510,13 @@ func testDAOChallenge(t *testing.T, localForked, remoteForked bool, timeout bool } // Create a block to reply to the challenge if no timeout is simulated if !timeout { - blocks, _ := core.GenerateChain(¶ms.ChainConfig{}, genesis, ethash.NewFaker(), db, 1, func(i int, block *core.BlockGen) { + _, blocks, _ := core.GenerateChainWithGenesis(gspec, ethash.NewFaker(), 1, func(i int, block *core.BlockGen) { if remoteForked { block.SetExtra(params.DAOForkBlockExtra) + } else { + // Override the auto-injected DAO extra-data from GenerateChain when + // the local config supports the fork but the remote peer should not. + block.SetExtra([]byte{}) } }) if err := p2p.Send(peer.app, BlockHeadersMsg, []*types.Header{blocks[0].Header()}); err != nil { diff --git a/eth/helper_test.go b/eth/helper_test.go index c98914fc6a63..2106afda1f1e 100644 --- a/eth/helper_test.go +++ b/eth/helper_test.go @@ -59,7 +59,7 @@ func newTestProtocolManager(mode downloader.SyncMode, blocks int, generator func engine = ethash.NewFaker() db = rawdb.NewMemoryDatabase() gspec = &core.Genesis{ - Alloc: types.GenesisAlloc{testBank: {Balance: big.NewInt(1000000)}}, + Alloc: types.GenesisAlloc{testBank: {Balance: new(big.Int).SetUint64(10000000000000000000)}}, Config: params.TestChainConfig, } genesis = gspec.MustCommit(db) diff --git a/eth/tracers/api_test.go b/eth/tracers/api_test.go index 66bbfb10f8f7..8ecd1ff0e400 100644 --- a/eth/tracers/api_test.go +++ b/eth/tracers/api_test.go @@ -73,10 +73,10 @@ func newTestBackend(t *testing.T, n int, gspec *core.Genesis, generator func(i i engine: ethash.NewFaker(), chaindb: rawdb.NewMemoryDatabase(), } + // Generate blocks for testing _, blocks, _ := core.GenerateChainWithGenesis(gspec, backend.engine, n, generator) // Import the canonical chain - gspec.MustCommit(backend.chaindb) cacheConfig := &core.CacheConfig{ TrieCleanLimit: 256, TrieDirtyLimit: 256, @@ -303,9 +303,9 @@ func TestTraceCall(t *testing.T) { t.Parallel() // Initialize test accounts - accounts := newAccounts(3) config := *params.TestChainConfig config.Eip1559Block = big.NewInt(0) + accounts := newAccounts(3) genesis := &core.Genesis{ Config: &config, Alloc: types.GenesisAlloc{ @@ -521,10 +521,8 @@ func TestTraceTransaction(t *testing.T) { // Initialize test accounts accounts := newAccounts(2) - config := *params.TestChainConfig - config.Eip1559Block = big.NewInt(0) genesis := &core.Genesis{ - Config: &config, + Config: params.TestChainConfig, Alloc: types.GenesisAlloc{ accounts[0].addr: {Balance: big.NewInt(9000000000000000000)}, accounts[1].addr: {Balance: big.NewInt(9000000000000000000)}, @@ -577,10 +575,8 @@ func TestTraceBlock(t *testing.T) { // Initialize test accounts accounts := newAccounts(3) - config := *params.TestChainConfig - config.Eip1559Block = big.NewInt(0) genesis := &core.Genesis{ - Config: &config, + Config: params.TestChainConfig, Alloc: types.GenesisAlloc{ accounts[0].addr: {Balance: big.NewInt(9000000000000000000)}, accounts[1].addr: {Balance: big.NewInt(9000000000000000000)}, @@ -665,10 +661,11 @@ func TestTraceBlock(t *testing.T) { func TestTracingWithOverrides(t *testing.T) { t.Parallel() + // Initialize test accounts - accounts := newAccounts(3) config := *params.TestChainConfig config.Eip1559Block = big.NewInt(0) + accounts := newAccounts(3) genesis := &core.Genesis{ Config: &config, Alloc: types.GenesisAlloc{ @@ -871,10 +868,8 @@ func newStates(keys []common.Hash, vals []common.Hash) map[common.Hash]common.Ha func TestTraceChain(t *testing.T) { // Initialize test accounts accounts := newAccounts(3) - config := *params.TestChainConfig - config.Eip1559Block = big.NewInt(0) genesis := &core.Genesis{ - Config: &config, + Config: params.TestChainConfig, Alloc: types.GenesisAlloc{ accounts[0].addr: {Balance: big.NewInt(params.Ether)}, accounts[1].addr: {Balance: big.NewInt(params.Ether)},