difflayer.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. // Copyright 2019 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. package snapshot
  17. import (
  18. "encoding/binary"
  19. "fmt"
  20. "math"
  21. "math/rand"
  22. "sort"
  23. "sync"
  24. "sync/atomic"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. bloomfilter "github.com/holiman/bloomfilter/v2"
  29. )
  30. var (
  31. // aggregatorMemoryLimit is the maximum size of the bottom-most diff layer
  32. // that aggregates the writes from above until it's flushed into the disk
  33. // layer.
  34. //
  35. // Note, bumping this up might drastically increase the size of the bloom
  36. // filters that's stored in every diff layer. Don't do that without fully
  37. // understanding all the implications.
  38. aggregatorMemoryLimit = uint64(4 * 1024 * 1024)
  39. // aggregatorItemLimit is an approximate number of items that will end up
  40. // in the agregator layer before it's flushed out to disk. A plain account
  41. // weighs around 14B (+hash), a storage slot 32B (+hash), a deleted slot
  42. // 0B (+hash). Slots are mostly set/unset in lockstep, so that average at
  43. // 16B (+hash). All in all, the average entry seems to be 15+32=47B. Use a
  44. // smaller number to be on the safe side.
  45. aggregatorItemLimit = aggregatorMemoryLimit / 42
  46. // bloomTargetError is the target false positive rate when the aggregator
  47. // layer is at its fullest. The actual value will probably move around up
  48. // and down from this number, it's mostly a ballpark figure.
  49. //
  50. // Note, dropping this down might drastically increase the size of the bloom
  51. // filters that's stored in every diff layer. Don't do that without fully
  52. // understanding all the implications.
  53. bloomTargetError = 0.02
  54. // bloomSize is the ideal bloom filter size given the maximum number of items
  55. // it's expected to hold and the target false positive error rate.
  56. bloomSize = math.Ceil(float64(aggregatorItemLimit) * math.Log(bloomTargetError) / math.Log(1/math.Pow(2, math.Log(2))))
  57. // bloomFuncs is the ideal number of bits a single entry should set in the
  58. // bloom filter to keep its size to a minimum (given it's size and maximum
  59. // entry count).
  60. bloomFuncs = math.Round((bloomSize / float64(aggregatorItemLimit)) * math.Log(2))
  61. // the bloom offsets are runtime constants which determines which part of the
  62. // the account/storage hash the hasher functions looks at, to determine the
  63. // bloom key for an account/slot. This is randomized at init(), so that the
  64. // global population of nodes do not all display the exact same behaviour with
  65. // regards to bloom content
  66. bloomDestructHasherOffset = 0
  67. bloomAccountHasherOffset = 0
  68. bloomStorageHasherOffset = 0
  69. )
  70. func init() {
  71. // Init the bloom offsets in the range [0:24] (requires 8 bytes)
  72. bloomDestructHasherOffset = rand.Intn(25)
  73. bloomAccountHasherOffset = rand.Intn(25)
  74. bloomStorageHasherOffset = rand.Intn(25)
  75. // The destruct and account blooms must be different, as the storage slots
  76. // will check for destruction too for every bloom miss. It should not collide
  77. // with modified accounts.
  78. for bloomAccountHasherOffset == bloomDestructHasherOffset {
  79. bloomAccountHasherOffset = rand.Intn(25)
  80. }
  81. }
  82. // diffLayer represents a collection of modifications made to a state snapshot
  83. // after running a block on top. It contains one sorted list for the account trie
  84. // and one-one list for each storage tries.
  85. //
  86. // The goal of a diff layer is to act as a journal, tracking recent modifications
  87. // made to the state, that have not yet graduated into a semi-immutable state.
  88. type diffLayer struct {
  89. origin *diskLayer // Base disk layer to directly use on bloom misses
  90. parent snapshot // Parent snapshot modified by this one, never nil
  91. memory uint64 // Approximate guess as to how much memory we use
  92. root common.Hash // Root hash to which this snapshot diff belongs to
  93. stale uint32 // Signals that the layer became stale (state progressed)
  94. // destructSet is a very special helper marker. If an account is marked as
  95. // deleted, then it's recorded in this set. However it's allowed that an account
  96. // is included here but still available in other sets(e.g. storageData). The
  97. // reason is the diff layer includes all the changes in a *block*. It can
  98. // happen that in the tx_1, account A is self-destructed while in the tx_2
  99. // it's recreated. But we still need this marker to indicate the "old" A is
  100. // deleted, all data in other set belongs to the "new" A.
  101. destructSet map[common.Hash]struct{} // Keyed markers for deleted (and potentially) recreated accounts
  102. accountList []common.Hash // List of account for iteration. If it exists, it's sorted, otherwise it's nil
  103. accountData map[common.Hash][]byte // Keyed accounts for direct retrieval (nil means deleted)
  104. 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. storageData map[common.Hash]map[common.Hash][]byte // Keyed storage slots for direct retrieval. one per account (nil means deleted)
  106. verifiedCh chan struct{} // the difflayer is verified when verifiedCh is nil or closed
  107. valid bool // mark the difflayer is valid or not.
  108. diffed *bloomfilter.Filter // Bloom filter tracking all the diffed items up to the disk layer
  109. lock sync.RWMutex
  110. }
  111. // destructBloomHasher is a wrapper around a common.Hash to satisfy the interface
  112. // API requirements of the bloom library used. It's used to convert a destruct
  113. // event into a 64 bit mini hash.
  114. type destructBloomHasher common.Hash
  115. func (h destructBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") }
  116. func (h destructBloomHasher) Sum(b []byte) []byte { panic("not implemented") }
  117. func (h destructBloomHasher) Reset() { panic("not implemented") }
  118. func (h destructBloomHasher) BlockSize() int { panic("not implemented") }
  119. func (h destructBloomHasher) Size() int { return 8 }
  120. func (h destructBloomHasher) Sum64() uint64 {
  121. return binary.BigEndian.Uint64(h[bloomDestructHasherOffset : bloomDestructHasherOffset+8])
  122. }
  123. // accountBloomHasher is a wrapper around a common.Hash to satisfy the interface
  124. // API requirements of the bloom library used. It's used to convert an account
  125. // hash into a 64 bit mini hash.
  126. type accountBloomHasher common.Hash
  127. func (h accountBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") }
  128. func (h accountBloomHasher) Sum(b []byte) []byte { panic("not implemented") }
  129. func (h accountBloomHasher) Reset() { panic("not implemented") }
  130. func (h accountBloomHasher) BlockSize() int { panic("not implemented") }
  131. func (h accountBloomHasher) Size() int { return 8 }
  132. func (h accountBloomHasher) Sum64() uint64 {
  133. return binary.BigEndian.Uint64(h[bloomAccountHasherOffset : bloomAccountHasherOffset+8])
  134. }
  135. // storageBloomHasher is a wrapper around a [2]common.Hash to satisfy the interface
  136. // API requirements of the bloom library used. It's used to convert an account
  137. // hash into a 64 bit mini hash.
  138. type storageBloomHasher [2]common.Hash
  139. func (h storageBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") }
  140. func (h storageBloomHasher) Sum(b []byte) []byte { panic("not implemented") }
  141. func (h storageBloomHasher) Reset() { panic("not implemented") }
  142. func (h storageBloomHasher) BlockSize() int { panic("not implemented") }
  143. func (h storageBloomHasher) Size() int { return 8 }
  144. func (h storageBloomHasher) Sum64() uint64 {
  145. return binary.BigEndian.Uint64(h[0][bloomStorageHasherOffset:bloomStorageHasherOffset+8]) ^
  146. binary.BigEndian.Uint64(h[1][bloomStorageHasherOffset:bloomStorageHasherOffset+8])
  147. }
  148. // newDiffLayer creates a new diff on top of an existing snapshot, whether that's a low
  149. // level persistent database or a hierarchical diff already.
  150. 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, verified chan struct{}) *diffLayer {
  151. // Create the new layer with some pre-allocated data segments
  152. dl := &diffLayer{
  153. parent: parent,
  154. root: root,
  155. destructSet: destructs,
  156. accountData: accounts,
  157. storageData: storage,
  158. storageList: make(map[common.Hash][]common.Hash),
  159. verifiedCh: verified,
  160. }
  161. switch parent := parent.(type) {
  162. case *diskLayer:
  163. dl.rebloom(parent)
  164. case *diffLayer:
  165. dl.rebloom(parent.origin)
  166. default:
  167. panic("unknown parent type")
  168. }
  169. // Sanity check that accounts or storage slots are never nil
  170. for accountHash, blob := range accounts {
  171. if blob == nil {
  172. panic(fmt.Sprintf("account %#x nil", accountHash))
  173. }
  174. // Determine memory size and track the dirty writes
  175. dl.memory += uint64(common.HashLength + len(blob))
  176. snapshotDirtyAccountWriteMeter.Mark(int64(len(blob)))
  177. }
  178. for accountHash, slots := range storage {
  179. if slots == nil {
  180. panic(fmt.Sprintf("storage %#x nil", accountHash))
  181. }
  182. // Determine memory size and track the dirty writes
  183. for _, data := range slots {
  184. dl.memory += uint64(common.HashLength + len(data))
  185. snapshotDirtyStorageWriteMeter.Mark(int64(len(data)))
  186. }
  187. }
  188. dl.memory += uint64(len(destructs) * common.HashLength)
  189. return dl
  190. }
  191. // rebloom discards the layer's current bloom and rebuilds it from scratch based
  192. // on the parent's and the local diffs.
  193. func (dl *diffLayer) rebloom(origin *diskLayer) {
  194. dl.lock.Lock()
  195. defer dl.lock.Unlock()
  196. defer func(start time.Time) {
  197. snapshotBloomIndexTimer.Update(time.Since(start))
  198. }(time.Now())
  199. // Inject the new origin that triggered the rebloom
  200. dl.origin = origin
  201. // Retrieve the parent bloom or create a fresh empty one
  202. if parent, ok := dl.parent.(*diffLayer); ok {
  203. parent.lock.RLock()
  204. dl.diffed, _ = parent.diffed.Copy()
  205. parent.lock.RUnlock()
  206. } else {
  207. dl.diffed, _ = bloomfilter.New(uint64(bloomSize), uint64(bloomFuncs))
  208. }
  209. // Iterate over all the accounts and storage slots and index them
  210. for hash := range dl.destructSet {
  211. dl.diffed.Add(destructBloomHasher(hash))
  212. }
  213. for hash := range dl.accountData {
  214. dl.diffed.Add(accountBloomHasher(hash))
  215. }
  216. for accountHash, slots := range dl.storageData {
  217. for storageHash := range slots {
  218. dl.diffed.Add(storageBloomHasher{accountHash, storageHash})
  219. }
  220. }
  221. // Calculate the current false positive rate and update the error rate meter.
  222. // This is a bit cheating because subsequent layers will overwrite it, but it
  223. // should be fine, we're only interested in ballpark figures.
  224. k := float64(dl.diffed.K())
  225. n := float64(dl.diffed.N())
  226. m := float64(dl.diffed.M())
  227. snapshotBloomErrorGauge.Update(math.Pow(1.0-math.Exp((-k)*(n+0.5)/(m-1)), k))
  228. }
  229. // Root returns the root hash for which this snapshot was made.
  230. func (dl *diffLayer) Root() common.Hash {
  231. return dl.root
  232. }
  233. // WaitAndGetVerifyRes will wait until the diff layer been verified and return the verification result
  234. func (dl *diffLayer) WaitAndGetVerifyRes() bool {
  235. if dl.verifiedCh == nil {
  236. return true
  237. }
  238. <-dl.verifiedCh
  239. return dl.valid
  240. }
  241. func (dl *diffLayer) MarkValid() {
  242. dl.valid = true
  243. }
  244. // Represent whether the difflayer is been verified, does not means it is a valid or invalid difflayer
  245. func (dl *diffLayer) Verified() bool {
  246. if dl.verifiedCh == nil {
  247. return true
  248. }
  249. select {
  250. case <-dl.verifiedCh:
  251. return true
  252. default:
  253. return false
  254. }
  255. }
  256. // Parent returns the subsequent layer of a diff layer.
  257. func (dl *diffLayer) Parent() snapshot {
  258. return dl.parent
  259. }
  260. // Stale return whether this layer has become stale (was flattened across) or if
  261. // it's still live.
  262. func (dl *diffLayer) Stale() bool {
  263. return atomic.LoadUint32(&dl.stale) != 0
  264. }
  265. // Account directly retrieves the account associated with a particular hash in
  266. // the snapshot slim data format.
  267. func (dl *diffLayer) Account(hash common.Hash) (*Account, error) {
  268. data, err := dl.AccountRLP(hash)
  269. if err != nil {
  270. return nil, err
  271. }
  272. if len(data) == 0 { // can be both nil and []byte{}
  273. return nil, nil
  274. }
  275. account := new(Account)
  276. if err := rlp.DecodeBytes(data, account); err != nil {
  277. panic(err)
  278. }
  279. return account, nil
  280. }
  281. // AccountRLP directly retrieves the account RLP associated with a particular
  282. // hash in the snapshot slim data format.
  283. //
  284. // Note the returned account is not a copy, please don't modify it.
  285. func (dl *diffLayer) AccountRLP(hash common.Hash) ([]byte, error) {
  286. // Check the bloom filter first whether there's even a point in reaching into
  287. // all the maps in all the layers below
  288. dl.lock.RLock()
  289. hit := dl.diffed.Contains(accountBloomHasher(hash))
  290. if !hit {
  291. hit = dl.diffed.Contains(destructBloomHasher(hash))
  292. }
  293. var origin *diskLayer
  294. if !hit {
  295. origin = dl.origin // extract origin while holding the lock
  296. }
  297. dl.lock.RUnlock()
  298. // If the bloom filter misses, don't even bother with traversing the memory
  299. // diff layers, reach straight into the bottom persistent disk layer
  300. if origin != nil {
  301. snapshotBloomAccountMissMeter.Mark(1)
  302. return origin.AccountRLP(hash)
  303. }
  304. // The bloom filter hit, start poking in the internal maps
  305. return dl.accountRLP(hash, 0)
  306. }
  307. // accountRLP is an internal version of AccountRLP that skips the bloom filter
  308. // checks and uses the internal maps to try and retrieve the data. It's meant
  309. // to be used if a higher layer's bloom filter hit already.
  310. func (dl *diffLayer) accountRLP(hash common.Hash, depth int) ([]byte, error) {
  311. dl.lock.RLock()
  312. defer dl.lock.RUnlock()
  313. // If the layer was flattened into, consider it invalid (any live reference to
  314. // the original should be marked as unusable).
  315. if dl.Stale() {
  316. return nil, ErrSnapshotStale
  317. }
  318. // If the account is known locally, return it
  319. if data, ok := dl.accountData[hash]; ok {
  320. snapshotDirtyAccountHitMeter.Mark(1)
  321. snapshotDirtyAccountHitDepthHist.Update(int64(depth))
  322. snapshotDirtyAccountReadMeter.Mark(int64(len(data)))
  323. snapshotBloomAccountTrueHitMeter.Mark(1)
  324. return data, nil
  325. }
  326. // If the account is known locally, but deleted, return it
  327. if _, ok := dl.destructSet[hash]; ok {
  328. snapshotDirtyAccountHitMeter.Mark(1)
  329. snapshotDirtyAccountHitDepthHist.Update(int64(depth))
  330. snapshotDirtyAccountInexMeter.Mark(1)
  331. snapshotBloomAccountTrueHitMeter.Mark(1)
  332. return nil, nil
  333. }
  334. // Account unknown to this diff, resolve from parent
  335. if diff, ok := dl.parent.(*diffLayer); ok {
  336. return diff.accountRLP(hash, depth+1)
  337. }
  338. // Failed to resolve through diff layers, mark a bloom error and use the disk
  339. snapshotBloomAccountFalseHitMeter.Mark(1)
  340. return dl.parent.AccountRLP(hash)
  341. }
  342. // Storage directly retrieves the storage data associated with a particular hash,
  343. // within a particular account. If the slot is unknown to this diff, it's parent
  344. // is consulted.
  345. //
  346. // Note the returned slot is not a copy, please don't modify it.
  347. func (dl *diffLayer) Storage(accountHash, storageHash common.Hash) ([]byte, error) {
  348. // Check the bloom filter first whether there's even a point in reaching into
  349. // all the maps in all the layers below
  350. dl.lock.RLock()
  351. hit := dl.diffed.Contains(storageBloomHasher{accountHash, storageHash})
  352. if !hit {
  353. hit = dl.diffed.Contains(destructBloomHasher(accountHash))
  354. }
  355. var origin *diskLayer
  356. if !hit {
  357. origin = dl.origin // extract origin while holding the lock
  358. }
  359. dl.lock.RUnlock()
  360. // If the bloom filter misses, don't even bother with traversing the memory
  361. // diff layers, reach straight into the bottom persistent disk layer
  362. if origin != nil {
  363. snapshotBloomStorageMissMeter.Mark(1)
  364. return origin.Storage(accountHash, storageHash)
  365. }
  366. // The bloom filter hit, start poking in the internal maps
  367. return dl.storage(accountHash, storageHash, 0)
  368. }
  369. // storage is an internal version of Storage that skips the bloom filter checks
  370. // and uses the internal maps to try and retrieve the data. It's meant to be
  371. // used if a higher layer's bloom filter hit already.
  372. func (dl *diffLayer) storage(accountHash, storageHash common.Hash, depth int) ([]byte, error) {
  373. dl.lock.RLock()
  374. defer dl.lock.RUnlock()
  375. // If the layer was flattened into, consider it invalid (any live reference to
  376. // the original should be marked as unusable).
  377. if dl.Stale() {
  378. return nil, ErrSnapshotStale
  379. }
  380. // If the account is known locally, try to resolve the slot locally
  381. if storage, ok := dl.storageData[accountHash]; ok {
  382. if data, ok := storage[storageHash]; ok {
  383. snapshotDirtyStorageHitMeter.Mark(1)
  384. //snapshotDirtyStorageHitDepthHist.Update(int64(depth))
  385. if n := len(data); n > 0 {
  386. snapshotDirtyStorageReadMeter.Mark(int64(n))
  387. } else {
  388. snapshotDirtyStorageInexMeter.Mark(1)
  389. }
  390. snapshotBloomStorageTrueHitMeter.Mark(1)
  391. return data, nil
  392. }
  393. }
  394. // If the account is known locally, but deleted, return an empty slot
  395. if _, ok := dl.destructSet[accountHash]; ok {
  396. snapshotDirtyStorageHitMeter.Mark(1)
  397. //snapshotDirtyStorageHitDepthHist.Update(int64(depth))
  398. snapshotDirtyStorageInexMeter.Mark(1)
  399. snapshotBloomStorageTrueHitMeter.Mark(1)
  400. return nil, nil
  401. }
  402. // Storage slot unknown to this diff, resolve from parent
  403. if diff, ok := dl.parent.(*diffLayer); ok {
  404. return diff.storage(accountHash, storageHash, depth+1)
  405. }
  406. // Failed to resolve through diff layers, mark a bloom error and use the disk
  407. snapshotBloomStorageFalseHitMeter.Mark(1)
  408. return dl.parent.Storage(accountHash, storageHash)
  409. }
  410. // Update creates a new layer on top of the existing snapshot diff tree with
  411. // the specified data items.
  412. 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, verified chan struct{}) *diffLayer {
  413. return newDiffLayer(dl, blockRoot, destructs, accounts, storage, verified)
  414. }
  415. // flatten pushes all data from this point downwards, flattening everything into
  416. // a single diff at the bottom. Since usually the lowermost diff is the largest,
  417. // the flattening builds up from there in reverse.
  418. func (dl *diffLayer) flatten() snapshot {
  419. // If the parent is not diff, we're the first in line, return unmodified
  420. parent, ok := dl.parent.(*diffLayer)
  421. if !ok {
  422. return dl
  423. }
  424. // Parent is a diff, flatten it first (note, apart from weird corned cases,
  425. // flatten will realistically only ever merge 1 layer, so there's no need to
  426. // be smarter about grouping flattens together).
  427. parent = parent.flatten().(*diffLayer)
  428. parent.lock.Lock()
  429. defer parent.lock.Unlock()
  430. // Before actually writing all our data to the parent, first ensure that the
  431. // parent hasn't been 'corrupted' by someone else already flattening into it
  432. if atomic.SwapUint32(&parent.stale, 1) != 0 {
  433. panic("parent diff layer is stale") // we've flattened into the same parent from two children, boo
  434. }
  435. // Overwrite all the updated accounts blindly, merge the sorted list
  436. for hash := range dl.destructSet {
  437. parent.destructSet[hash] = struct{}{}
  438. delete(parent.accountData, hash)
  439. delete(parent.storageData, hash)
  440. }
  441. for hash, data := range dl.accountData {
  442. parent.accountData[hash] = data
  443. }
  444. // Overwrite all the updated storage slots (individually)
  445. for accountHash, storage := range dl.storageData {
  446. // If storage didn't exist (or was deleted) in the parent, overwrite blindly
  447. if _, ok := parent.storageData[accountHash]; !ok {
  448. parent.storageData[accountHash] = storage
  449. continue
  450. }
  451. // Storage exists in both parent and child, merge the slots
  452. comboData := parent.storageData[accountHash]
  453. for storageHash, data := range storage {
  454. comboData[storageHash] = data
  455. }
  456. parent.storageData[accountHash] = comboData
  457. }
  458. // Return the combo parent
  459. return &diffLayer{
  460. parent: parent.parent,
  461. origin: parent.origin,
  462. root: dl.root,
  463. destructSet: parent.destructSet,
  464. accountData: parent.accountData,
  465. storageData: parent.storageData,
  466. storageList: make(map[common.Hash][]common.Hash),
  467. diffed: dl.diffed,
  468. memory: parent.memory + dl.memory,
  469. }
  470. }
  471. // AccountList returns a sorted list of all accounts in this diffLayer, including
  472. // the deleted ones.
  473. //
  474. // Note, the returned slice is not a copy, so do not modify it.
  475. func (dl *diffLayer) AccountList() []common.Hash {
  476. // If an old list already exists, return it
  477. dl.lock.RLock()
  478. list := dl.accountList
  479. dl.lock.RUnlock()
  480. if list != nil {
  481. return list
  482. }
  483. // No old sorted account list exists, generate a new one
  484. dl.lock.Lock()
  485. defer dl.lock.Unlock()
  486. dl.accountList = make([]common.Hash, 0, len(dl.destructSet)+len(dl.accountData))
  487. for hash := range dl.accountData {
  488. dl.accountList = append(dl.accountList, hash)
  489. }
  490. for hash := range dl.destructSet {
  491. if _, ok := dl.accountData[hash]; !ok {
  492. dl.accountList = append(dl.accountList, hash)
  493. }
  494. }
  495. sort.Sort(hashes(dl.accountList))
  496. dl.memory += uint64(len(dl.accountList) * common.HashLength)
  497. return dl.accountList
  498. }
  499. // StorageList returns a sorted list of all storage slot hashes in this diffLayer
  500. // for the given account. If the whole storage is destructed in this layer, then
  501. // an additional flag *destructed = true* will be returned, otherwise the flag is
  502. // false. Besides, the returned list will include the hash of deleted storage slot.
  503. // Note a special case is an account is deleted in a prior tx but is recreated in
  504. // the following tx with some storage slots set. In this case the returned list is
  505. // not empty but the flag is true.
  506. //
  507. // Note, the returned slice is not a copy, so do not modify it.
  508. func (dl *diffLayer) StorageList(accountHash common.Hash) ([]common.Hash, bool) {
  509. dl.lock.RLock()
  510. _, destructed := dl.destructSet[accountHash]
  511. if _, ok := dl.storageData[accountHash]; !ok {
  512. // Account not tracked by this layer
  513. dl.lock.RUnlock()
  514. return nil, destructed
  515. }
  516. // If an old list already exists, return it
  517. if list, exist := dl.storageList[accountHash]; exist {
  518. dl.lock.RUnlock()
  519. return list, destructed // the cached list can't be nil
  520. }
  521. dl.lock.RUnlock()
  522. // No old sorted account list exists, generate a new one
  523. dl.lock.Lock()
  524. defer dl.lock.Unlock()
  525. storageMap := dl.storageData[accountHash]
  526. storageList := make([]common.Hash, 0, len(storageMap))
  527. for k := range storageMap {
  528. storageList = append(storageList, k)
  529. }
  530. sort.Sort(hashes(storageList))
  531. dl.storageList[accountHash] = storageList
  532. dl.memory += uint64(len(dl.storageList)*common.HashLength + common.HashLength)
  533. return storageList, destructed
  534. }