Skip to content

Commit

Permalink
all: move genesis init to blockchain (#570)
Browse files Browse the repository at this point in the history
* all: move genesis initialization to blockchain

* all: fix test
  • Loading branch information
Francesco4203 authored Sep 16, 2024
1 parent 5dc0bd6 commit 1c73b9a
Show file tree
Hide file tree
Showing 34 changed files with 289 additions and 174 deletions.
2 changes: 1 addition & 1 deletion accounts/abi/bind/backends/simulated.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ type SimulatedBackend struct {
func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend {
genesis := core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: gasLimit, Alloc: alloc}
genesis.MustCommit(database)
blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
blockchain, _ := core.NewBlockChain(database, nil, &genesis, nil, ethash.NewFaker(), vm.Config{}, nil, nil)

backend := &SimulatedBackend{
database: database,
Expand Down
5 changes: 3 additions & 2 deletions cmd/utils/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -2223,7 +2223,8 @@ func MakeGenesis(ctx *cli.Context) *core.Genesis {
func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
var err error
chainDb = MakeChainDatabase(ctx, stack, false) // TODO(rjl493456442) support read-only database
config, _, err := core.SetupGenesisBlock(chainDb, MakeGenesis(ctx), false)
gpec := MakeGenesis(ctx)
config, err := core.LoadChainConfig(chainDb, gpec)
if err != nil {
Fatalf("%v", err)
}
Expand Down Expand Up @@ -2282,7 +2283,7 @@ func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chai

// TODO(rjl493456442) disable snapshot generation/wiping if the chain is read only.
// Disable transaction indexing/unindexing by default.
chain, err = core.NewBlockChain(chainDb, cache, config, engine, vmcfg, nil, nil)
chain, err = core.NewBlockChain(chainDb, cache, gpec, nil, engine, vmcfg, nil, nil)
if err != nil {
Fatalf("Can't create BlockChain: %v", err)
}
Expand Down
7 changes: 4 additions & 3 deletions consensus/clique/clique_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ func TestReimportMirroredState(t *testing.T) {
signer = new(types.HomesteadSigner)
)
genspec := &core.Genesis{
Config: params.AllCliqueProtocolChanges,
ExtraData: make([]byte, extraVanity+common.AddressLength+extraSeal),
Alloc: map[common.Address]core.GenesisAccount{
addr: {Balance: big.NewInt(10000000000000000)},
Expand All @@ -55,7 +56,7 @@ func TestReimportMirroredState(t *testing.T) {
genesis := genspec.MustCommit(db)

// Generate a batch of blocks, each properly signed
chain, _ := core.NewBlockChain(db, nil, params.AllCliqueProtocolChanges, engine, vm.Config{}, nil, nil)
chain, _ := core.NewBlockChain(db, nil, genspec, nil, engine, vm.Config{}, nil, nil)
defer chain.Stop()

blocks, _ := core.GenerateChain(params.AllCliqueProtocolChanges, genesis, engine, db, 3, func(i int, block *core.BlockGen) {
Expand Down Expand Up @@ -89,7 +90,7 @@ func TestReimportMirroredState(t *testing.T) {
db = rawdb.NewMemoryDatabase()
genspec.MustCommit(db)

chain, _ = core.NewBlockChain(db, nil, params.AllCliqueProtocolChanges, engine, vm.Config{}, nil, nil)
chain, _ = core.NewBlockChain(db, nil, genspec, nil, engine, vm.Config{}, nil, nil)
defer chain.Stop()

if _, err := chain.InsertChain(blocks[:2]); err != nil {
Expand All @@ -102,7 +103,7 @@ func TestReimportMirroredState(t *testing.T) {
// Simulate a crash by creating a new chain on top of the database, without
// flushing the dirty states out. Insert the last block, triggering a sidechain
// reimport.
chain, _ = core.NewBlockChain(db, nil, params.AllCliqueProtocolChanges, engine, vm.Config{}, nil, nil)
chain, _ = core.NewBlockChain(db, nil, genspec, nil, engine, vm.Config{}, nil, nil)
defer chain.Stop()

if _, err := chain.InsertChain(blocks[2:]); err != nil {
Expand Down
3 changes: 2 additions & 1 deletion consensus/clique/snapshot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ func TestClique(t *testing.T) {
Period: 1,
Epoch: tt.epoch,
}
genesis.Config = &config
engine := New(config.Clique, db)
engine.fakeDiff = true

Expand Down Expand Up @@ -450,7 +451,7 @@ func TestClique(t *testing.T) {
batches[len(batches)-1] = append(batches[len(batches)-1], block)
}
// Pass all the headers through clique and ensure tallying succeeds
chain, err := core.NewBlockChain(db, nil, &config, engine, vm.Config{}, nil, nil)
chain, err := core.NewBlockChain(db, nil, genesis, nil, engine, vm.Config{}, nil, nil)
if err != nil {
t.Errorf("test %d: failed to create test chain: %v", i, err)
continue
Expand Down
49 changes: 28 additions & 21 deletions consensus/consortium/v2/consortium_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1433,11 +1433,12 @@ func TestVerifyVote(t *testing.T) {
}

db := rawdb.NewMemoryDatabase()
genesis := (&core.Genesis{
gspec := &core.Genesis{
Config: params.TestChainConfig,
BaseFee: big.NewInt(params.InitialBaseFee),
}).MustCommit(db)
chain, _ := core.NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFullFaker(), vm.Config{}, nil, nil)
}
genesis := gspec.MustCommit(db)
chain, _ := core.NewBlockChain(db, nil, gspec, nil, ethash.NewFullFaker(), vm.Config{}, nil, nil)

bs, _ := core.GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), db, 1, nil, true)
if _, err := chain.InsertChain(bs[:]); err != nil {
Expand Down Expand Up @@ -1564,9 +1565,10 @@ func TestKnownBlockReorg(t *testing.T) {
},
}

genesis := (&core.Genesis{
gspec := &core.Genesis{
Config: &chainConfig,
}).MustCommit(db)
}
genesis := gspec.MustCommit(db)

mock := &mockContract{
validators: make(map[common.Address]blsCommon.PublicKey),
Expand All @@ -1584,7 +1586,7 @@ func TestKnownBlockReorg(t *testing.T) {
db: db,
}

chain, _ := core.NewBlockChain(db, nil, &chainConfig, &v2, vm.Config{}, nil, nil)
chain, _ := core.NewBlockChain(db, nil, gspec, nil, &v2, vm.Config{}, nil, nil)
extraData := [consortiumCommon.ExtraVanity + consortiumCommon.ExtraSeal]byte{}

blocks, _ := core.GenerateConsortiumChain(
Expand Down Expand Up @@ -1811,13 +1813,14 @@ func TestUpgradeRoninTrustedOrg(t *testing.T) {
},
}

genesis := (&core.Genesis{
gspec := &core.Genesis{
Config: &chainConfig,
Alloc: core.GenesisAlloc{
// Make proxy address non-empty to avoid being deleted
common.Address{0x10}: core.GenesisAccount{Balance: common.Big1},
},
}).MustCommit(db)
}
genesis := gspec.MustCommit(db)

mock := &mockContract{
validators: map[common.Address]blsCommon.PublicKey{
Expand All @@ -1837,7 +1840,7 @@ func TestUpgradeRoninTrustedOrg(t *testing.T) {
},
}

chain, _ := core.NewBlockChain(db, nil, &chainConfig, &v2, vm.Config{}, nil, nil)
chain, _ := core.NewBlockChain(db, nil, gspec, nil, &v2, vm.Config{}, nil, nil)
extraData := [consortiumCommon.ExtraVanity + consortiumCommon.ExtraSeal]byte{}

parent := genesis
Expand Down Expand Up @@ -1956,9 +1959,10 @@ func TestUpgradeAxieProxyCode(t *testing.T) {
Code: code,
},
}
genesis := (&core.Genesis{
gspec := &core.Genesis{
Config: chainConfig,
}).MustCommit(db)
}
genesis := gspec.MustCommit(db)
mock := &mockTrippContract{
checkpointValidators: []validatorWithBlsWeight{
validatorWithBlsWeight{
Expand All @@ -1985,7 +1989,7 @@ func TestUpgradeAxieProxyCode(t *testing.T) {
testTrippEffective: true,
}

chain, _ := core.NewBlockChain(db, nil, chainConfig, v2, vm.Config{}, nil, nil)
chain, _ := core.NewBlockChain(db, nil, gspec, nil, v2, vm.Config{}, nil, nil)
extraData := &finality.HeaderExtraData{}

parent := genesis
Expand Down Expand Up @@ -2078,13 +2082,14 @@ func TestSystemTransactionOrder(t *testing.T) {
},
}

genesis := (&core.Genesis{
gspec := &core.Genesis{
Config: &chainConfig,
Alloc: core.GenesisAlloc{
// Make proxy address non-empty to avoid being deleted
common.Address{0x10}: core.GenesisAccount{Balance: common.Big1},
},
}).MustCommit(db)
}
genesis := gspec.MustCommit(db)

mock := &mockContract{
validators: map[common.Address]blsCommon.PublicKey{
Expand All @@ -2104,7 +2109,7 @@ func TestSystemTransactionOrder(t *testing.T) {
},
}

chain, _ := core.NewBlockChain(db, nil, &chainConfig, &v2, vm.Config{}, nil, nil)
chain, _ := core.NewBlockChain(db, nil, gspec, nil, &v2, vm.Config{}, nil, nil)
extraData := [consortiumCommon.ExtraVanity + consortiumCommon.ExtraSeal]byte{}

signer := types.NewEIP155Signer(big.NewInt(2021))
Expand Down Expand Up @@ -2201,12 +2206,13 @@ func TestIsPeriodBlock(t *testing.T) {
RoninValidatorSet: common.HexToAddress("0xaa"),
},
}
genesis := (&core.Genesis{
gspec := &core.Genesis{
Config: &chainConfig,
BaseFee: big.NewInt(params.InitialBaseFee),
Timestamp: midnight, // genesis at day 1
}).MustCommit(db)
chain, _ := core.NewBlockChain(db, nil, &chainConfig, ethash.NewFullFaker(), vm.Config{}, nil, nil)
}
genesis := gspec.MustCommit(db)
chain, _ := core.NewBlockChain(db, nil, gspec, nil, ethash.NewFullFaker(), vm.Config{}, nil, nil)
// create chain of up to 399 blocks, all of them are not period block
bs, _ := core.GenerateChain(&chainConfig, genesis, ethash.NewFaker(), db, 399, nil, true) // create chain of up to 399 blocks
if _, err := chain.InsertChain(bs[:]); err != nil {
Expand Down Expand Up @@ -2297,12 +2303,13 @@ func TestIsTrippEffective(t *testing.T) {
},
TrippPeriod: new(big.Int).SetUint64(now / dayInSeconds),
}
genesis := (&core.Genesis{
gspec := &core.Genesis{
Config: &chainConfig,
BaseFee: big.NewInt(params.InitialBaseFee),
Timestamp: midnight, // genesis at day 1
}).MustCommit(db)
chain, _ := core.NewBlockChain(db, nil, &chainConfig, ethash.NewFullFaker(), vm.Config{}, nil, nil)
}
genesis := gspec.MustCommit(db)
chain, _ := core.NewBlockChain(db, nil, gspec, nil, ethash.NewFullFaker(), vm.Config{}, nil, nil)
// create chain of up to 399 blocks, all of them are not Tripp effective
bs, _ := core.GenerateChain(&chainConfig, genesis, ethash.NewFaker(), db, 399, nil, true)
if _, err := chain.InsertChain(bs[:]); err != nil {
Expand Down
7 changes: 5 additions & 2 deletions core/bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) {

// Time the insertion of the new chain.
// State and blocks are stored in the same DB.
chainman, _ := NewBlockChain(db, nil, gspec.Config, ethash.NewFaker(), vm.Config{}, nil, nil)
chainman, _ := NewBlockChain(db, nil, &gspec, nil, ethash.NewFaker(), vm.Config{}, nil, nil)
defer chainman.Stop()
b.ReportAllocs()
b.ResetTimer()
Expand Down Expand Up @@ -316,7 +316,10 @@ func benchReadChain(b *testing.B, full bool, count uint64) {
if err != nil {
b.Fatalf("error opening database at %v: %v", dir, err)
}
chain, err := NewBlockChain(db, &cacheConfig, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
gspec := &Genesis{
Config: params.TestChainConfig,
}
chain, err := NewBlockChain(db, &cacheConfig, gspec, nil, ethash.NewFaker(), vm.Config{}, nil, nil)
if err != nil {
b.Fatalf("error creating chain: %v", err)
}
Expand Down
8 changes: 4 additions & 4 deletions core/block_validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func TestHeaderVerification(t *testing.T) {
headers[i] = block.Header()
}
// Run the header checker for blocks one-by-one, checking for both valid and invalid nonces
chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
chain, _ := NewBlockChain(testdb, nil, gspec, nil, ethash.NewFaker(), vm.Config{}, nil, nil)
defer chain.Stop()

for i := 0; i < len(blocks); i++ {
Expand Down Expand Up @@ -106,11 +106,11 @@ func testHeaderConcurrentVerification(t *testing.T, threads int) {
var results <-chan error

if valid {
chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
chain, _ := NewBlockChain(testdb, nil, gspec, nil, ethash.NewFaker(), vm.Config{}, nil, nil)
_, results = chain.engine.VerifyHeaders(chain, headers, seals)
chain.Stop()
} else {
chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFakeFailer(uint64(len(headers)-1)), vm.Config{}, nil, nil)
chain, _ := NewBlockChain(testdb, nil, gspec, nil, ethash.NewFakeFailer(uint64(len(headers)-1)), vm.Config{}, nil, nil)
_, results = chain.engine.VerifyHeaders(chain, headers, seals)
chain.Stop()
}
Expand Down Expand Up @@ -173,7 +173,7 @@ func testHeaderConcurrentAbortion(t *testing.T, threads int) {
defer runtime.GOMAXPROCS(old)

// Start the verifications and immediately abort
chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFakeDelayer(time.Millisecond), vm.Config{}, nil, nil)
chain, _ := NewBlockChain(testdb, nil, gspec, nil, ethash.NewFakeDelayer(time.Millisecond), vm.Config{}, nil, nil)
defer chain.Stop()

abort, results := chain.engine.VerifyHeaders(chain, headers, seals)
Expand Down
15 changes: 13 additions & 2 deletions core/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ type BlockChain struct {
// NewBlockChain returns a fully initialised block chain using information
// available in the database. It initialises the default Ethereum Validator and
// Processor.
func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool, txLookupLimit *uint64) (*BlockChain, error) {
func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis, overrideArrowGlacier *big.Int, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool, txLookupLimit *uint64) (*BlockChain, error) {
if cacheConfig == nil {
cacheConfig = defaultCacheConfig
}
Expand All @@ -249,6 +249,12 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
dirtyAccountsCache, _ := lru.New[common.Hash, []*types.DirtyStateAccount](dirtyAccountsCacheLimit)
internalTxsCache, _ := lru.New[common.Hash, []*types.InternalTransaction](internalTxsCacheLimit)

chainConfig, genesisHash, genesisErr := SetupGenesisBlockWithOverride(db, genesis, overrideArrowGlacier, false)
if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok {
return nil, genesisErr
}
log.Info("Initialised chain configuration", "config", chainConfig)

bc := &BlockChain{
chainConfig: chainConfig,
cacheConfig: cacheConfig,
Expand Down Expand Up @@ -429,7 +435,12 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par

// load the latest dirty accounts stored from last stop to cache
bc.loadLatestDirtyAccounts()

// Rewind the chain in case of an incompatible config upgrade.
if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
log.Warn("Rewinding chain to upgrade configuration", "err", compat)
bc.SetHead(compat.RewindTo)
rawdb.WriteChainConfig(db, genesisHash, chainConfig)
}
return bc, nil
}

Expand Down
14 changes: 8 additions & 6 deletions core/blockchain_repair_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1774,7 +1774,8 @@ func testRepair(t *testing.T, tt *rewindTest, snapshots bool) {

// Initialize a fresh chain
var (
genesis = (&Genesis{BaseFee: big.NewInt(params.InitialBaseFee)}).MustCommit(db)
gspec = &Genesis{Config: params.TestChainConfig, BaseFee: big.NewInt(params.InitialBaseFee)}
genesis = gspec.MustCommit(db)
engine = ethash.NewFullFaker()
config = &CacheConfig{
TrieCleanLimit: 256,
Expand All @@ -1787,7 +1788,7 @@ func testRepair(t *testing.T, tt *rewindTest, snapshots bool) {
config.SnapshotLimit = 256
config.SnapshotWait = true
}
chain, err := NewBlockChain(db, config, params.AllEthashProtocolChanges, engine, vm.Config{}, nil, nil)
chain, err := NewBlockChain(db, config, gspec, nil, engine, vm.Config{}, nil, nil)
if err != nil {
t.Fatalf("Failed to create chain: %v", err)
}
Expand Down Expand Up @@ -1845,7 +1846,7 @@ func testRepair(t *testing.T, tt *rewindTest, snapshots bool) {
}
defer db.Close()

chain, err = NewBlockChain(db, nil, params.AllEthashProtocolChanges, engine, vm.Config{}, nil, nil)
chain, err = NewBlockChain(db, nil, gspec, nil, engine, vm.Config{}, nil, nil)
if err != nil {
t.Fatalf("Failed to recreate chain: %v", err)
}
Expand Down Expand Up @@ -1910,7 +1911,8 @@ func TestIssue23496(t *testing.T) {

// Initialize a fresh chain
var (
genesis = (&Genesis{BaseFee: big.NewInt(params.InitialBaseFee)}).MustCommit(db)
gspec = &Genesis{Config: params.TestChainConfig, BaseFee: big.NewInt(params.InitialBaseFee)}
genesis = gspec.MustCommit(db)
engine = ethash.NewFullFaker()
config = &CacheConfig{
TrieCleanLimit: 256,
Expand All @@ -1920,7 +1922,7 @@ func TestIssue23496(t *testing.T) {
SnapshotWait: true,
}
)
chain, err := NewBlockChain(db, config, params.AllEthashProtocolChanges, engine, vm.Config{}, nil, nil)
chain, err := NewBlockChain(db, config, gspec, nil, engine, vm.Config{}, nil, nil)
if err != nil {
t.Fatalf("Failed to create chain: %v", err)
}
Expand Down Expand Up @@ -1968,7 +1970,7 @@ func TestIssue23496(t *testing.T) {
}
defer db.Close()

chain, err = NewBlockChain(db, nil, params.AllEthashProtocolChanges, engine, vm.Config{}, nil, nil)
chain, err = NewBlockChain(db, nil, gspec, nil, engine, vm.Config{}, nil, nil)
if err != nil {
t.Fatalf("Failed to recreate chain: %v", err)
}
Expand Down
5 changes: 3 additions & 2 deletions core/blockchain_sethead_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1973,7 +1973,8 @@ func testSetHead(t *testing.T, tt *rewindTest, snapshots bool) {

// Initialize a fresh chain
var (
genesis = (&Genesis{BaseFee: big.NewInt(params.InitialBaseFee)}).MustCommit(db)
gspec = &Genesis{Config: params.TestChainConfig, BaseFee: big.NewInt(params.InitialBaseFee)}
genesis = gspec.MustCommit(db)
engine = ethash.NewFullFaker()
config = &CacheConfig{
TrieCleanLimit: 256,
Expand All @@ -1986,7 +1987,7 @@ func testSetHead(t *testing.T, tt *rewindTest, snapshots bool) {
config.SnapshotLimit = 256
config.SnapshotWait = true
}
chain, err := NewBlockChain(db, config, params.AllEthashProtocolChanges, engine, vm.Config{}, nil, nil)
chain, err := NewBlockChain(db, config, gspec, nil, engine, vm.Config{}, nil, nil)
if err != nil {
t.Fatalf("Failed to create chain: %v", err)
}
Expand Down
Loading

0 comments on commit 1c73b9a

Please sign in to comment.