Skip to content

Commit 7e29b0b

Browse files
committed
core/state, trie: add node iterator, test state/trie sync consistency
1 parent 4f28c5b commit 7e29b0b

4 files changed

Lines changed: 451 additions & 11 deletions

File tree

‎core/state/iterator.go‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
// Copyright 2015 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package state
18+
19+
import (
20+
"bytes"
21+
"fmt"
22+
"math/big"
23+
24+
"github.com/ethereum/go-ethereum/common"
25+
"github.com/ethereum/go-ethereum/rlp"
26+
"github.com/ethereum/go-ethereum/trie"
27+
)
28+
29+
// NodeIterator is an iterator to traverse the entire state trie post-order,
30+
// including all of the contract code and contract state tries.
31+
type NodeIterator struct {
32+
state *StateDB // State being iterated
33+
34+
stateIt *trie.NodeIterator // Primary iterator for the global state trie
35+
dataIt *trie.NodeIterator // Secondary iterator for the data trie of a contract
36+
code []byte // Source code associated with a contract
37+
38+
Entry interface{} // Current state entry being iterated (internal representation)
39+
}
40+
41+
// NewNodeIterator creates an post-order state node iterator.
42+
func NewNodeIterator(state *StateDB) *NodeIterator {
43+
return &NodeIterator{
44+
state: state,
45+
}
46+
}
47+
48+
// Next moves the iterator to the next node, returning whether there are any
49+
// further nodes.
50+
func (it *NodeIterator) Next() bool {
51+
it.step()
52+
return it.retrieve()
53+
}
54+
55+
// step moves the iterator to the next entry of the state trie.
56+
func (it *NodeIterator) step() {
57+
// Abort if we reached the end of the iteration
58+
if it.state == nil {
59+
return
60+
}
61+
// Initialize the iterator if we've just started
62+
if it.stateIt == nil {
63+
it.stateIt = trie.NewNodeIterator(it.state.trie.Trie)
64+
}
65+
// If we had data nodes previously, we surely have at least state nodes
66+
if it.dataIt != nil {
67+
if cont := it.dataIt.Next(); !cont {
68+
it.dataIt = nil
69+
}
70+
return
71+
}
72+
// If we had source code previously, discard that
73+
if it.code != nil {
74+
it.code = nil
75+
return
76+
}
77+
// Step to the next state trie node, terminating if we're out of nodes
78+
if cont := it.stateIt.Next(); !cont {
79+
it.state, it.stateIt = nil, nil
80+
return
81+
}
82+
// If the state trie node is an internal entry, leave as is
83+
if !it.stateIt.Leaf {
84+
return
85+
}
86+
// Otherwise we've reached an account node, initiate data iteration
87+
var account struct {
88+
Nonce uint64
89+
Balance *big.Int
90+
Root common.Hash
91+
CodeHash []byte
92+
}
93+
err := rlp.Decode(bytes.NewReader(it.stateIt.LeafBlob), &account)
94+
if err != nil {
95+
panic(err)
96+
}
97+
dataTrie, err := trie.New(account.Root, it.state.db)
98+
if err != nil {
99+
panic(err)
100+
}
101+
it.dataIt = trie.NewNodeIterator(dataTrie)
102+
if !it.dataIt.Next() {
103+
it.dataIt = nil
104+
}
105+
if bytes.Compare(account.CodeHash, emptyCodeHash) != 0 {
106+
it.code, err = it.state.db.Get(account.CodeHash)
107+
if err != nil {
108+
panic(fmt.Sprintf("code %x: %v", account.CodeHash, err))
109+
}
110+
}
111+
}
112+
113+
// retrieve pulls and caches the current state entry the iterator is traversing.
114+
// The method returns whether there are any more data left for inspection.
115+
func (it *NodeIterator) retrieve() bool {
116+
// Clear out any previously set values
117+
it.Entry = nil
118+
119+
// If the iteration's done, return no available data
120+
if it.state == nil {
121+
return false
122+
}
123+
// Otherwise retrieve the current entry
124+
switch {
125+
case it.dataIt != nil:
126+
it.Entry = it.dataIt.Node
127+
case it.code != nil:
128+
it.Entry = it.code
129+
case it.stateIt != nil:
130+
it.Entry = it.stateIt.Node
131+
}
132+
return true
133+
}

‎core/state/sync_test.go‎

Lines changed: 104 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,12 @@ package state
1818

