Skip to content

Commit 8bfd404

Browse files
rjl493456442jagdeep sidhu
authored andcommitted
all: cleanup the APIs for initializing genesis (ethereum#25473)
1 parent 4b8895f commit 8bfd404

File tree

26 files changed

+133
-108
lines changed

26 files changed

+133
-108
lines changed

cmd/devp2p/internal/ethtest/chain.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ func loadChain(chainfile string, genesis string) (*Chain, error) {
139139
if err != nil {
140140
return nil, err
141141
}
142-
gblock := gen.ToBlock(nil)
142+
gblock := gen.ToBlock()
143143

144144
blocks, err := blocksFromFile(chainfile, gblock)
145145
if err != nil {

cmd/evm/runner.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ func runCmd(ctx *cli.Context) error {
138138
gen := readGenesis(ctx.String(GenesisFlag.Name))
139139
genesisConfig = gen
140140
db := rawdb.NewMemoryDatabase()
141-
genesis := gen.ToBlock(db)
141+
genesis := gen.MustCommit(db)
142142
statedb, _ = state.New(genesis.Root(), state.NewDatabase(db), nil)
143143
chainConfig = gen.Config
144144
} else {

cmd/faucet/faucet.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ func newFaucet(genesis *core.Genesis, port int, enodes []*enode.Node, network ui
263263
if NEVMPub != "" {
264264
cfg.NEVMPubEP = NEVMPub
265265
}
266-
utils.SetDNSDiscoveryDefaults(&cfg, genesis.ToBlock(nil).Hash())
266+
utils.SetDNSDiscoveryDefaults(&cfg, genesis.ToBlock().Hash())
267267

268268
lesBackend, err := les.New(stack, &cfg)
269269
if err != nil {

consensus/clique/snapshot_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,7 @@ func TestClique(t *testing.T) {
403403
}
404404
// Create a pristine blockchain with the genesis injected
405405
db := rawdb.NewMemoryDatabase()
406-
genesis.Commit(db)
406+
genesisBlock := genesis.MustCommit(db)
407407

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

417-
blocks, _ := core.GenerateChain(&config, genesis.ToBlock(db), engine, db, len(tt.votes), func(j int, gen *core.BlockGen) {
417+
blocks, _ := core.GenerateChain(&config, genesisBlock, engine, db, len(tt.votes), func(j int, gen *core.BlockGen) {
418418
// Cast the vote contained in this block
419419
gen.SetCoinbase(accounts.address(tt.votes[j].voted))
420420
if tt.votes[j].auth {

core/blockchain_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1941,8 +1941,8 @@ func testSideImport(t *testing.T, numCanonBlocksInSidechain, blocksBetweenCommon
19411941
Alloc: GenesisAlloc{addr: {Balance: big.NewInt(math.MaxInt64)}},
19421942
BaseFee: big.NewInt(params.InitialBaseFee),
19431943
}
1944-
signer = types.LatestSigner(gspec.Config)
1945-
genesis, _ = gspec.Commit(db)
1944+
signer = types.LatestSigner(gspec.Config)
1945+
genesis = gspec.MustCommit(db)
19461946
)
19471947
// Generate and import the canonical chain
19481948
diskdb := rawdb.NewMemoryDatabase()

core/genesis.go

Lines changed: 42 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,12 @@ func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error {
8080
return nil
8181
}
8282

83-
// flush adds allocated genesis accounts into a fresh new statedb and
84-
// commit the state changes into the given database handler.
85-
func (ga *GenesisAlloc) flush(db ethdb.Database) (common.Hash, error) {
86-
statedb, err := state.New(common.Hash{}, state.NewDatabase(db), nil)
83+
// deriveHash computes the state root according to the genesis specification.
84+
func (ga *GenesisAlloc) deriveHash() (common.Hash, error) {
85+
// Create an ephemeral in-memory database for computing hash,
86+
// all the derived states will be discarded to not pollute disk.
87+
db := state.NewDatabase(rawdb.NewMemoryDatabase())
88+
statedb, err := state.New(common.Hash{}, db, nil)
8789
if err != nil {
8890
return common.Hash{}, err
8991
}
@@ -95,33 +97,47 @@ func (ga *GenesisAlloc) flush(db ethdb.Database) (common.Hash, error) {
9597
statedb.SetState(addr, key, value)
9698
}
9799
}
100+
return statedb.Commit(false)
101+
}
102+
103+
// flush is very similar with deriveHash, but the main difference is
104+
// all the generated states will be persisted into the given database.
105+
// Also, the genesis state specification will be flushed as well.
106+
func (ga *GenesisAlloc) flush(db ethdb.Database) error {
107+
statedb, err := state.New(common.Hash{}, state.NewDatabase(db), nil)
108+
if err != nil {
109+
return err
110+
}
111+
for addr, account := range *ga {
112+
statedb.AddBalance(addr, account.Balance)
113+
statedb.SetCode(addr, account.Code)
114+
statedb.SetNonce(addr, account.Nonce)
115+
for key, value := range account.Storage {
116+
statedb.SetState(addr, key, value)
117+
}
118+
}
98119
root, err := statedb.Commit(false)
99120
if err != nil {
100-
return common.Hash{}, err
121+
return err
101122
}
102123
err = statedb.Database().TrieDB().Commit(root, true, nil)
103124
if err != nil {
104-
return common.Hash{}, err
125+
return err
105126
}
106-
return root, nil
107-
}
108-
109-
// write writes the json marshaled genesis state into database
110-
// with the given block hash as the unique identifier.
111-
func (ga *GenesisAlloc) write(db ethdb.KeyValueWriter, hash common.Hash) error {
127+
// Marshal the genesis state specification and persist.
112128
blob, err := json.Marshal(ga)
113129
if err != nil {
114130
return err
115131
}
116-
rawdb.WriteGenesisState(db, hash, blob)
132+
rawdb.WriteGenesisStateSpec(db, root, blob)
117133
return nil
118134
}
119135

120136
// CommitGenesisState loads the stored genesis state with the given block
121137
// hash and commits them into the given database handler.
122138
func CommitGenesisState(db ethdb.Database, hash common.Hash) error {
123139
var alloc GenesisAlloc
124-
blob := rawdb.ReadGenesisState(db, hash)
140+
blob := rawdb.ReadGenesisStateSpec(db, hash)
125141
if len(blob) != 0 {
126142
if err := alloc.UnmarshalJSON(blob); err != nil {
127143
return err
@@ -156,8 +172,7 @@ func CommitGenesisState(db ethdb.Database, hash common.Hash) error {
156172
return errors.New("not found")
157173
}
158174
}
159-
_, err := alloc.flush(db)
160-
return err
175+
return alloc.flush(db)
161176
}
162177

163178
// GenesisAccount is an account in the state of the genesis block.
@@ -278,7 +293,7 @@ func SetupGenesisBlockWithOverride(db ethdb.Database, genesis *Genesis, override
278293
genesis = DefaultGenesisBlock()
279294
}
280295
// Ensure the stored genesis matches with the given one.
281-
hash := genesis.ToBlock(nil).Hash()
296+
hash := genesis.ToBlock().Hash()
282297
if hash != stored {
283298
return genesis.Config, hash, &GenesisMismatchError{stored, hash}
284299
}
@@ -291,7 +306,7 @@ func SetupGenesisBlockWithOverride(db ethdb.Database, genesis *Genesis, override
291306
}
292307
// Check whether the genesis block is already written.
293308
if genesis != nil {
294-
hash := genesis.ToBlock(nil).Hash()
309+
hash := genesis.ToBlock().Hash()
295310
if hash != stored {
296311
return genesis.Config, hash, &GenesisMismatchError{stored, hash}
297312
}
@@ -356,13 +371,9 @@ func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
356371
}
357372
}
358373

359-
// ToBlock creates the genesis block and writes state of a genesis specification
360-
// to the given database (or discards it if nil).
361-
func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
362-
if db == nil {
363-
db = rawdb.NewMemoryDatabase()
364-
}
365-
root, err := g.Alloc.flush(db)
374+
// ToBlock returns the genesis block according to genesis specification.
375+
func (g *Genesis) ToBlock() *types.Block {
376+
root, err := g.Alloc.deriveHash()
366377
if err != nil {
367378
panic(err)
368379
}
@@ -399,7 +410,7 @@ func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
399410
// Commit writes the block and state of a genesis specification to the database.
400411
// The block is committed as the canonical head block.
401412
func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) {
402-
block := g.ToBlock(db)
413+
block := g.ToBlock()
403414
if block.Number().Sign() != 0 {
404415
return nil, errors.New("can't commit genesis block with number > 0")
405416
}
@@ -413,7 +424,10 @@ func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) {
413424
if config.Clique != nil && len(block.Extra()) < 32+crypto.SignatureLength {
414425
return nil, errors.New("can't start clique chain without signers")
415426
}
416-
if err := g.Alloc.write(db, block.Hash()); err != nil {
427+
// All the checks has passed, flush the states derived from the genesis
428+
// specification as well as the specification itself into the provided
429+
// database.
430+
if err := g.Alloc.flush(db); err != nil {
417431
return nil, err
418432
}
419433
rawdb.WriteTd(db, block.Hash(), block.NumberU64(), block.Difficulty())
@@ -437,15 +451,6 @@ func (g *Genesis) MustCommit(db ethdb.Database) *types.Block {
437451
return block
438452
}
439453

440-
// GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.
441-
func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
442-
g := Genesis{
443-
Alloc: GenesisAlloc{addr: {Balance: balance}},
444-
BaseFee: big.NewInt(params.InitialBaseFee),
445-
}
446-
return g.MustCommit(db)
447-
}
448-
449454
// DefaultGenesisBlock returns the Ethereum main net genesis block.
450455
func DefaultGenesisBlock() *Genesis {
451456
return &Genesis{
@@ -529,6 +534,7 @@ func DefaultSepoliaGenesisBlock() *Genesis {
529534
}
530535
}
531536

537+
// DefaultKilnGenesisBlock returns the kiln network genesis block.
532538
func DefaultKilnGenesisBlock() *Genesis {
533539
g := new(Genesis)
534540
reader := strings.NewReader(KilnAllocData)

core/genesis_test.go

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ func TestGenesisHashes(t *testing.T) {
181181
t.Errorf("case: %d a), want: %s, got: %s", i, c.want.Hex(), have.Hex())
182182
}
183183
// Test via ToBlock
184-
if have := c.genesis.ToBlock(nil).Hash(); have != c.want {
184+
if have := c.genesis.ToBlock().Hash(); have != c.want {
185185
t.Errorf("case: %d a), want: %s, got: %s", i, c.want.Hex(), have.Hex())
186186
}
187187
}
@@ -195,11 +195,7 @@ func TestGenesis_Commit(t *testing.T) {
195195
}
196196

197197
db := rawdb.NewMemoryDatabase()
198-
genesisBlock, err := genesis.Commit(db)
199-
if err != nil {
200-
t.Fatal(err)
201-
}
202-
198+
genesisBlock := genesis.MustCommit(db)
203199
if genesis.Difficulty != nil {
204200
t.Fatalf("assumption wrong")
205201
}
@@ -224,12 +220,12 @@ func TestReadWriteGenesisAlloc(t *testing.T) {
224220
{1}: {Balance: big.NewInt(1), Storage: map[common.Hash]common.Hash{{1}: {1}}},
225221
{2}: {Balance: big.NewInt(2), Storage: map[common.Hash]common.Hash{{2}: {2}}},
226222
}
227-
hash = common.HexToHash("0xdeadbeef")
223+
hash, _ = alloc.deriveHash()
228224
)
229-
alloc.write(db, hash)
225+
alloc.flush(db)
230226

231227
var reload GenesisAlloc
232-
err := reload.UnmarshalJSON(rawdb.ReadGenesisState(db, hash))
228+
err := reload.UnmarshalJSON(rawdb.ReadGenesisStateSpec(db, hash))
233229
if err != nil {
234230
t.Fatalf("Failed to load genesis state %v", err)
235231
}

core/rawdb/accessors_metadata.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -81,15 +81,16 @@ func WriteChainConfig(db ethdb.KeyValueWriter, hash common.Hash, cfg *params.Cha
8181
}
8282
}
8383

84-
// ReadGenesisState retrieves the genesis state based on the given genesis hash.
85-
func ReadGenesisState(db ethdb.KeyValueReader, hash common.Hash) []byte {
86-
data, _ := db.Get(genesisKey(hash))
84+
// ReadGenesisStateSpec retrieves the genesis state specification based on the
85+
// given genesis hash.
86+
func ReadGenesisStateSpec(db ethdb.KeyValueReader, hash common.Hash) []byte {
87+
data, _ := db.Get(genesisStateSpecKey(hash))
8788
return data
8889
}
8990

90-
// WriteGenesisState writes the genesis state into the disk.
91-
func WriteGenesisState(db ethdb.KeyValueWriter, hash common.Hash, data []byte) {
92-
if err := db.Put(genesisKey(hash), data); err != nil {
91+
// WriteGenesisStateSpec writes the genesis state specification into the disk.
92+
func WriteGenesisStateSpec(db ethdb.KeyValueWriter, hash common.Hash, data []byte) {
93+
if err := db.Put(genesisStateSpecKey(hash), data); err != nil {
9394
log.Crit("Failed to store genesis state", "err", err)
9495
}
9596
}

core/rawdb/schema.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ func dataHashKey(hash common.Hash) []byte {
244244
return append(dataHashKeyPrefix, hash.Bytes()...)
245245
}
246246

247-
// genesisKey = genesisPrefix + hash
248-
func genesisKey(hash common.Hash) []byte {
247+
// genesisStateSpecKey = genesisPrefix + hash
248+
func genesisStateSpecKey(hash common.Hash) []byte {
249249
return append(genesisPrefix, hash.Bytes()...)
250250
}

eth/catalyst/api_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ func generatePreMergeChain(n int) (*core.Genesis, []*types.Block) {
6969
g.AddTx(tx)
7070
testNonce++
7171
}
72-
gblock := genesis.ToBlock(db)
72+
gblock := genesis.MustCommit(db)
7373
engine := ethash.NewFaker()
7474
blocks, _ := core.GenerateChain(config, gblock, engine, db, n, generate)
7575
totalDifficulty := big.NewInt(0)

0 commit comments

Comments
 (0)