Skip to content

Commit

Permalink
all: polish tests
Browse files Browse the repository at this point in the history
  • Loading branch information
rjl493456442 committed Aug 5, 2022
1 parent f67e54c commit 5c09ef9
Show file tree
Hide file tree
Showing 24 changed files with 94 additions and 75 deletions.
2 changes: 1 addition & 1 deletion cmd/devp2p/internal/ethtest/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ func loadChain(chainfile string, genesis string) (*Chain, error) {
if err != nil {
return nil, err
}
gblock := gen.ToBlock(nil)
gblock := gen.ToBlock()

blocks, err := blocksFromFile(chainfile, gblock)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/evm/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func runCmd(ctx *cli.Context) error {
gen := readGenesis(ctx.String(GenesisFlag.Name))
genesisConfig = gen
db := rawdb.NewMemoryDatabase()
genesis := gen.ToBlock(db)
genesis := gen.MustCommit(db)
statedb, _ = state.New(genesis.Root(), state.NewDatabase(db), nil)
chainConfig = gen.Config
} else {
Expand Down
2 changes: 1 addition & 1 deletion cmd/faucet/faucet.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ func newFaucet(genesis *core.Genesis, port int, enodes []*enode.Node, network ui
cfg.SyncMode = downloader.LightSync
cfg.NetworkId = network
cfg.Genesis = genesis
utils.SetDNSDiscoveryDefaults(&cfg, genesis.ToBlock(nil).Hash())
utils.SetDNSDiscoveryDefaults(&cfg, genesis.ToBlock().Hash())

lesBackend, err := les.New(stack, &cfg)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions consensus/clique/snapshot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ func TestClique(t *testing.T) {
}
// Create a pristine blockchain with the genesis injected
db := rawdb.NewMemoryDatabase()
genesis.Commit(db)
genesisBlock := genesis.MustCommit(db)

// Assemble a chain of headers from the cast votes
config := *params.TestChainConfig
Expand All @@ -414,7 +414,7 @@ func TestClique(t *testing.T) {
engine := New(config.Clique, db)
engine.fakeDiff = true

blocks, _ := core.GenerateChain(&config, genesis.ToBlock(db), engine, db, len(tt.votes), func(j int, gen *core.BlockGen) {
blocks, _ := core.GenerateChain(&config, genesisBlock, engine, db, len(tt.votes), func(j int, gen *core.BlockGen) {
// Cast the vote contained in this block
gen.SetCoinbase(accounts.address(tt.votes[j].voted))
if tt.votes[j].auth {
Expand Down
4 changes: 2 additions & 2 deletions core/blockchain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1941,8 +1941,8 @@ func testSideImport(t *testing.T, numCanonBlocksInSidechain, blocksBetweenCommon
Alloc: GenesisAlloc{addr: {Balance: big.NewInt(math.MaxInt64)}},
BaseFee: big.NewInt(params.InitialBaseFee),
}
signer = types.LatestSigner(gspec.Config)
genesis, _ = gspec.Commit(db)
signer = types.LatestSigner(gspec.Config)
genesis = gspec.MustCommit(db)
)
// Generate and import the canonical chain
diskdb := rawdb.NewMemoryDatabase()
Expand Down
29 changes: 15 additions & 14 deletions core/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ func (ga *GenesisAlloc) flush(db ethdb.Database) (common.Hash, error) {
if err != nil {
return common.Hash{}, err
}
// Short circuit if nothing to flush
if len(*ga) == 0 {
return statedb.Commit(false)
}
for addr, account := range *ga {
statedb.AddBalance(addr, account.Balance)
statedb.SetCode(addr, account.Code)
Expand Down Expand Up @@ -273,7 +277,7 @@ func SetupGenesisBlockWithOverride(db ethdb.Database, genesis *Genesis, override
genesis = DefaultGenesisBlock()
}
// Ensure the stored genesis matches with the given one.
hash := genesis.ToBlock(nil).Hash()
hash := genesis.ToBlock().Hash()
if hash != stored {
return genesis.Config, hash, &GenesisMismatchError{stored, hash}
}
Expand All @@ -286,7 +290,7 @@ func SetupGenesisBlockWithOverride(db ethdb.Database, genesis *Genesis, override
}
// Check whether the genesis block is already written.
if genesis != nil {
hash := genesis.ToBlock(nil).Hash()
hash := genesis.ToBlock().Hash()
if hash != stored {
return genesis.Config, hash, &GenesisMismatchError{stored, hash}
}
Expand Down Expand Up @@ -347,9 +351,9 @@ func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
}
}

// ToBlock creates the genesis block and writes state of a genesis specification
// 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(db ethdb.Database) *types.Block {
func (g *Genesis) toBlock(db ethdb.Database) *types.Block {
if db == nil {
db = rawdb.NewMemoryDatabase()
}
Expand Down Expand Up @@ -387,10 +391,15 @@ func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
return types.NewBlock(head, nil, nil, nil, trie.NewStackTrie(nil))
}

// ToBlock returns the genesis block according to genesis specification.
func (g *Genesis) ToBlock() *types.Block {
return g.toBlock(nil)
}

// Commit writes the block and state of a genesis specification to the database.
// The block is committed as the canonical head block.
func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) {
block := g.ToBlock(db)
block := g.toBlock(db)
if block.Number().Sign() != 0 {
return nil, errors.New("can't commit genesis block with number > 0")
}
Expand Down Expand Up @@ -428,15 +437,6 @@ func (g *Genesis) MustCommit(db ethdb.Database) *types.Block {
return block
}

// GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.
func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
g := Genesis{
Alloc: GenesisAlloc{addr: {Balance: balance}},
BaseFee: big.NewInt(params.InitialBaseFee),
}
return g.MustCommit(db)
}

// DefaultGenesisBlock returns the Ethereum main net genesis block.
func DefaultGenesisBlock() *Genesis {
return &Genesis{
Expand Down Expand Up @@ -498,6 +498,7 @@ func DefaultSepoliaGenesisBlock() *Genesis {
}
}

// DefaultKilnGenesisBlock returns the kiln network genesis block.
func DefaultKilnGenesisBlock() *Genesis {
g := new(Genesis)
reader := strings.NewReader(KilnAllocData)
Expand Down
8 changes: 2 additions & 6 deletions core/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ func TestGenesisHashes(t *testing.T) {
t.Errorf("case: %d a), want: %s, got: %s", i, c.want.Hex(), have.Hex())
}
// Test via ToBlock
if have := c.genesis.ToBlock(nil).Hash(); have != c.want {
if have := c.genesis.ToBlock().Hash(); have != c.want {
t.Errorf("case: %d a), want: %s, got: %s", i, c.want.Hex(), have.Hex())
}
}
Expand All @@ -192,11 +192,7 @@ func TestGenesis_Commit(t *testing.T) {
}

db := rawdb.NewMemoryDatabase()
genesisBlock, err := genesis.Commit(db)
if err != nil {
t.Fatal(err)
}

genesisBlock := genesis.MustCommit(db)
if genesis.Difficulty != nil {
t.Fatalf("assumption wrong")
}
Expand Down
2 changes: 1 addition & 1 deletion eth/catalyst/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func generatePreMergeChain(n int) (*core.Genesis, []*types.Block) {
g.AddTx(tx)
testNonce++
}
gblock := genesis.ToBlock(db)
gblock := genesis.MustCommit(db)
engine := ethash.NewFaker()
blocks, _ := core.GenerateChain(config, gblock, engine, db, n, generate)
totalDifficulty := big.NewInt(0)
Expand Down
6 changes: 5 additions & 1 deletion eth/downloader/downloader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,11 @@ func newTesterWithNotification(t *testing.T, success func()) *downloadTester {
t.Cleanup(func() {
db.Close()
})
core.GenesisBlockForTesting(db, testAddress, big.NewInt(1000000000000000))
gspec := core.Genesis{
Alloc: core.GenesisAlloc{testAddress: {Balance: big.NewInt(1000000000000000)}},
BaseFee: big.NewInt(params.InitialBaseFee),
}
gspec.MustCommit(db)

chain, err := core.NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
if err != nil {
Expand Down
14 changes: 4 additions & 10 deletions eth/downloader/queue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,18 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/trie"
)

var (
testdb = rawdb.NewMemoryDatabase()
genesis = core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000000000))
)

// makeChain creates a chain of n blocks starting at and including parent.
// the returned hash chain is ordered head->parent. In addition, every 3rd block
// contains a transaction and every 5th an uncle to allow testing correct block
// reassembly.
func makeChain(n int, seed byte, parent *types.Block, empty bool) ([]*types.Block, []types.Receipts) {
blocks, receipts := core.GenerateChain(params.TestChainConfig, parent, ethash.NewFaker(), testdb, n, func(i int, block *core.BlockGen) {
blocks, receipts := core.GenerateChain(params.TestChainConfig, parent, ethash.NewFaker(), testDB, n, func(i int, block *core.BlockGen) {
block.SetCoinbase(common.Address{seed})
// Add one tx to every secondblock
if !empty && i%2 == 0 {
Expand All @@ -70,10 +64,10 @@ var emptyChain *chainData
func init() {
// Create a chain of blocks to import
targetBlocks := 128
blocks, _ := makeChain(targetBlocks, 0, genesis, false)
blocks, _ := makeChain(targetBlocks, 0, testGenesis, false)
chain = &chainData{blocks, 0}

blocks, _ = makeChain(targetBlocks, 0, genesis, true)
blocks, _ = makeChain(targetBlocks, 0, testGenesis, true)
emptyChain = &chainData{blocks, 0}
}

Expand Down Expand Up @@ -271,7 +265,7 @@ func TestEmptyBlocks(t *testing.T) {
// some more advanced scenarios
func XTestDelivery(t *testing.T) {
// the outside network, holding blocks
blo, rec := makeChain(128, 0, genesis, false)
blo, rec := makeChain(128, 0, testGenesis, false)
world := newNetwork()
world.receipts = rec
world.chain = blo
Expand Down
9 changes: 7 additions & 2 deletions eth/downloader/testchain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,12 @@ var (
testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
testAddress = crypto.PubkeyToAddress(testKey.PublicKey)
testDB = rawdb.NewMemoryDatabase()
testGenesis = core.GenesisBlockForTesting(testDB, testAddress, big.NewInt(1000000000000000))

testGspec = core.Genesis{
Alloc: core.GenesisAlloc{testAddress: {Balance: big.NewInt(1000000000000000)}},
BaseFee: big.NewInt(params.InitialBaseFee),
}
testGenesis = testGspec.MustCommit(testDB)
)

// The common prefix of all test chains:
Expand Down Expand Up @@ -212,7 +217,7 @@ func newTestBlockchain(blocks []*types.Block) *core.BlockChain {
panic("Requested chain generation outside of init")
}
db := rawdb.NewMemoryDatabase()
core.GenesisBlockForTesting(db, testAddress, big.NewInt(1000000000000000))
testGspec.MustCommit(db)

chain, err := core.NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
if err != nil {
Expand Down
12 changes: 8 additions & 4 deletions eth/fetcher/block_fetcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,14 @@ import (
)

var (
testdb = rawdb.NewMemoryDatabase()
testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
testAddress = crypto.PubkeyToAddress(testKey.PublicKey)
genesis = core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000000000))
testdb = rawdb.NewMemoryDatabase()
testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
testAddress = crypto.PubkeyToAddress(testKey.PublicKey)
gspec = core.Genesis{
Alloc: core.GenesisAlloc{testAddress: {Balance: big.NewInt(1000000000000000)}},
BaseFee: big.NewInt(params.InitialBaseFee),
}
genesis = gspec.MustCommit(testdb)
unknownBlock = types.NewBlock(&types.Header{GasLimit: params.GenesisGasLimit, BaseFee: big.NewInt(params.InitialBaseFee)}, nil, nil, nil, trie.NewStackTrie(nil))
)

Expand Down
18 changes: 16 additions & 2 deletions eth/filters/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,17 @@ func BenchmarkFilters(b *testing.B) {
addr2 = common.BytesToAddress([]byte("jeff"))
addr3 = common.BytesToAddress([]byte("ethereum"))
addr4 = common.BytesToAddress([]byte("random addresses please"))

gspec = core.Genesis{
Alloc: core.GenesisAlloc{addr1: {Balance: big.NewInt(1000000)}},
BaseFee: big.NewInt(params.InitialBaseFee),
}
genesis = gspec.ToBlock()
)
defer db.Close()

genesis := core.GenesisBlockForTesting(db, addr1, big.NewInt(1000000))
gspec.MustCommit(db)

chain, receipts := core.GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 100010, func(i int, gen *core.BlockGen) {
switch i {
case 2403:
Expand Down Expand Up @@ -105,10 +112,17 @@ func TestFilters(t *testing.T) {
hash2 = common.BytesToHash([]byte("topic2"))
hash3 = common.BytesToHash([]byte("topic3"))
hash4 = common.BytesToHash([]byte("topic4"))

gspec = core.Genesis{
Alloc: core.GenesisAlloc{addr: {Balance: big.NewInt(1000000)}},
BaseFee: big.NewInt(params.InitialBaseFee),
}
genesis = gspec.ToBlock()
)
defer db.Close()

genesis := core.GenesisBlockForTesting(db, addr, big.NewInt(1000000))
gspec.MustCommit(db)

chain, receipts := core.GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 1000, func(i int, gen *core.BlockGen) {
switch i {
case 1:
Expand Down
8 changes: 3 additions & 5 deletions eth/gasprice/gasprice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,8 @@ func newTestBackend(t *testing.T, londonBlock *big.Int, pending bool) *testBacke
config.TerminalTotalDifficulty = common.Big0
engine := ethash.NewFaker()
db := rawdb.NewMemoryDatabase()
genesis, err := gspec.Commit(db)
if err != nil {
t.Fatal(err)
}
genesis := gspec.MustCommit(db)

// Generate testing blocks
blocks, _ := core.GenerateChain(gspec.Config, genesis, engine, db, testHead+1, func(i int, b *core.BlockGen) {
b.SetCoinbase(common.Address{1})
Expand Down Expand Up @@ -163,7 +161,7 @@ func newTestBackend(t *testing.T, londonBlock *big.Int, pending bool) *testBacke
})
// Construct testing chain
diskdb := rawdb.NewMemoryDatabase()
gspec.Commit(diskdb)
gspec.MustCommit(diskdb)
chain, err := core.NewBlockChain(diskdb, &core.CacheConfig{TrieCleanNoPrefetch: true}, gspec.Config, engine, vm.Config{}, nil, nil)
if err != nil {
t.Fatalf("Failed to create local chain, %v", err)
Expand Down
2 changes: 1 addition & 1 deletion ethclient/ethclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ func generateTestChain() []*types.Block {
g.AddTx(testTx2)
}
}
gblock := genesis.ToBlock(db)
gblock := genesis.MustCommit(db)
engine := ethash.NewFaker()
blocks, _ := core.GenerateChain(genesis.Config, gblock, engine, db, 2, generate)
blocks = append([]*types.Block{gblock}, blocks...)
Expand Down
2 changes: 1 addition & 1 deletion ethclient/gethclient/gethclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func generateTestChain() (*core.Genesis, []*types.Block) {
g.OffsetTime(5)
g.SetExtra([]byte("test"))
}
gblock := genesis.ToBlock(db)
gblock := genesis.MustCommit(db)
engine := ethash.NewFaker()
blocks, _ := core.GenerateChain(config, gblock, engine, db, 1, generate)
blocks = append([]*types.Block{gblock}, blocks...)
Expand Down
2 changes: 1 addition & 1 deletion les/catalyst/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func generatePreMergeChain(n int) (*core.Genesis, []*types.Header, []*types.Bloc
Timestamp: 9000,
BaseFee: big.NewInt(params.InitialBaseFee),
}
gblock := genesis.ToBlock(db)
gblock := genesis.MustCommit(db)
engine := ethash.NewFaker()
blocks, _ := core.GenerateChain(config, gblock, engine, db, n, nil)
totalDifficulty := big.NewInt(0)
Expand Down
Loading

0 comments on commit 5c09ef9

Please sign in to comment.