Skip to content

Commit 5ad9c1e

Browse files
committed
all: introduce state reader interface
1 parent de6d597 commit 5ad9c1e

33 files changed

+700
-386
lines changed

cmd/evm/internal/t8ntool/execution.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -372,7 +372,7 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
372372
}
373373
// Re-create statedb instance with new root upon the updated database
374374
// for accessing latest states.
375-
statedb, err = state.New(root, statedb.Database(), nil)
375+
statedb, err = state.New(root, statedb.Database())
376376
if err != nil {
377377
return nil, nil, nil, NewError(ErrorEVM, fmt.Errorf("could not reopen state: %v", err))
378378
}
@@ -381,8 +381,9 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
381381
}
382382

383383
func MakePreState(db ethdb.Database, accounts types.GenesisAlloc) *state.StateDB {
384-
sdb := state.NewDatabaseWithConfig(db, &triedb.Config{Preimages: true})
385-
statedb, _ := state.New(types.EmptyRootHash, sdb, nil)
384+
tdb := triedb.NewDatabase(db, &triedb.Config{Preimages: true})
385+
sdb := state.NewDatabase(db, tdb, nil)
386+
statedb, _ := state.New(types.EmptyRootHash, sdb)
386387
for addr, a := range accounts {
387388
statedb.SetCode(addr, a.Code)
388389
statedb.SetNonce(addr, a.Nonce)
@@ -393,7 +394,7 @@ func MakePreState(db ethdb.Database, accounts types.GenesisAlloc) *state.StateDB
393394
}
394395
// Commit and re-open to start with a clean state.
395396
root, _ := statedb.Commit(0, false)
396-
statedb, _ = state.New(root, sdb, nil)
397+
statedb, _ = state.New(root, sdb)
397398
return statedb
398399
}
399400

cmd/evm/runner.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,8 @@ func runCmd(ctx *cli.Context) error {
155155
})
156156
defer triedb.Close()
157157
genesis := genesisConfig.MustCommit(db, triedb)
158-
sdb := state.NewDatabaseWithNodeDB(db, triedb)
159-
statedb, _ = state.New(genesis.Root(), sdb, nil)
158+
sdb := state.NewDatabase(db, triedb, nil)
159+
statedb, _ = state.New(genesis.Root(), sdb)
160160
chainConfig = genesisConfig.Config
161161

