Skip to content

Commit 26d271d

Browse files
authored
core/state/snapshot: implement storage iterator (#20971)
* core/state/snapshot: implement storage iterator * core/state/snapshot, tests: implement helper function * core/state/snapshot: fix storage issue If an account is deleted in the tx_1 but recreated in the tx_2, the it can happen that in this diff layer, both destructedSet and storageData records this account. In this case, the storage iterator should be able to iterate the slots belong to new account but disable further iteration in deeper layers(belong to old account) * core/state/snapshot: address peter and martin's comment * core/state: address comments * core/state/snapshot: fix test
1 parent 1264c19 commit 26d271d

13 files changed

Lines changed: 1088 additions & 196 deletions

‎core/state/snapshot/account.go‎

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,18 +24,19 @@ import (
2424
"github.com/ethereum/go-ethereum/rlp"
2525
)
2626

27-
// Account is a slim version of a state.Account, where the root and code hash
28-
// are replaced with a nil byte slice for empty accounts.
27+
// Account is a modified version of a state.Account, where the root is replaced
28+
// with a byte slice. This format can be used to represent full-consensus format
29+
// or slim-snapshot format which replaces the empty root and code hash as nil
30+
// byte slice.
2931
type Account struct {
3032
Nonce uint64
3133
Balance *big.Int
3234
Root []byte
3335
CodeHash []byte
3436
}
3537

36-
// AccountRLP converts a state.Account content into a slim snapshot version RLP
37-
// encoded.
38-
func AccountRLP(nonce uint64, balance *big.Int, root common.Hash, codehash []byte) []byte {
38+
// SlimAccount converts a state.Account content into a slim snapshot account
39+
func SlimAccount(nonce uint64, balance *big.Int, root common.Hash, codehash []byte) Account {
3940
slim := Account{
4041
Nonce: nonce,
4142
Balance: balance,
@@ -46,9 +47,40 @@ func AccountRLP(nonce uint64, balance *big.Int, root common.Hash, codehash []byt
4647
if !bytes.Equal(codehash, emptyCode[:]) {
4748
slim.CodeHash = codehash
4849
}
49-
data, err := rlp.EncodeToBytes(slim)
50+
return slim
51+
}
52+
53+
// SlimAccountRLP converts a state.Account content into a slim snapshot
54+
// version RLP encoded.
55+
func SlimAccountRLP(nonce uint64, balance *big.Int, root common.Hash, codehash []byte) []byte {
56+
data, err := rlp.EncodeToBytes(SlimAccount(nonce, balance, root, codehash))
5057
if err != nil {
5158
panic(err)
5259
}
5360
return data
5461
}
62+
63+
// FullAccount decodes the data on the 'slim RLP' format and return
64+
// the consensus format account.
65+
func FullAccount(data []byte) (Account, error) {
66+
var account Account
67+
if err := rlp.DecodeBytes(data, &account); err != nil {
68+
return Account{}, err
69+
}
70+
if len(account.Root) == 0 {
71+
account.Root = emptyRoot[:]
72+
}
73+
if len(account.CodeHash) == 0 {
74+
account.CodeHash = emptyCode[:]
75+
}
76+
return account, nil
77+
}
78+
79+
// FullAccountRLP converts data on the 'slim RLP' format into the full RLP-format.
80+
func FullAccountRLP(data []byte) ([]byte, error) {
81+
account, err := FullAccount(data)
82+
if err != nil {
83+
return nil, err
84+
}
85+
return rlp.EncodeToBytes(account)
86+
}

‎core/state/snapshot/conversion.go‎

Lines changed: 213 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
package snapshot
1818

1919
import (
20+
"bytes"
21+
"fmt"
2022
"sync"
2123
"time"
2224

@@ -27,80 +29,239 @@ import (
2729
"github.com/ethereum/go-ethereum/trie"
2830
)
2931

30-
// conversionAccount is used for converting between full and slim format. When
31-
// doing this, we can consider 'balance' as a byte array, as it has already
32-
// been converted from big.Int into an rlp-byteslice.
33-
type conversionAccount struct {
34-
Nonce uint64
35-
Balance []byte
36-
Root []byte
37-
CodeHash []byte
32+
// trieKV represents a trie key-value pair
33+
type trieKV struct {
34+
key common.Hash
35+
value []byte
36+
}
37+
38+
type (
39+
// trieGeneratorFn is the interface of trie generation which can
40+
// be implemented by different trie algorithm.
41+
trieGeneratorFn func(in chan (trieKV), out chan (common.Hash))
42+
43+
// leafCallbackFn is the callback invoked at the leaves of the trie,
44+
// returns the subtrie root with the specified subtrie identifier.
45+
leafCallbackFn func(hash common.Hash, stat *generateStats) common.Hash
46+
)
47+
48+
// GenerateAccountTrieRoot takes an account iterator and reproduces the root hash.
49+
func GenerateAccountTrieRoot(it AccountIterator) (common.Hash, error) {
50+
return generateTrieRoot(it, common.Hash{}, stdGenerate, nil, &generateStats{start: time.Now()}, true)
51+
}
52+
53+
// GenerateStorageTrieRoot takes a storage iterator and reproduces the root hash.
54+
func GenerateStorageTrieRoot(account common.Hash, it StorageIterator) (common.Hash, error) {
55+
return generateTrieRoot(it, account, stdGenerate, nil, &generateStats{start: time.Now()}, true)
3856
}
3957

40-
// SlimToFull converts data on the 'slim RLP' format into the full RLP-format
41-
func SlimToFull(data []byte) ([]byte, error) {
42-
acc := &conversionAccount{}
43-
if err := rlp.DecodeBytes(data, acc); err != nil {
44-
return nil, err
58+
// VerifyState takes the whole snapshot tree as the input, traverses all the accounts
59+
// as well as the corresponding storages and compares the re-computed hash with the
60+
// original one(state root and the storage root).
61+
func VerifyState(snaptree *Tree, root common.Hash) error {
62+
acctIt, err := snaptree.AccountIterator(root, common.Hash{})
63+
if err != nil {
64+
return err
4565
}
46-
if len(acc.Root) == 0 {
47-
acc.Root = emptyRoot[:]
66+
got, err := generateTrieRoot(acctIt, common.Hash{}, stdGenerate, func(account common.Hash, stat *generateStats) common.Hash {
67+
storageIt, err := snaptree.StorageIterator(root, account, common.Hash{})
68+
if err != nil {
69+
return common.Hash{}
70+
}
71+
hash, err := generateTrieRoot(storageIt, account, stdGenerate, nil, stat, false)
72+
if err != nil {
73+
return common.Hash{}
74+
}
75+
return hash
76+
}, &generateStats{start: time.Now()}, true)
77+
78+
if err != nil {
79+
return err
4880
}
49-
if len(acc.CodeHash) == 0 {
50-
acc.CodeHash = emptyCode[:]
81+
if got != root {
82+
return fmt.Errorf("State root hash mismatch, got %x, want %x", got, root)
5183
}
52-
fullData, err := rlp.EncodeToBytes(acc)
53-
if err != nil {
54-
return nil, err
84+
return nil
85+
}
86+
87+
// generateStats is a collection of statistics gathered by the trie generator
88+
// for logging purposes.
89+
type generateStats struct {
90+
accounts uint64
91+
slots uint64
92+
curAccount common.Hash
93+
curSlot common.Hash
94+
start time.Time
95+
lock sync.RWMutex
96+
}
97+
98+
// progress records the progress trie generator made recently.
99+
func (stat *generateStats) progress(accounts, slots uint64, curAccount common.Hash, curSlot common.Hash) {
100+
stat.lock.Lock()
101+
defer stat.lock.Unlock()
102+
103+
stat.accounts += accounts
104+
stat.slots += slots
105+
if curAccount != (common.Hash{}) {
106+
stat.curAccount = curAccount
107+
}
108+
if curSlot != (common.Hash{}) {
109+
stat.curSlot = curSlot
55110
}
56-
return fullData, nil
57111
}
58112

59-
// trieKV represents a trie key-value pair
60-
type trieKV struct {
61-
key common.Hash
62-
value []byte
113+
// report prints the cumulative progress statistic smartly.
114+
func (stat *generateStats) report() {
115+
stat.lock.RLock()
116+
defer stat.lock.RUnlock()
117+
118+
var ctx []interface{}
119+
if stat.curSlot != (common.Hash{}) {
120+
ctx = append(ctx, []interface{}{
121+
"in", stat.curAccount,
122+
"at", stat.curSlot,
123+
}...)
124+
} else {
125+
ctx = append(ctx, []interface{}{"at", stat.curAccount}...)
126+
}
127+
// Add the usual measurements
128+
ctx = append(ctx, []interface{}{"accounts", stat.accounts}...)
129+
if stat.slots != 0 {
130+
ctx = append(ctx, []interface{}{"slots", stat.slots}...)
131+
}
132+
ctx = append(ctx, []interface{}{"elapsed", common.PrettyDuration(time.Since(stat.start))}...)
133+
log.Info("Generating trie hash from snapshot", ctx...)
63134
}
64135

65-
type trieGeneratorFn func(in chan (trieKV), out chan (common.Hash))
136+
// reportDone prints the last log when the whole generation is finished.
137+
func (stat *generateStats) reportDone() {
138+
stat.lock.RLock()
139+
defer stat.lock.RUnlock()
66140

67-
// GenerateTrieRoot takes an account iterator and reproduces the root hash.
68-
func GenerateTrieRoot(it AccountIterator) common.Hash {
69-
return generateTrieRoot(it, stdGenerate)
141+
var ctx []interface{}
142+
ctx = append(ctx, []interface{}{"accounts", stat.accounts}...)
143+
if stat.slots != 0 {
144+
ctx = append(ctx, []interface{}{"slots", stat.slots}...)
145+
}
146+
ctx = append(ctx, []interface{}{"elapsed", common.PrettyDuration(time.Since(stat.start))}...)
147+
log.Info("Generated trie hash from snapshot", ctx...)
70148
}
71149

72-
func generateTrieRoot(it AccountIterator, generatorFn trieGeneratorFn) common.Hash {
150+
// generateTrieRoot generates the trie hash based on the snapshot iterator.
151+
// It can be used for generating account trie, storage trie or even the
152+
// whole state which connects the accounts and the corresponding storages.
153+
func generateTrieRoot(it Iterator, account common.Hash, generatorFn trieGeneratorFn, leafCallback leafCallbackFn, stats *generateStats, report bool) (common.Hash, error) {
73154
var (
74-
in = make(chan trieKV) // chan to pass leaves
75-
out = make(chan common.Hash) // chan to collect result
76-
wg sync.WaitGroup
155+
in = make(chan trieKV) // chan to pass leaves
156+
out = make(chan common.Hash, 1) // chan to collect result
157+
stoplog = make(chan bool, 1) // 1-size buffer, works when logging is not enabled
158+
wg sync.WaitGroup
77159
)
160+
// Spin up a go-routine for trie hash re-generation
78161
wg.Add(1)
79162
go func() {
163+
defer wg.Done()
80164
generatorFn(in, out)
81-
wg.Done()
82165
}()
83-
// Feed leaves
84-
start := time.Now()
85-
logged := time.Now()
86-
accounts := 0
166+
167+
// Spin up a go-routine for progress logging
168+
if report && stats != nil {
169+
wg.Add(1)
170+
go func() {
171+
defer wg.Done()
172+
173+
timer := time.NewTimer(0)
174+
defer timer.Stop()
175+
176+
for {
177+
select {
178+
case <-timer.C:
179+
stats.report()
180+
timer.Reset(time.Second * 8)
181+
case success := <-stoplog:
182+
if success {
183+
stats.reportDone()
184+
}
185+
return
186+
}
187+
}
188+
}()
189+
}
190+
// stop is a helper function to shutdown the background threads
191+
// and return the re-generated trie hash.
192+
stop := func(success bool) common.Hash {
193+
close(in)
194+
result := <-out
195+
stoplog <- success
196+
wg.Wait()
197+
return result
198+
}
199+
var (
200+
logged = time.Now()
201+
processed = uint64(0)
202+
leaf trieKV
203+
last common.Hash
204+
)
205+
// Start to feed leaves
87206
for it.Next() {
88-
slimData := it.Account()
89-
fullData, _ := SlimToFull(slimData)
90-
l := trieKV{it.Hash(), fullData}
91-
in <- l
92-
if time.Since(logged) > 8*time.Second {
93-
log.Info("Generating trie hash from snapshot",
94-
"at", l.key, "accounts", accounts, "elapsed", time.Since(start))
95-
logged = time.Now()
207+
if account == (common.Hash{}) {
208+
var (
209+
err error
210+
fullData []byte
211+
)
212+
if leafCallback == nil {
213+
fullData, err = FullAccountRLP(it.(AccountIterator).Account())
214+
if err != nil {
215+
stop(false)
216+
return common.Hash{}, err
217+
}
218+
} else {
219+
account, err := FullAccount(it.(AccountIterator).Account())
220+
if err != nil {
221+
stop(false)
222+
return common.Hash{}, err
223+
}
224+
// Apply the leaf callback. Normally the callback is used to traverse
225+
// the storage trie and re-generate the subtrie root.
226+
subroot := leafCallback(it.Hash(), stats)
227+
if !bytes.Equal(account.Root, subroot.Bytes()) {
228+
stop(false)
229+
return common.Hash{}, fmt.Errorf("invalid subroot(%x), want %x, got %x", it.Hash(), account.Root, subroot)
230+
}
231+
fullData, err = rlp.EncodeToBytes(account)
232+
if err != nil {
233+
stop(false)
234+
return common.Hash{}, err
235+
}
236+
}
237+
leaf = trieKV{it.Hash(), fullData}
238+
} else {
239+
leaf = trieKV{it.Hash(), common.CopyBytes(it.(StorageIterator).Slot())}
240+
}
241+
in <- leaf
242+
243+
// Accumulate the generaation statistic if it's required.
244+
processed++
245+
if time.Since(logged) > 3*time.Second && stats != nil {
246+
if account == (common.Hash{}) {
247+
stats.progress(processed, 0, it.Hash(), common.Hash{})
248+
} else {
249+
stats.progress(0, processed, account, it.Hash())
250+
}
251+
logged, processed = time.Now(), 0
252+
}
253+
last = it.Hash()
254+
}
255+
// Commit the last part statistic.
256+
if processed > 0 && stats != nil {
257+
if account == (common.Hash{}) {
258+
stats.progress(processed, 0, last, common.Hash{})
259+
} else {
260+
stats.progress(0, processed, account, last)
96261
}
97-
accounts++
98262
}
99-
close(in)
100-
result := <-out
101-
log.Info("Generated trie hash from snapshot", "accounts", accounts, "elapsed", time.Since(start))
102-
wg.Wait()
103-
return result
263+
result := stop(true)
264+
return result, nil
104265
}
105266

106267
// stdGenerate is a very basic hexary trie builder which uses the same Trie

0 commit comments

Comments
 (0)