1919
import (
2020
"bytes"
21+
"fmt"
2122
"math/big"
2223
"testing"
2324

2425
"github.com/ethereum/go-ethereum/common"
26+
"github.com/ethereum/go-ethereum/crypto"
2527
"github.com/ethereum/go-ethereum/ethdb"
2628
"github.com/ethereum/go-ethereum/trie"
2729
)
@@ -42,7 +44,7 @@ func makeTestState() (ethdb.Database, common.Hash, []*testAccount) {
4244

4345
// Fill it with some arbitrary data
4446
accounts := []*testAccount{}
45-
for i := byte(0); i < 255; i++ {
47+
for i := byte(0); i < 96; i++ {
4648
obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
4749
acc := &testAccount{address: common.BytesToAddress([]byte{i})}
4850

@@ -61,16 +63,28 @@ func makeTestState() (ethdb.Database, common.Hash, []*testAccount) {
6163
}
6264
root, _ := state.Commit()
6365

66+
// Remove any potentially cached data from the test state creation
67+
trie.ClearGlobalCache()
68+
6469
// Return the generated state
6570
return db, root, accounts
6671
}
6772

6873
// checkStateAccounts cross references a reconstructed state with an expected
6974
// account array.
7075
func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accounts []*testAccount) {
71-
state, _ := New(root, db)
72-
for i, acc := range accounts {
76+
// Remove any potentially cached data from the state synchronisation
77+
trie.ClearGlobalCache()
7378

79+
// Check root availability and state contents
80+
state, err := New(root, db)
81+
if err != nil {
82+
t.Fatalf("failed to create state trie at %x: %v", root, err)
83+
}
84+
if err := checkStateConsistency(db, root); err != nil {
85+
t.Fatalf("inconsistent state trie at %x: %v", root, err)
86+
}
87+
for i, acc := range accounts {
7488
if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
7589
t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
7690
}
@@ -83,6 +97,31 @@ func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accou
8397
}
8498
}
8599

100+
// checkStateConsistency checks that all nodes in a state trie and indeed present.
101+
func checkStateConsistency(db ethdb.Database, root common.Hash) (failure error) {
102+
// Capture any panics by the iterator
103+
defer func() {
104+
if r := recover(); r != nil {
105+
failure = fmt.Errorf("%v", r)
106+
}
107+
}()
108+
// Remove any potentially cached data from the test state creation or previous checks
109+
trie.ClearGlobalCache()
110+
111+
// Create and iterate a state trie rooted in a sub-node
112+
if _, err := db.Get(root.Bytes()); err != nil {
113+
return
114+
}
115+
state, err := New(root, db)
116+
if err != nil {
117+
return
118+
}
119+
it := NewNodeIterator(state)
120+
for it.Next() {
121+
}
122+
return nil
123+
}
124+
86125
// Tests that an empty state is not scheduled for syncing.
87126
func TestEmptyStateSync(t *testing.T) {
88127
empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
@@ -236,3 +275,65 @@ func TestIterativeRandomDelayedStateSync(t *testing.T) {
236275
// Cross check that the two states are in sync
237276
checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
238277
}
278+
279+
// Tests that at any point in time during a sync, only complete sub-tries are in
280+
// the database.
281+
func TestIncompleteStateSync(t *testing.T) {
282+
// Create a random state to copy
283+
srcDb, srcRoot, srcAccounts := makeTestState()
284+
285+
// Create a destination state and sync with the scheduler
286+
dstDb, _ := ethdb.NewMemDatabase()
287+
sched := NewStateSync(srcRoot, dstDb)
288+
289+
added := []common.Hash{}
290+
queue := append([]common.Hash{}, sched.Missing(1)...)
291+
for len(queue) > 0 {
292+
// Fetch a batch of state nodes
293+
results := make([]trie.SyncResult, len(queue))
294+
for i, hash := range queue {
295+
data, err := srcDb.Get(hash.Bytes())
296+
if err != nil {
297+
t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
298+
}
299+
results[i] = trie.SyncResult{hash, data}
300+
}
301+
// Process each of the state nodes
302+
if index, err := sched.Process(results); err != nil {
303+
t.Fatalf("failed to process result #%d: %v", index, err)
304+
}
305+
for _, result := range results {
306+
added = append(added, result.Hash)
307+
}
308+
// Check that all known sub-tries in the synced state is complete
309+
for _, root := range added {
310+
// Skim through the accounts and make sure the root hash is not a code node
311+
codeHash := false
312+
for _, acc := range srcAccounts {
313+
if bytes.Compare(root.Bytes(), crypto.Sha3(acc.code)) == 0 {
314+
codeHash = true
315+
break
316+
}
317+
}
318+
// If the root is a real trie node, check consistency
319+
if !codeHash {
320+
if err := checkStateConsistency(dstDb, root); err != nil {
321+
t.Fatalf("state inconsistent: %v", err)
322+
}
323+
}
324+
}
325+
// Fetch the next batch to retrieve
326+
queue = append(queue[:0], sched.Missing(1)...)
327+
}
328+
// Sanity check that removing any node from the database is detected
329+
for _, node := range added[1:] {
330+
key := node.Bytes()
331+
value, _ := dstDb.Get(key)
332+
333+
dstDb.Delete(key)
334+
if err := checkStateConsistency(dstDb, added[0]); err == nil {
335+
t.Fatalf("trie inconsistency not caught, missing: %x", key)
336+
}
337+
dstDb.Put(key, value)
338+
}
339+
}

0 commit comments

Comments
 (0)