Skip to content

Commit 9e5f03b

Browse files
authored
core/state: access trie through Database interface, track errors (#14589)
With this commit, core/state's access to the underlying key/value database is mediated through an interface. Database errors are tracked in StateDB and returned by CommitTo or the new Error method. Motivation for this change: We can remove the light client's duplicated copy of core/state. The light client now supports node iteration, so tracing and storage enumeration can work with the light client (not implemented in this commit).
1 parent bb36627 commit 9e5f03b

49 files changed

Lines changed: 809 additions & 1663 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎accounts/abi/bind/backends/simulated.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ func (b *SimulatedBackend) Rollback() {
9090
func (b *SimulatedBackend) rollback() {
9191
blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), b.database, 1, func(int, *core.BlockGen) {})
9292
b.pendingBlock = blocks[0]
93-
b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
93+
b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database))
9494
}
9595

9696
// CodeAt returns the code associated with a certain account in the blockchain.
@@ -279,7 +279,7 @@ func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transa
279279
block.AddTx(tx)
280280
})
281281
b.pendingBlock = blocks[0]
282-
b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
282+
b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database))
283283
return nil
284284
}
285285

‎cmd/evm/runner.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,8 @@ func runCmd(ctx *cli.Context) error {
9898
_, statedb = gen.ToBlock()
9999
chainConfig = gen.Config
100100
} else {
101-
var db, _ = ethdb.NewMemDatabase()
102-
statedb, _ = state.New(common.Hash{}, db)
101+
db, _ := ethdb.NewMemDatabase()
102+
statedb, _ = state.New(common.Hash{}, state.NewDatabase(db))
103103
}
104104
if ctx.GlobalString(SenderFlag.Name) != "" {
105105
sender = common.HexToAddress(ctx.GlobalString(SenderFlag.Name))
@@ -188,7 +188,7 @@ func runCmd(ctx *cli.Context) error {
188188
execTime := time.Since(tstart)
189189

190190
if ctx.GlobalBool(DumpFlag.Name) {
191-
statedb.Commit(true)
191+
statedb.IntermediateRoot(true)
192192
fmt.Println(string(statedb.Dump()))
193193
}
194194

‎cmd/geth/chaincmd.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ func dump(ctx *cli.Context) error {
312312
fmt.Println("{}")
313313
utils.Fatalf("block not found")
314314
} else {
315-
state, err := state.New(block.Root(), chainDb)
315+
state, err := state.New(block.Root(), state.NewDatabase(chainDb))
316316
if err != nil {
317317
utils.Fatalf("could not create new state: %v", err)
318318
}

‎core/block_validator.go‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,16 +52,10 @@ func NewBlockValidator(config *params.ChainConfig, blockchain *BlockChain, engin
5252
// validated at this point.
5353
func (v *BlockValidator) ValidateBody(block *types.Block) error {
5454
// Check whether the block's known, and if not, that it's linkable
55-
if v.bc.HasBlock(block.Hash()) {
56-
if _, err := state.New(block.Root(), v.bc.chainDb); err == nil {
57-
return ErrKnownBlock
58-
}
55+
if v.bc.HasBlockAndState(block.Hash()) {
56+
return ErrKnownBlock
5957
}
60-
parent := v.bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
61-
if parent == nil {
62-
return consensus.ErrUnknownAncestor
63-
}
64-
if _, err := state.New(parent.Root(), v.bc.chainDb); err != nil {
58+
if !v.bc.HasBlockAndState(block.ParentHash()) {
6559
return consensus.ErrUnknownAncestor
6660
}
6761
// Header validity is known at this point, check the uncles and transactions

‎core/blockchain.go‎

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ type BlockChain struct {
9292
currentBlock *types.Block // Current head of the block chain
9393
currentFastBlock *types.Block // Current head of the fast-sync chain (may be above the block chain!)
9494

95-
stateCache *state.StateDB // State database to reuse between imports (contains state cache)
95+
stateCache state.Database // State database to reuse between imports (contains state cache)
9696
bodyCache *lru.Cache // Cache for the most recent block bodies
9797
bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
9898
blockCache *lru.Cache // Cache for the most recent entire blocks
@@ -125,6 +125,7 @@ func NewBlockChain(chainDb ethdb.Database, config *params.ChainConfig, engine co
125125
bc := &BlockChain{
126126
config: config,
127127
chainDb: chainDb,
128+
stateCache: state.NewDatabase(chainDb),
128129
eventMux: mux,
129130
quit: make(chan struct{}),
130131
bodyCache: bodyCache,
@@ -190,7 +191,7 @@ func (bc *BlockChain) loadLastState() error {
190191
return bc.Reset()
191192
}
192193
// Make sure the state associated with the block is available
193-
if _, err := state.New(currentBlock.Root(), bc.chainDb); err != nil {
194+
if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil {
194195
// Dangling block without a state associated, init from scratch
195196
log.Warn("Head state missing, resetting chain", "number", currentBlock.Number(), "hash", currentBlock.Hash())
196197
return bc.Reset()
@@ -214,12 +215,6 @@ func (bc *BlockChain) loadLastState() error {
214215
bc.currentFastBlock = block
215216
}
216217
}
217-
// Initialize a statedb cache to ensure singleton account bloom filter generation
218-
statedb, err := state.New(bc.currentBlock.Root(), bc.chainDb)
219-
if err != nil {
220-
return err
221-
}
222-
bc.stateCache = statedb
223218

224219
// Issue a status log for the user
225220
headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
@@ -261,7 +256,7 @@ func (bc *BlockChain) SetHead(head uint64) error {
261256
bc.currentBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64())
262257
}
263258
if bc.currentBlock != nil {
264-
if _, err := state.New(bc.currentBlock.Root(), bc.chainDb); err != nil {
259+
if _, err := state.New(bc.currentBlock.Root(), bc.stateCache); err != nil {
265260
// Rewound state missing, rolled back to before pivot, reset to genesis
266261
bc.currentBlock = nil
267262
}
@@ -384,7 +379,7 @@ func (bc *BlockChain) State() (*state.StateDB, error) {
384379

385380
// StateAt returns a new mutable state based on a particular point in time.
386381
func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
387-
return bc.stateCache.New(root)
382+
return state.New(root, bc.stateCache)
388383
}
389384

390385
// Reset purges the entire blockchain, restoring it to its genesis state.
@@ -531,7 +526,7 @@ func (bc *BlockChain) HasBlockAndState(hash common.Hash) bool {
531526
return false
532527
}
533528
// Ensure the associated state is also present
534-
_, err := state.New(block.Root(), bc.chainDb)
529+
_, err := bc.stateCache.OpenTrie(block.Root())
535530
return err == nil
536531
}
537532

@@ -959,31 +954,30 @@ func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
959954
}
960955
// Create a new statedb using the parent block and report an
961956
// error if it fails.
962-
switch {
963-
case i == 0:
964-
err = bc.stateCache.Reset(bc.GetBlock(block.ParentHash(), block.NumberU64()-1).Root())
965-
default:
966-
err = bc.stateCache.Reset(chain[i-1].Root())
957+
var parent *types.Block
958+
if i == 0 {
959+
parent = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
960+
} else {
961+
parent = chain[i-1]
967962
}
963+
state, err := state.New(parent.Root(), bc.stateCache)
968964
if err != nil {
969-
bc.reportBlock(block, nil, err)
970965
return i, err
971966
}
972967
// Process block using the parent state as reference point.
973-
receipts, logs, usedGas, err := bc.processor.Process(block, bc.stateCache, bc.vmConfig)
968+
receipts, logs, usedGas, err := bc.processor.Process(block, state, bc.vmConfig)
974969
if err != nil {
975970
bc.reportBlock(block, receipts, err)
976971
return i, err
977972
}
978973
// Validate the state using the default validator
979-
err = bc.Validator().ValidateState(block, bc.GetBlock(block.ParentHash(), block.NumberU64()-1), bc.stateCache, receipts, usedGas)
974+
err = bc.Validator().ValidateState(block, parent, state, receipts, usedGas)
980975
if err != nil {
981976
bc.reportBlock(block, receipts, err)
982977
return i, err
983978
}
984979
// Write state changes to database
985-
_, err = bc.stateCache.Commit(bc.config.IsEIP158(block.Number()))
986-
if err != nil {
980+
if _, err = state.CommitTo(bc.chainDb, bc.config.IsEIP158(block.Number())); err != nil {
987981
return i, err
988982
}
989983

@@ -1021,7 +1015,7 @@ func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
10211015
return i, err
10221016
}
10231017
// Write hash preimages
1024-
if err := WritePreimages(bc.chainDb, block.NumberU64(), bc.stateCache.Preimages()); err != nil {
1018+
if err := WritePreimages(bc.chainDb, block.NumberU64(), state.Preimages()); err != nil {
10251019
return i, err
10261020
}
10271021
case SideStatTy:

‎core/blockchain_test.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error {
131131
}
132132
return err
133133
}
134-
statedb, err := state.New(blockchain.GetBlockByHash(block.ParentHash()).Root(), blockchain.chainDb)
134+
statedb, err := state.New(blockchain.GetBlockByHash(block.ParentHash()).Root(), blockchain.stateCache)
135135
if err != nil {
136136
return err
137137
}
@@ -148,7 +148,7 @@ func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error {
148148
blockchain.mu.Lock()
149149
WriteTd(blockchain.chainDb, block.Hash(), block.NumberU64(), new(big.Int).Add(block.Difficulty(), blockchain.GetTdByHash(block.ParentHash())))
150150
WriteBlock(blockchain.chainDb, block)
151-
statedb.Commit(false)
151+
statedb.CommitTo(blockchain.chainDb, false)
152152
blockchain.mu.Unlock()
153153
}
154154
return nil
@@ -1131,23 +1131,23 @@ func TestEIP161AccountRemoval(t *testing.T) {
11311131
if _, err := blockchain.InsertChain(types.Blocks{blocks[0]}); err != nil {
11321132
t.Fatal(err)
11331133
}
1134-
if !blockchain.stateCache.Exist(theAddr) {
1134+
if st, _ := blockchain.State(); !st.Exist(theAddr) {
11351135
t.Error("expected account to exist")
11361136
}
11371137

11381138
// account needs to be deleted post eip 161
11391139
if _, err := blockchain.InsertChain(types.Blocks{blocks[1]}); err != nil {
11401140
t.Fatal(err)
11411141
}
1142-
if blockchain.stateCache.Exist(theAddr) {
1142+
if st, _ := blockchain.State(); st.Exist(theAddr) {
11431143
t.Error("account should not exist")
11441144
}
11451145

11461146
// account musn't be created post eip 161
11471147
if _, err := blockchain.InsertChain(types.Blocks{blocks[2]}); err != nil {
11481148
t.Fatal(err)
11491149
}
1150-
if blockchain.stateCache.Exist(theAddr) {
1150+
if st, _ := blockchain.State(); st.Exist(theAddr) {
11511151
t.Error("account should not exist")
11521152
}
11531153
}

‎core/chain_makers.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -181,15 +181,15 @@ func GenerateChain(config *params.ChainConfig, parent *types.Block, db ethdb.Dat
181181
gen(i, b)
182182
}
183183
ethash.AccumulateRewards(statedb, h, b.uncles)
184-
root, err := statedb.Commit(config.IsEIP158(h.Number))
184+
root, err := statedb.CommitTo(db, config.IsEIP158(h.Number))
185185
if err != nil {
186186
panic(fmt.Sprintf("state write error: %v", err))
187187
}
188188
h.Root = root
189189
return types.NewBlock(h, b.txs, b.uncles, b.receipts), b.receipts
190190
}
191191
for i := 0; i < n; i++ {
192-
statedb, err := state.New(parent.Root(), db)
192+
statedb, err := state.New(parent.Root(), state.NewDatabase(db))
193193
if err != nil {
194194
panic(err)
195195
}

‎core/genesis.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
176176
// ToBlock creates the block and state of a genesis specification.
177177
func (g *Genesis) ToBlock() (*types.Block, *state.StateDB) {
178178
db, _ := ethdb.NewMemDatabase()
179-
statedb, _ := state.New(common.Hash{}, db)
179+
statedb, _ := state.New(common.Hash{}, state.NewDatabase(db))
180180
for addr, account := range g.Alloc {
181181
statedb.AddBalance(addr, account.Balance)
182182
statedb.SetCode(addr, account.Code)

0 commit comments

Comments
 (0)