@@ -40,13 +40,12 @@ type diffLayer struct {
4040
4141 number uint64 // Block number to which this snapshot diff belongs to
4242 root common.Hash // Root hash to which this snapshot diff belongs to
43+ stale bool // Signals that the layer became stale (state progressed)
4344
44- accountList []common.Hash // List of account for iteration, might not be sorted yet (lazy)
45- accountSorted bool // Flag whether the account list has alreayd been sorted or not
46- accountData map [common.Hash ][]byte // Keyed accounts for direct retrival (nil means deleted)
47- storageList map [common.Hash ][]common.Hash // List of storage slots for iterated retrievals, one per account
48- storageSorted map [common.Hash ]bool // Flag whether the storage slot list has alreayd been sorted or not
49- storageData map [common.Hash ]map [common.Hash ][]byte // Keyed storage slots for direct retrival. one per account (nil means deleted)
45+ accountList []common.Hash // List of account for iteration. If it exists, it's sorted, otherwise it's nil
46+ accountData map [common.Hash ][]byte // Keyed accounts for direct retrival (nil means deleted)
47+ storageList map [common.Hash ][]common.Hash // List of storage slots for iterated retrievals, one per account. Any existing lists are sorted if non-nil
48+ storageData map [common.Hash ]map [common.Hash ][]byte // Keyed storage slots for direct retrival. one per account (nil means deleted)
5049
5150 lock sync.RWMutex
5251}
@@ -62,21 +61,13 @@ func newDiffLayer(parent snapshot, number uint64, root common.Hash, accounts map
6261 accountData : accounts ,
6362 storageData : storage ,
6463 }
65- // Fill the account hashes and sort them for the iterator
66- accountList := make ([]common.Hash , 0 , len (accounts ))
67- for hash , data := range accounts {
68- accountList = append (accountList , hash )
64+ // Determine mem size
65+ for _ , data := range accounts {
6966 dl .memory += uint64 (len (data ))
7067 }
71- sort .Sort (hashes (accountList ))
72- dl .accountList = accountList
73- dl .accountSorted = true
74-
75- dl .memory += uint64 (len (dl .accountList ) * common .HashLength )
7668
7769 // Fill the storage hashes and sort them for the iterator
78- dl .storageList = make (map [common.Hash ][]common.Hash , len (storage ))
79- dl .storageSorted = make (map [common.Hash ]bool , len (storage ))
70+ dl .storageList = make (map [common.Hash ][]common.Hash )
8071
8172 for accountHash , slots := range storage {
8273 // If the slots are nil, sanity check that it's a deleted account
@@ -93,19 +84,11 @@ func newDiffLayer(parent snapshot, number uint64, root common.Hash, accounts map
9384 // account was just updated.
9485 if account , ok := accounts [accountHash ]; account == nil || ! ok {
9586 log .Error (fmt .Sprintf ("storage in %#x exists, but account nil (exists: %v)" , accountHash , ok ))
96- //panic(fmt.Sprintf("storage in %#x exists, but account nil (exists: %v)", accountHash, ok))
9787 }
98- // Fill the storage hashes for this account and sort them for the iterator
99- storageList := make ([]common.Hash , 0 , len (slots ))
100- for storageHash , data := range slots {
101- storageList = append (storageList , storageHash )
88+ // Determine mem size
89+ for _ , data := range slots {
10290 dl .memory += uint64 (len (data ))
10391 }
104- sort .Sort (hashes (storageList ))
105- dl .storageList [accountHash ] = storageList
106- dl .storageSorted [accountHash ] = true
107-
108- dl .memory += uint64 (len (storageList ) * common .HashLength )
10992 }
11093 dl .memory += uint64 (len (dl .storageList ) * common .HashLength )
11194
@@ -119,28 +102,36 @@ func (dl *diffLayer) Info() (uint64, common.Hash) {
119102
120103// Account directly retrieves the account associated with a particular hash in
121104// the snapshot slim data format.
122- func (dl * diffLayer ) Account (hash common.Hash ) * Account {
123- data := dl .AccountRLP (hash )
105+ func (dl * diffLayer ) Account (hash common.Hash ) (* Account , error ) {
106+ data , err := dl .AccountRLP (hash )
107+ if err != nil {
108+ return nil , err
109+ }
124110 if len (data ) == 0 { // can be both nil and []byte{}
125- return nil
111+ return nil , nil
126112 }
127113 account := new (Account )
128114 if err := rlp .DecodeBytes (data , account ); err != nil {
129115 panic (err )
130116 }
131- return account
117+ return account , nil
132118}
133119
134120// AccountRLP directly retrieves the account RLP associated with a particular
135121// hash in the snapshot slim data format.
136- func (dl * diffLayer ) AccountRLP (hash common.Hash ) []byte {
122+ func (dl * diffLayer ) AccountRLP (hash common.Hash ) ( []byte , error ) {
137123 dl .lock .RLock ()
138124 defer dl .lock .RUnlock ()
139125
126+ // If the layer was flattened into, consider it invalid (any live reference to
127+ // the original should be marked as unusable).
128+ if dl .stale {
129+ return nil , ErrSnapshotStale
130+ }
140131 // If the account is known locally, return it. Note, a nil account means it was
141132 // deleted, and is a different notion than an unknown account!
142133 if data , ok := dl .accountData [hash ]; ok {
143- return data
134+ return data , nil
144135 }
145136 // Account unknown to this diff, resolve from parent
146137 return dl .parent .AccountRLP (hash )
@@ -149,18 +140,23 @@ func (dl *diffLayer) AccountRLP(hash common.Hash) []byte {
149140// Storage directly retrieves the storage data associated with a particular hash,
150141// within a particular account. If the slot is unknown to this diff, it's parent
151142// is consulted.
152- func (dl * diffLayer ) Storage (accountHash , storageHash common.Hash ) []byte {
143+ func (dl * diffLayer ) Storage (accountHash , storageHash common.Hash ) ( []byte , error ) {
153144 dl .lock .RLock ()
154145 defer dl .lock .RUnlock ()
155146
147+ // If the layer was flattened into, consider it invalid (any live reference to
148+ // the original should be marked as unusable).
149+ if dl .stale {
150+ return nil , ErrSnapshotStale
151+ }
156152 // If the account is known locally, try to resolve the slot locally. Note, a nil
157153 // account means it was deleted, and is a different notion than an unknown account!
158154 if storage , ok := dl .storageData [accountHash ]; ok {
159155 if storage == nil {
160- return nil
156+ return nil , nil
161157 }
162158 if data , ok := storage [storageHash ]; ok {
163- return data
159+ return data , nil
164160 }
165161 }
166162 // Account - or slot within - unknown to this diff, resolve from parent
@@ -193,13 +189,17 @@ func (dl *diffLayer) Cap(layers int, memory uint64) (uint64, uint64) {
193189 case * diskLayer :
194190 return parent .number , dl .number
195191 case * diffLayer :
192+ // Flatten the parent into the grandparent. The flattening internally obtains a
193+ // write lock on grandparent.
194+ flattened := parent .flatten ().(* diffLayer )
195+
196196 dl .lock .Lock ()
197197 defer dl .lock .Unlock ()
198198
199- dl .parent = parent . flatten ()
200- if dl . parent .( * diffLayer ) .memory < memory {
201- diskNumber , _ := parent .parent .Info ()
202- return diskNumber , parent .number
199+ dl .parent = flattened
200+ if flattened .memory < memory {
201+ diskNumber , _ := flattened .parent .Info ()
202+ return diskNumber , flattened .number
203203 }
204204 default :
205205 panic (fmt .Sprintf ("unknown data layer: %T" , parent ))
@@ -213,10 +213,18 @@ func (dl *diffLayer) Cap(layers int, memory uint64) (uint64, uint64) {
213213 parent .lock .RLock ()
214214 defer parent .lock .RUnlock ()
215215
216- // Start by temporarilly deleting the current snapshot block marker. This
216+ // Start by temporarily deleting the current snapshot block marker. This
217217 // ensures that in the case of a crash, the entire snapshot is invalidated.
218218 rawdb .DeleteSnapshotBlock (batch )
219219
220+ // Mark the original base as stale as we're going to create a new wrapper
221+ base .lock .Lock ()
222+ if base .stale {
223+ panic ("parent disk layer is stale" ) // we've committed into the same base from two children, boo
224+ }
225+ base .stale = true
226+ base .lock .Unlock ()
227+
220228 // Push all the accounts into the database
221229 for hash , data := range parent .accountData {
222230 if len (data ) > 0 {
@@ -264,15 +272,20 @@ func (dl *diffLayer) Cap(layers int, memory uint64) (uint64, uint64) {
264272 }
265273 }
266274 // Update the snapshot block marker and write any remainder data
267- base .number , base .root = parent .number , parent .root
268-
269- rawdb .WriteSnapshotBlock (batch , base .number , base .root )
275+ newBase := & diskLayer {
276+ root : parent .root ,
277+ number : parent .number ,
278+ cache : base .cache ,
279+ db : base .db ,
280+ journal : base .journal ,
281+ }
282+ rawdb .WriteSnapshotBlock (batch , newBase .number , newBase .root )
270283 if err := batch .Write (); err != nil {
271284 log .Crit ("Failed to write leftover snapshot" , "err" , err )
272285 }
273- dl .parent = base
286+ dl .parent = newBase
274287
275- return base .number , dl .number
288+ return newBase .number , dl .number
276289}
277290
278291// flatten pushes all data from this point downwards, flattening everything into
@@ -289,19 +302,25 @@ func (dl *diffLayer) flatten() snapshot {
289302 // be smarter about grouping flattens together).
290303 parent = parent .flatten ().(* diffLayer )
291304
305+ parent .lock .Lock ()
306+ defer parent .lock .Unlock ()
307+
308+ // Before actually writing all our data to the parent, first ensure that the
309+ // parent hasn't been 'corrupted' by someone else already flattening into it
310+ if parent .stale {
311+ panic ("parent diff layer is stale" ) // we've flattened into the same parent from two children, boo
312+ }
313+ parent .stale = true
314+
292315 // Overwrite all the updated accounts blindly, merge the sorted list
293316 for hash , data := range dl .accountData {
294317 parent .accountData [hash ] = data
295318 }
296- parent .accountList = append (parent .accountList , dl .accountList ... ) // TODO(karalabe): dedup!!
297- parent .accountSorted = false
298-
299319 // Overwrite all the updates storage slots (individually)
300320 for accountHash , storage := range dl .storageData {
301321 // If storage didn't exist (or was deleted) in the parent; or if the storage
302322 // was freshly deleted in the child, overwrite blindly
303323 if parent .storageData [accountHash ] == nil || storage == nil {
304- parent .storageList [accountHash ] = dl .storageList [accountHash ]
305324 parent .storageData [accountHash ] = storage
306325 continue
307326 }
@@ -311,14 +330,18 @@ func (dl *diffLayer) flatten() snapshot {
311330 comboData [storageHash ] = data
312331 }
313332 parent .storageData [accountHash ] = comboData
314- parent .storageList [accountHash ] = append (parent .storageList [accountHash ], dl .storageList [accountHash ]... ) // TODO(karalabe): dedup!!
315- parent .storageSorted [accountHash ] = false
316333 }
317334 // Return the combo parent
318- parent .number = dl .number
319- parent .root = dl .root
320- parent .memory += dl .memory
321- return parent
335+ return & diffLayer {
336+ parent : parent .parent ,
337+ number : dl .number ,
338+ root : dl .root ,
339+ storageList : parent .storageList ,
340+ storageData : parent .storageData ,
341+ accountList : parent .accountList ,
342+ accountData : parent .accountData ,
343+ memory : parent .memory + dl .memory ,
344+ }
322345}
323346
324347// Journal commits an entire diff hierarchy to disk into a single journal file.
@@ -335,3 +358,45 @@ func (dl *diffLayer) Journal() error {
335358 writer .Close ()
336359 return nil
337360}
361+
362+ // AccountList returns a sorted list of all accounts in this difflayer.
363+ func (dl * diffLayer ) AccountList () []common.Hash {
364+ dl .lock .Lock ()
365+ defer dl .lock .Unlock ()
366+ if dl .accountList != nil {
367+ return dl .accountList
368+ }
369+ accountList := make ([]common.Hash , len (dl .accountData ))
370+ i := 0
371+ for k , _ := range dl .accountData {
372+ accountList [i ] = k
373+ i ++
374+ // This would be a pretty good opportunity to also
375+ // calculate the size, if we want to
376+ }
377+ sort .Sort (hashes (accountList ))
378+ dl .accountList = accountList
379+ return dl .accountList
380+ }
381+
382+ // StorageList returns a sorted list of all storage slot hashes
383+ // in this difflayer for the given account.
384+ func (dl * diffLayer ) StorageList (accountHash common.Hash ) []common.Hash {
385+ dl .lock .Lock ()
386+ defer dl .lock .Unlock ()
387+ if dl .storageList [accountHash ] != nil {
388+ return dl .storageList [accountHash ]
389+ }
390+ accountStorageMap := dl .storageData [accountHash ]
391+ accountStorageList := make ([]common.Hash , len (accountStorageMap ))
392+ i := 0
393+ for k , _ := range accountStorageMap {
394+ accountStorageList [i ] = k
395+ i ++
396+ // This would be a pretty good opportunity to also
397+ // calculate the size, if we want to
398+ }
399+ sort .Sort (hashes (accountStorageList ))
400+ dl .storageList [accountHash ] = accountStorageList
401+ return accountStorageList
402+ }
0 commit comments