Skip to content

Commit a4cf279

Browse files
committed
core/state: extend snapshotter to handle account resurrections
1 parent 6e05ccd commit a4cf279

12 files changed

Lines changed: 366 additions & 252 deletions

‎core/blockchain.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
198198
TrieDirtyLimit: 256,
199199
TrieTimeLimit: 5 * time.Minute,
200200
SnapshotLimit: 256,
201+
SnapshotWait: true,
201202
}
202203
}
203204
bodyCache, _ := lru.New(bodyCacheLimit)

‎core/blockchain_test.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2315,7 +2315,7 @@ func TestDeleteCreateRevert(t *testing.T) {
23152315
// The address 0xAAAAA selfdestructs if called
23162316
aa: {
23172317
// Code needs to just selfdestruct
2318-
Code: []byte{byte(vm.PC), 0xFF},
2318+
Code: []byte{byte(vm.PC), byte(vm.SELFDESTRUCT)},
23192319
Nonce: 1,
23202320
Balance: big.NewInt(0),
23212321
},
@@ -2382,8 +2382,8 @@ func TestDeleteRecreateSlots(t *testing.T) {
23822382

23832383
aa = common.HexToAddress("0x7217d81b76bdd8707601e959454e3d776aee5f43")
23842384
bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")
2385-
aaStorage = make(map[common.Hash]common.Hash) // Initial storage in AA
2386-
aaCode = []byte{byte(vm.PC), 0xFF} // Code for AA (simple selfdestruct)
2385+
aaStorage = make(map[common.Hash]common.Hash) // Initial storage in AA
2386+
aaCode = []byte{byte(vm.PC), byte(vm.SELFDESTRUCT)} // Code for AA (simple selfdestruct)
23872387
)
23882388
// Populate two slots
23892389
aaStorage[common.HexToHash("01")] = common.HexToHash("01")
@@ -2506,8 +2506,8 @@ func TestDeleteRecreateAccount(t *testing.T) {
25062506
funds = big.NewInt(1000000000)
25072507

25082508
aa = common.HexToAddress("0x7217d81b76bdd8707601e959454e3d776aee5f43")
2509-
aaStorage = make(map[common.Hash]common.Hash) // Initial storage in AA
2510-
aaCode = []byte{byte(vm.PC), 0xFF} // Code for AA (simple selfdestruct)
2509+
aaStorage = make(map[common.Hash]common.Hash) // Initial storage in AA
2510+
aaCode = []byte{byte(vm.PC), byte(vm.SELFDESTRUCT)} // Code for AA (simple selfdestruct)
25112511
)
25122512
// Populate two slots
25132513
aaStorage[common.HexToHash("01")] = common.HexToHash("01")

‎core/state/snapshot/difflayer.go‎

Lines changed: 93 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ import (
2727
"time"
2828

2929
"github.com/ethereum/go-ethereum/common"
30-
"github.com/ethereum/go-ethereum/log"
3130
"github.com/ethereum/go-ethereum/rlp"
3231
"github.com/steakknife/bloomfilter"
3332
)
@@ -68,17 +67,28 @@ var (
6867
// entry count).
6968
bloomFuncs = math.Round((bloomSize / float64(aggregatorItemLimit)) * math.Log(2))
7069

71-
// bloomHashesOffset is a runtime constant which determines which part of the
70+
// the bloom offsets are runtime constants which determines which part of the
7271
// the account/storage hash the hasher functions looks at, to determine the
7372
// bloom key for an account/slot. This is randomized at init(), so that the
7473
// global population of nodes do not all display the exact same behaviour with
7574
// regards to bloom content
76-
bloomHasherOffset = 0
75+
bloomDestructHasherOffset = 0
76+
bloomAccountHasherOffset = 0
77+
bloomStorageHasherOffset = 0
7778
)
7879

7980
func init() {
80-
// Init bloomHasherOffset in the range [0:24] (requires 8 bytes)
81-
bloomHasherOffset = rand.Intn(25)
81+
// Init the bloom offsets in the range [0:24] (requires 8 bytes)
82+
bloomDestructHasherOffset = rand.Intn(25)
83+
bloomAccountHasherOffset = rand.Intn(25)
84+
bloomStorageHasherOffset = rand.Intn(25)
85+
86+
// The destruct and account blooms must be different, as the storage slots
87+
// will check for destruction too for every bloom miss. It should not collide
88+
// with modified accounts.
89+
for bloomAccountHasherOffset == bloomDestructHasherOffset {
90+
bloomAccountHasherOffset = rand.Intn(25)
91+
}
8292
}
8393

8494
// diffLayer represents a collection of modifications made to a state snapshot
@@ -95,6 +105,7 @@ type diffLayer struct {
95105
root common.Hash // Root hash to which this snapshot diff belongs to
96106
stale uint32 // Signals that the layer became stale (state progressed)
97107

108+
destructSet map[common.Hash]struct{} // Keyed markers for deleted (and potentially) recreated accounts
98109
accountList []common.Hash // List of account for iteration. If it exists, it's sorted, otherwise it's nil
99110
accountData map[common.Hash][]byte // Keyed accounts for direct retrival (nil means deleted)
100111
storageList map[common.Hash][]common.Hash // List of storage slots for iterated retrievals, one per account. Any existing lists are sorted if non-nil
@@ -105,6 +116,20 @@ type diffLayer struct {
105116
lock sync.RWMutex
106117
}
107118

119+
// destructBloomHasher is a wrapper around a common.Hash to satisfy the interface
120+
// API requirements of the bloom library used. It's used to convert a destruct
121+
// event into a 64 bit mini hash.
122+
type destructBloomHasher common.Hash
123+
124+
func (h destructBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") }
125+
func (h destructBloomHasher) Sum(b []byte) []byte { panic("not implemented") }
126+
func (h destructBloomHasher) Reset() { panic("not implemented") }
127+
func (h destructBloomHasher) BlockSize() int { panic("not implemented") }
128+
func (h destructBloomHasher) Size() int { return 8 }
129+
func (h destructBloomHasher) Sum64() uint64 {
130+
return binary.BigEndian.Uint64(h[bloomDestructHasherOffset : bloomDestructHasherOffset+8])
131+
}
132+
108133
// accountBloomHasher is a wrapper around a common.Hash to satisfy the interface
109134
// API requirements of the bloom library used. It's used to convert an account
110135
// hash into a 64 bit mini hash.
@@ -116,7 +141,7 @@ func (h accountBloomHasher) Reset() { panic("not impl
116141
func (h accountBloomHasher) BlockSize() int { panic("not implemented") }
117142
func (h accountBloomHasher) Size() int { return 8 }
118143
func (h accountBloomHasher) Sum64() uint64 {
119-
return binary.BigEndian.Uint64(h[bloomHasherOffset : bloomHasherOffset+8])
144+
return binary.BigEndian.Uint64(h[bloomAccountHasherOffset : bloomAccountHasherOffset+8])
120145
}
121146

122147
// storageBloomHasher is a wrapper around a [2]common.Hash to satisfy the interface
@@ -130,17 +155,18 @@ func (h storageBloomHasher) Reset() { panic("not impl
130155
func (h storageBloomHasher) BlockSize() int { panic("not implemented") }
131156
func (h storageBloomHasher) Size() int { return 8 }
132157
func (h storageBloomHasher) Sum64() uint64 {
133-
return binary.BigEndian.Uint64(h[0][bloomHasherOffset:bloomHasherOffset+8]) ^
134-
binary.BigEndian.Uint64(h[1][bloomHasherOffset:bloomHasherOffset+8])
158+
return binary.BigEndian.Uint64(h[0][bloomStorageHasherOffset:bloomStorageHasherOffset+8]) ^
159+
binary.BigEndian.Uint64(h[1][bloomStorageHasherOffset:bloomStorageHasherOffset+8])
135160
}
136161

137162
// newDiffLayer creates a new diff on top of an existing snapshot, whether that's a low
138163
// level persistent database or a hierarchical diff already.
139-
func newDiffLayer(parent snapshot, root common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer {
164+
func newDiffLayer(parent snapshot, root common.Hash, destructs map[common.Hash]struct{}, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer {
140165
// Create the new layer with some pre-allocated data segments
141166
dl := &diffLayer{
142167
parent: parent,
143168
root: root,
169+
destructSet: destructs,
144170
accountData: accounts,
145171
storageData: storage,
146172
}
@@ -152,31 +178,29 @@ func newDiffLayer(parent snapshot, root common.Hash, accounts map[common.Hash][]
152178
default:
153179
panic("unknown parent type")
154180
}
181+
// Sanity check that accounts or storage slots are never nil
182+
for accountHash, blob := range accounts {
183+
if blob == nil {
184+
panic(fmt.Sprintf("account %#x nil", accountHash))
185+
}
186+
}
187+
for accountHash, slots := range storage {
188+
if slots == nil {
189+
panic(fmt.Sprintf("storage %#x nil", accountHash))
190+
}
191+
}
155192
// Determine memory size and track the dirty writes
156193
for _, data := range accounts {
157194
dl.memory += uint64(common.HashLength + len(data))
158195
snapshotDirtyAccountWriteMeter.Mark(int64(len(data)))
159196
}
160197
// Fill the storage hashes and sort them for the iterator
161198
dl.storageList = make(map[common.Hash][]common.Hash)
162-
163-
for accountHash, slots := range storage {
164-
// If the slots are nil, sanity check that it's a deleted account
165-
if slots == nil {
166-
// Ensure that the account was just marked as deleted
167-
if account, ok := accounts[accountHash]; account != nil || !ok {
168-
panic(fmt.Sprintf("storage in %#x nil, but account conflicts (%#x, exists: %v)", accountHash, account, ok))
169-
}
170-
// Everything ok, store the deletion mark and continue
171-
dl.storageList[accountHash] = nil
172-
continue
173-
}
174-
// Storage slots are not nil so entire contract was not deleted, ensure the
175-
// account was just updated.
176-
if account, ok := accounts[accountHash]; account == nil || !ok {
177-
log.Error(fmt.Sprintf("storage in %#x exists, but account nil (exists: %v)", accountHash, ok))
178-
}
179-
// Determine memory size and track the dirty writes
199+
for accountHash := range destructs {
200+
dl.storageList[accountHash] = nil
201+
}
202+
// Determine memory size and track the dirty writes
203+
for _, slots := range storage {
180204
for _, data := range slots {
181205
dl.memory += uint64(common.HashLength + len(data))
182206
snapshotDirtyStorageWriteMeter.Mark(int64(len(data)))
@@ -208,6 +232,9 @@ func (dl *diffLayer) rebloom(origin *diskLayer) {
208232
dl.diffed, _ = bloomfilter.New(uint64(bloomSize), uint64(bloomFuncs))
209233
}
210234
// Iterate over all the accounts and storage slots and index them
235+
for hash := range dl.destructSet {
236+
dl.diffed.Add(destructBloomHasher(hash))
237+
}
211238
for hash := range dl.accountData {
212239
dl.diffed.Add(accountBloomHasher(hash))
213240
}
@@ -265,6 +292,9 @@ func (dl *diffLayer) AccountRLP(hash common.Hash) ([]byte, error) {
265292
// all the maps in all the layers below
266293
dl.lock.RLock()
267294
hit := dl.diffed.Contains(accountBloomHasher(hash))
295+
if !hit {
296+
hit = dl.diffed.Contains(destructBloomHasher(hash))
297+
}
268298
dl.lock.RUnlock()
269299

270300
// If the bloom filter misses, don't even bother with traversing the memory
@@ -289,19 +319,22 @@ func (dl *diffLayer) accountRLP(hash common.Hash, depth int) ([]byte, error) {
289319
if dl.Stale() {
290320
return nil, ErrSnapshotStale
291321
}
292-
// If the account is known locally, return it. Note, a nil account means it was
293-
// deleted, and is a different notion than an unknown account!
322+
// If the account is known locally, return it
294323
if data, ok := dl.accountData[hash]; ok {
295324
snapshotDirtyAccountHitMeter.Mark(1)
296325
snapshotDirtyAccountHitDepthHist.Update(int64(depth))
297-
if n := len(data); n > 0 {
298-
snapshotDirtyAccountReadMeter.Mark(int64(n))
299-
} else {
300-
snapshotDirtyAccountInexMeter.Mark(1)
301-
}
326+
snapshotDirtyAccountReadMeter.Mark(int64(len(data)))
302327
snapshotBloomAccountTrueHitMeter.Mark(1)
303328
return data, nil
304329
}
330+
// If the account is known locally, but deleted, return it
331+
if _, ok := dl.destructSet[hash]; ok {
332+
snapshotDirtyAccountHitMeter.Mark(1)
333+
snapshotDirtyAccountHitDepthHist.Update(int64(depth))
334+
snapshotDirtyAccountInexMeter.Mark(1)
335+
snapshotBloomAccountTrueHitMeter.Mark(1)
336+
return nil, nil
337+
}
305338
// Account unknown to this diff, resolve from parent
306339
if diff, ok := dl.parent.(*diffLayer); ok {
307340
return diff.accountRLP(hash, depth+1)
@@ -319,6 +352,9 @@ func (dl *diffLayer) Storage(accountHash, storageHash common.Hash) ([]byte, erro
319352
// all the maps in all the layers below
320353
dl.lock.RLock()
321354
hit := dl.diffed.Contains(storageBloomHasher{accountHash, storageHash})
355+
if !hit {
356+
hit = dl.diffed.Contains(destructBloomHasher(accountHash))
357+
}
322358
dl.lock.RUnlock()
323359

324360
// If the bloom filter misses, don't even bother with traversing the memory
@@ -343,16 +379,8 @@ func (dl *diffLayer) storage(accountHash, storageHash common.Hash, depth int) ([
343379
if dl.Stale() {
344380
return nil, ErrSnapshotStale
345381
}
346-
// If the account is known locally, try to resolve the slot locally. Note, a nil
347-
// account means it was deleted, and is a different notion than an unknown account!
382+
// If the account is known locally, try to resolve the slot locally
348383
if storage, ok := dl.storageData[accountHash]; ok {
349-
if storage == nil {
350-
snapshotDirtyStorageHitMeter.Mark(1)
351-
snapshotDirtyStorageHitDepthHist.Update(int64(depth))
352-
snapshotDirtyStorageInexMeter.Mark(1)
353-
snapshotBloomStorageTrueHitMeter.Mark(1)
354-
return nil, nil
355-
}
356384
if data, ok := storage[storageHash]; ok {
357385
snapshotDirtyStorageHitMeter.Mark(1)
358386
snapshotDirtyStorageHitDepthHist.Update(int64(depth))
@@ -365,6 +393,14 @@ func (dl *diffLayer) storage(accountHash, storageHash common.Hash, depth int) ([
365393
return data, nil
366394
}
367395
}
396+
// If the account is known locally, but deleted, return an empty slot
397+
if _, ok := dl.destructSet[accountHash]; ok {
398+
snapshotDirtyStorageHitMeter.Mark(1)
399+
snapshotDirtyStorageHitDepthHist.Update(int64(depth))
400+
snapshotDirtyStorageInexMeter.Mark(1)
401+
snapshotBloomStorageTrueHitMeter.Mark(1)
402+
return nil, nil
403+
}
368404
// Storage slot unknown to this diff, resolve from parent
369405
if diff, ok := dl.parent.(*diffLayer); ok {
370406
return diff.storage(accountHash, storageHash, depth+1)
@@ -376,8 +412,8 @@ func (dl *diffLayer) storage(accountHash, storageHash common.Hash, depth int) ([
376412

377413
// Update creates a new layer on top of the existing snapshot diff tree with
378414
// the specified data items.
379-
func (dl *diffLayer) Update(blockRoot common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer {
380-
return newDiffLayer(dl, blockRoot, accounts, storage)
415+
func (dl *diffLayer) Update(blockRoot common.Hash, destructs map[common.Hash]struct{}, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer {
416+
return newDiffLayer(dl, blockRoot, destructs, accounts, storage)
381417
}
382418

383419
// flatten pushes all data from this point downwards, flattening everything into
@@ -403,14 +439,18 @@ func (dl *diffLayer) flatten() snapshot {
403439
panic("parent diff layer is stale") // we've flattened into the same parent from two children, boo
404440
}
405441
// Overwrite all the updated accounts blindly, merge the sorted list
442+
for hash := range dl.destructSet {
443+
parent.destructSet[hash] = struct{}{}
444+
delete(parent.accountData, hash)
445+
delete(parent.storageData, hash)
446+
}
406447
for hash, data := range dl.accountData {
407448
parent.accountData[hash] = data
408449
}
409450
// Overwrite all the updated storage slots (individually)
410451
for accountHash, storage := range dl.storageData {
411-
// If storage didn't exist (or was deleted) in the parent; or if the storage
412-
// was freshly deleted in the child, overwrite blindly
413-
if parent.storageData[accountHash] == nil || storage == nil {
452+
// If storage didn't exist (or was deleted) in the parent, overwrite blindly
453+
if _, ok := parent.storageData[accountHash]; !ok {
414454
parent.storageData[accountHash] = storage
415455
continue
416456
}
@@ -426,6 +466,7 @@ func (dl *diffLayer) flatten() snapshot {
426466
parent: parent.parent,
427467
origin: parent.origin,
428468
root: dl.root,
469+
destructSet: parent.destructSet,
429470
accountData: parent.accountData,
430471
storageData: parent.storageData,
431472
storageList: make(map[common.Hash][]common.Hash),
@@ -451,7 +492,10 @@ func (dl *diffLayer) AccountList() []common.Hash {
451492
dl.lock.Lock()
452493
defer dl.lock.Unlock()
453494

454-
dl.accountList = make([]common.Hash, 0, len(dl.accountData))
495+
dl.accountList = make([]common.Hash, 0, len(dl.destructSet)+len(dl.accountData))
496+
for hash := range dl.destructSet {
497+
dl.accountList = append(dl.accountList, hash)
498+
}
455499
for hash := range dl.accountData {
456500
dl.accountList = append(dl.accountList, hash)
457501
}

0 commit comments

Comments
 (0)