162162
if ctx.String(SenderFlag.Name) != "" {
@@ -277,7 +277,7 @@ func runCmd(ctx *cli.Context) error {
277277
fmt.Printf("Failed to commit changes %v\n", err)
278278
return err
279279
}
280-
dumpdb, err := state.New(root, sdb, nil)
280+
dumpdb, err := state.New(root, sdb)
281281
if err != nil {
282282
fmt.Printf("Failed to open statedb %v\n", err)
283283
return err

cmd/evm/staterunner.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ func runStateTest(fname string, cfg vm.Config, dump bool) error {
107107
result.Root = &root
108108
fmt.Fprintf(os.Stderr, "{\"stateRoot\": \"%#x\"}\n", root)
109109
if dump { // Dump any state to aid debugging
110-
cpy, _ := state.New(root, tstate.StateDB.Database(), nil)
110+
cpy, _ := state.New(root, tstate.StateDB.Database())
111111
dump := cpy.RawDump(nil)
112112
result.State = &dump
113113
}

cmd/geth/chaincmd.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -586,7 +586,7 @@ func dump(ctx *cli.Context) error {
586586
triedb := utils.MakeTrieDatabase(ctx, db, true, true, false) // always enable preimage lookup
587587
defer triedb.Close()
588588

589-
state, err := state.New(root, state.NewDatabaseWithNodeDB(db, triedb), nil)
589+
state, err := state.New(root, state.NewDatabase(db, triedb, nil))
590590
if err != nil {
591591
return err
592592
}

core/blockchain.go

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,8 @@ var (
7272
storageUpdateTimer = metrics.NewRegisteredResettingTimer("chain/storage/updates", nil)
7373
storageCommitTimer = metrics.NewRegisteredResettingTimer("chain/storage/commits", nil)
7474

75-
snapshotAccountReadTimer = metrics.NewRegisteredResettingTimer("chain/snapshot/account/reads", nil)
76-
snapshotStorageReadTimer = metrics.NewRegisteredResettingTimer("chain/snapshot/storage/reads", nil)
77-
snapshotCommitTimer = metrics.NewRegisteredResettingTimer("chain/snapshot/commits", nil)
78-
79-
triedbCommitTimer = metrics.NewRegisteredResettingTimer("chain/triedb/commits", nil)
75+
snapshotCommitTimer = metrics.NewRegisteredResettingTimer("chain/snapshot/commits", nil)
76+
triedbCommitTimer = metrics.NewRegisteredResettingTimer("chain/triedb/commits", nil)
8077

8178
blockInsertTimer = metrics.NewRegisteredResettingTimer("chain/inserts", nil)
8279
blockValidationTimer = metrics.NewRegisteredResettingTimer("chain/validation", nil)
@@ -217,7 +214,7 @@ type BlockChain struct {
217214
lastWrite uint64 // Last block when the state was flushed
218215
flushInterval atomic.Int64 // Time interval (processing time) after which to flush a state
219216
triedb *triedb.Database // The database handler for maintaining trie nodes.
220-
stateCache state.Database // State database to reuse between imports (contains state cache)
217+
stateDb *state.CachingDB // State database to reuse between imports (contains state cache)
221218
txIndexer *txIndexer // Transaction indexer, might be nil if not enabled
222219

223220
hc *HeaderChain
@@ -310,7 +307,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis
310307
}
311308
bc.flushInterval.Store(int64(cacheConfig.TrieTimeLimit))
312309
bc.forker = NewForkChoice(bc, shouldPreserve)
313-
bc.stateCache = state.NewDatabaseWithNodeDB(bc.db, bc.triedb)
310+
bc.stateDb = state.NewDatabase(bc.db, bc.triedb, nil)
314311
bc.validator = NewBlockValidator(chainConfig, bc)
315312
bc.prefetcher = newStatePrefetcher(chainConfig, bc.hc)
316313
bc.processor = NewStateProcessor(chainConfig, bc.hc)
@@ -448,7 +445,11 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis
448445
AsyncBuild: !bc.cacheConfig.SnapshotWait,
449446
}
450447
bc.snaps, _ = snapshot.New(snapconfig, bc.db, bc.triedb, head.Root)
448+
449+
// Re-initialize the state database with snapshot
450+
bc.stateDb = state.NewDatabase(bc.db, bc.triedb, bc.snaps)
451451
}
452+
452453
// Rewind the chain in case of an incompatible config upgrade.
453454
if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
454455
log.Warn("Rewinding chain to upgrade configuration", "err", compat)
@@ -1800,7 +1801,7 @@ func (bc *BlockChain) insertChain(chain types.Blocks, setHead bool) (int, error)
18001801
if parent == nil {
18011802
parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1)
18021803
}
1803-
statedb, err := state.New(parent.Root, bc.stateCache, bc.snaps)
1804+
statedb, err := state.New(parent.Root, bc.stateDb)
18041805
if err != nil {
18051806
return it.index, err
18061807
}
@@ -1826,7 +1827,7 @@ func (bc *BlockChain) insertChain(chain types.Blocks, setHead bool) (int, error)
18261827
var followupInterrupt atomic.Bool
18271828
if !bc.cacheConfig.TrieCleanNoPrefetch {
18281829
if followup, err := it.peek(); followup != nil && err == nil {
1829-
throwaway, _ := state.New(parent.Root, bc.stateCache, bc.snaps)
1830+
throwaway, _ := state.New(parent.Root, bc.stateDb)
18301831

18311832
go func(start time.Time, followup *types.Block, throwaway *state.StateDB) {
18321833
// Disable tracing for prefetcher executions.
@@ -1946,21 +1947,6 @@ func (bc *BlockChain) processBlock(block *types.Block, statedb *state.StateDB, s
19461947
}
19471948
proctime := time.Since(start) // processing + validation
19481949

1949-
// Update the metrics touched during block processing and validation
1950-
accountReadTimer.Update(statedb.AccountReads) // Account reads are complete(in processing)
1951-
storageReadTimer.Update(statedb.StorageReads) // Storage reads are complete(in processing)
1952-
snapshotAccountReadTimer.Update(statedb.SnapshotAccountReads) // Account reads are complete(in processing)
1953-
snapshotStorageReadTimer.Update(statedb.SnapshotStorageReads) // Storage reads are complete(in processing)
1954-
accountUpdateTimer.Update(statedb.AccountUpdates) // Account updates are complete(in validation)
1955-
storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete(in validation)
1956-
accountHashTimer.Update(statedb.AccountHashes) // Account hashes are complete(in validation)
1957-
triehash := statedb.AccountHashes // The time spent on tries hashing
1958-
trieUpdate := statedb.AccountUpdates + statedb.StorageUpdates // The time spent on tries update
1959-
trieRead := statedb.SnapshotAccountReads + statedb.AccountReads // The time spent on account read
1960-
trieRead += statedb.SnapshotStorageReads + statedb.StorageReads // The time spent on storage read
1961-
blockExecutionTimer.Update(ptime - trieRead) // The time spent on EVM processing
1962-
blockValidationTimer.Update(vtime - (triehash + trieUpdate)) // The time spent on block validation
1963-
19641950
// Write the block to the chain and get the status.
19651951
var (
19661952
wstart = time.Now()
@@ -1975,6 +1961,18 @@ func (bc *BlockChain) processBlock(block *types.Block, statedb *state.StateDB, s
19751961
if err != nil {
19761962
return nil, err
19771963
}
1964+
// Update the metrics touched during block processing and validation
1965+
accountReadTimer.Update(statedb.AccountReads) // Account reads are complete(in processing)
1966+
storageReadTimer.Update(statedb.StorageReads) // Storage reads are complete(in processing)
1967+
accountUpdateTimer.Update(statedb.AccountUpdates) // Account updates are complete(in validation)
1968+
storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete(in validation)
1969+
accountHashTimer.Update(statedb.AccountHashes) // Account hashes are complete(in validation)
1970+
triehash := statedb.AccountHashes // The time spent on account trie hashing
1971+
trieUpdate := statedb.AccountUpdates + statedb.StorageUpdates // The time spent on account trie update + storage tries update and hashing
1972+
trieRead := statedb.AccountReads + statedb.StorageReads // The time spent on account read and storage read
1973+
blockExecutionTimer.Update(ptime - trieRead) // The time spent on EVM processing
1974+
blockValidationTimer.Update(vtime - (triehash + trieUpdate)) // The time spent on block validation
1975+
19781976
// Update the metrics touched during block commit
19791977
accountCommitTimer.Update(statedb.AccountCommits) // Account commits are complete, we can mark them
19801978
storageCommitTimer.Update(statedb.StorageCommits) // Storage commits are complete, we can mark them

core/blockchain_reader.go

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
308308

309309
// HasState checks if state trie is fully present in the database or not.
310310
func (bc *BlockChain) HasState(hash common.Hash) bool {
311-
_, err := bc.stateCache.OpenTrie(hash)
311+
_, err := bc.stateDb.OpenTrie(hash)
312312
return err == nil
313313
}
314314

@@ -341,12 +341,9 @@ func (bc *BlockChain) stateRecoverable(root common.Hash) bool {
341341
// If the code doesn't exist in the in-memory cache, check the storage with
342342
// new code scheme.
343343
func (bc *BlockChain) ContractCodeWithPrefix(hash common.Hash) ([]byte, error) {
344-
type codeReader interface {
345-
ContractCodeWithPrefix(address common.Address, codeHash common.Hash) ([]byte, error)
346-
}
347344
// TODO(rjl493456442) The associated account address is also required
348345
// in Verkle scheme. Fix it once snap-sync is supported for Verkle.
349-
return bc.stateCache.(codeReader).ContractCodeWithPrefix(common.Address{}, hash)
346+
return bc.stateDb.ContractCodeWithPrefix(common.Address{}, hash)
350347
}
351348

352349
// State returns a new mutable state based on the current HEAD block.
@@ -356,7 +353,7 @@ func (bc *BlockChain) State() (*state.StateDB, error) {
356353

357354
// StateAt returns a new mutable state based on a particular point in time.
358355
func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
359-
return state.New(root, bc.stateCache, bc.snaps)
356+
return state.New(root, bc.stateDb)
360357
}
361358

362359
// Config retrieves the chain's fork configuration.
@@ -382,7 +379,7 @@ func (bc *BlockChain) Processor() Processor {
382379

383380
// StateCache returns the caching database underpinning the blockchain instance.
384381
func (bc *BlockChain) StateCache() state.Database {
385-
return bc.stateCache
382+
return bc.stateDb
386383
}
387384

388385
// GasLimit returns the gas limit of the current HEAD block.

core/blockchain_sethead_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2040,7 +2040,7 @@ func testSetHeadWithScheme(t *testing.T, tt *rewindTest, snapshots bool, scheme
20402040
dbconfig.HashDB = hashdb.Defaults
20412041
}
20422042
chain.triedb = triedb.NewDatabase(chain.db, dbconfig)
2043-
chain.stateCache = state.NewDatabaseWithNodeDB(chain.db, chain.triedb)
2043+
chain.stateDb = state.NewDatabase(chain.db, chain.triedb, chain.snaps)
20442044

20452045
// Force run a freeze cycle
20462046
type freezer interface {

core/blockchain_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error {
159159
}
160160
return err
161161
}
162-
statedb, err := state.New(blockchain.GetBlockByHash(block.ParentHash()).Root(), blockchain.stateCache, nil)
162+
statedb, err := state.New(blockchain.GetBlockByHash(block.ParentHash()).Root(), blockchain.stateDb)
163163
if err != nil {
164164
return err
165165
}

core/chain_makers.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,7 @@ func GenerateChain(config *params.ChainConfig, parent *types.Block, engine conse
368368
defer triedb.Close()
369369

370370
for i := 0; i < n; i++ {
371-
statedb, err := state.New(parent.Root(), state.NewDatabaseWithNodeDB(db, triedb), nil)
371+
statedb, err := state.New(parent.Root(), state.NewDatabase(db, triedb, nil))
372372
if err != nil {
373373
panic(err)
374374
}
@@ -475,7 +475,7 @@ func GenerateVerkleChain(config *params.ChainConfig, parent *types.Block, engine
475475
}
476476

477477
for i := 0; i < n; i++ {
478-
statedb, err := state.New(parent.Root(), state.NewDatabaseWithNodeDB(db, trdb), nil)
478+
statedb, err := state.New(parent.Root(), state.NewDatabase(db, trdb, nil))
479479
if err != nil {
480480
panic(err)
481481
}

core/genesis.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,8 @@ func hashAlloc(ga *types.GenesisAlloc, isVerkle bool) (common.Hash, error) {
127127
}
128128
// Create an ephemeral in-memory database for computing hash,
129129
// all the derived states will be discarded to not pollute disk.
130-
db := state.NewDatabaseWithConfig(rawdb.NewMemoryDatabase(), config)
131-
statedb, err := state.New(types.EmptyRootHash, db, nil)
130+
db := rawdb.NewMemoryDatabase()
131+
statedb, err := state.New(types.EmptyRootHash, state.NewDatabase(db, triedb.NewDatabase(db, config), nil))
132132
if err != nil {
133133
return common.Hash{}, err
134134
}
@@ -149,7 +149,7 @@ func hashAlloc(ga *types.GenesisAlloc, isVerkle bool) (common.Hash, error) {
149149
// states will be persisted into the given database. Also, the genesis state
150150
// specification will be flushed as well.
151151
func flushAlloc(ga *types.GenesisAlloc, db ethdb.Database, triedb *triedb.Database, blockhash common.Hash) error {
152-
statedb, err := state.New(types.EmptyRootHash, state.NewDatabaseWithNodeDB(db, triedb), nil)
152+
statedb, err := state.New(types.EmptyRootHash, state.NewDatabase(db, triedb, nil))
153153
if err != nil {
154154
return err
155155
}

0 commit comments

Comments
 (0)