github.com/MetalBlockchain/subnet-evm@v0.4.9/core/state/snapshot/difflayer.go (about)

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