github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/core/state/snapshot/snapshot.go (about)

     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  
    17  // Package snapshot implements a journalled, dynamic state dump.
    18  package snapshot
    19  
    20  import (
    21  	"bytes"
    22  	"errors"
    23  	"fmt"
    24  	"sync"
    25  	"sync/atomic"
    26  
    27  	"github.com/scroll-tech/go-ethereum/common"
    28  	"github.com/scroll-tech/go-ethereum/core/rawdb"
    29  	"github.com/scroll-tech/go-ethereum/ethdb"
    30  	"github.com/scroll-tech/go-ethereum/log"
    31  	"github.com/scroll-tech/go-ethereum/metrics"
    32  	"github.com/scroll-tech/go-ethereum/rlp"
    33  	"github.com/scroll-tech/go-ethereum/trie"
    34  )
    35  
    36  var (
    37  	snapshotCleanAccountHitMeter   = metrics.NewRegisteredMeter("state/snapshot/clean/account/hit", nil)
    38  	snapshotCleanAccountMissMeter  = metrics.NewRegisteredMeter("state/snapshot/clean/account/miss", nil)
    39  	snapshotCleanAccountInexMeter  = metrics.NewRegisteredMeter("state/snapshot/clean/account/inex", nil)
    40  	snapshotCleanAccountReadMeter  = metrics.NewRegisteredMeter("state/snapshot/clean/account/read", nil)
    41  	snapshotCleanAccountWriteMeter = metrics.NewRegisteredMeter("state/snapshot/clean/account/write", nil)
    42  
    43  	snapshotCleanStorageHitMeter   = metrics.NewRegisteredMeter("state/snapshot/clean/storage/hit", nil)
    44  	snapshotCleanStorageMissMeter  = metrics.NewRegisteredMeter("state/snapshot/clean/storage/miss", nil)
    45  	snapshotCleanStorageInexMeter  = metrics.NewRegisteredMeter("state/snapshot/clean/storage/inex", nil)
    46  	snapshotCleanStorageReadMeter  = metrics.NewRegisteredMeter("state/snapshot/clean/storage/read", nil)
    47  	snapshotCleanStorageWriteMeter = metrics.NewRegisteredMeter("state/snapshot/clean/storage/write", nil)
    48  
    49  	snapshotDirtyAccountHitMeter   = metrics.NewRegisteredMeter("state/snapshot/dirty/account/hit", nil)
    50  	snapshotDirtyAccountMissMeter  = metrics.NewRegisteredMeter("state/snapshot/dirty/account/miss", nil)
    51  	snapshotDirtyAccountInexMeter  = metrics.NewRegisteredMeter("state/snapshot/dirty/account/inex", nil)
    52  	snapshotDirtyAccountReadMeter  = metrics.NewRegisteredMeter("state/snapshot/dirty/account/read", nil)
    53  	snapshotDirtyAccountWriteMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/account/write", nil)
    54  
    55  	snapshotDirtyStorageHitMeter   = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/hit", nil)
    56  	snapshotDirtyStorageMissMeter  = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/miss", nil)
    57  	snapshotDirtyStorageInexMeter  = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/inex", nil)
    58  	snapshotDirtyStorageReadMeter  = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/read", nil)
    59  	snapshotDirtyStorageWriteMeter = metrics.NewRegisteredMeter("state/snapshot/dirty/storage/write", nil)
    60  
    61  	snapshotDirtyAccountHitDepthHist = metrics.NewRegisteredHistogram("state/snapshot/dirty/account/hit/depth", nil, metrics.NewExpDecaySample(1028, 0.015))
    62  	snapshotDirtyStorageHitDepthHist = metrics.NewRegisteredHistogram("state/snapshot/dirty/storage/hit/depth", nil, metrics.NewExpDecaySample(1028, 0.015))
    63  
    64  	snapshotFlushAccountItemMeter = metrics.NewRegisteredMeter("state/snapshot/flush/account/item", nil)
    65  	snapshotFlushAccountSizeMeter = metrics.NewRegisteredMeter("state/snapshot/flush/account/size", nil)
    66  	snapshotFlushStorageItemMeter = metrics.NewRegisteredMeter("state/snapshot/flush/storage/item", nil)
    67  	snapshotFlushStorageSizeMeter = metrics.NewRegisteredMeter("state/snapshot/flush/storage/size", nil)
    68  
    69  	snapshotBloomIndexTimer = metrics.NewRegisteredResettingTimer("state/snapshot/bloom/index", nil)
    70  	snapshotBloomErrorGauge = metrics.NewRegisteredGaugeFloat64("state/snapshot/bloom/error", nil)
    71  
    72  	snapshotBloomAccountTrueHitMeter  = metrics.NewRegisteredMeter("state/snapshot/bloom/account/truehit", nil)
    73  	snapshotBloomAccountFalseHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/account/falsehit", nil)
    74  	snapshotBloomAccountMissMeter     = metrics.NewRegisteredMeter("state/snapshot/bloom/account/miss", nil)
    75  
    76  	snapshotBloomStorageTrueHitMeter  = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/truehit", nil)
    77  	snapshotBloomStorageFalseHitMeter = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/falsehit", nil)
    78  	snapshotBloomStorageMissMeter     = metrics.NewRegisteredMeter("state/snapshot/bloom/storage/miss", nil)
    79  
    80  	// ErrSnapshotStale is returned from data accessors if the underlying snapshot
    81  	// layer had been invalidated due to the chain progressing forward far enough
    82  	// to not maintain the layer's original state.
    83  	ErrSnapshotStale = errors.New("snapshot stale")
    84  
    85  	// ErrNotCoveredYet is returned from data accessors if the underlying snapshot
    86  	// is being generated currently and the requested data item is not yet in the
    87  	// range of accounts covered.
    88  	ErrNotCoveredYet = errors.New("not covered yet")
    89  
    90  	// ErrNotConstructed is returned if the callers want to iterate the snapshot
    91  	// while the generation is not finished yet.
    92  	ErrNotConstructed = errors.New("snapshot is not constructed")
    93  
    94  	// errSnapshotCycle is returned if a snapshot is attempted to be inserted
    95  	// that forms a cycle in the snapshot tree.
    96  	errSnapshotCycle = errors.New("snapshot cycle")
    97  )
    98  
    99  // Snapshot represents the functionality supported by a snapshot storage layer.
   100  type Snapshot interface {
   101  	// Root returns the root hash for which this snapshot was made.
   102  	Root() common.Hash
   103  
   104  	// Account directly retrieves the account associated with a particular hash in
   105  	// the snapshot slim data format.
   106  	Account(hash common.Hash) (*Account, error)
   107  
   108  	// AccountRLP directly retrieves the account RLP associated with a particular
   109  	// hash in the snapshot slim data format.
   110  	AccountRLP(hash common.Hash) ([]byte, error)
   111  
   112  	// Storage directly retrieves the storage data associated with a particular hash,
   113  	// within a particular account.
   114  	Storage(accountHash, storageHash common.Hash) ([]byte, error)
   115  }
   116  
   117  // snapshot is the internal version of the snapshot data layer that supports some
   118  // additional methods compared to the public API.
   119  type snapshot interface {
   120  	Snapshot
   121  
   122  	// Parent returns the subsequent layer of a snapshot, or nil if the base was
   123  	// reached.
   124  	//
   125  	// Note, the method is an internal helper to avoid type switching between the
   126  	// disk and diff layers. There is no locking involved.
   127  	Parent() snapshot
   128  
   129  	// Update creates a new layer on top of the existing snapshot diff tree with
   130  	// the specified data items.
   131  	//
   132  	// Note, the maps are retained by the method to avoid copying everything.
   133  	Update(blockRoot common.Hash, destructs map[common.Hash]struct{}, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer
   134  
   135  	// Journal commits an entire diff hierarchy to disk into a single journal entry.
   136  	// This is meant to be used during shutdown to persist the snapshot without
   137  	// flattening everything down (bad for reorgs).
   138  	Journal(buffer *bytes.Buffer) (common.Hash, error)
   139  
   140  	// Stale return whether this layer has become stale (was flattened across) or
   141  	// if it's still live.
   142  	Stale() bool
   143  
   144  	// AccountIterator creates an account iterator over an arbitrary layer.
   145  	AccountIterator(seek common.Hash) AccountIterator
   146  
   147  	// StorageIterator creates a storage iterator over an arbitrary layer.
   148  	StorageIterator(account common.Hash, seek common.Hash) (StorageIterator, bool)
   149  }
   150  
   151  // Tree is an Ethereum state snapshot tree. It consists of one persistent base
   152  // layer backed by a key-value store, on top of which arbitrarily many in-memory
   153  // diff layers are topped. The memory diffs can form a tree with branching, but
   154  // the disk layer is singleton and common to all. If a reorg goes deeper than the
   155  // disk layer, everything needs to be deleted.
   156  //
   157  // The goal of a state snapshot is twofold: to allow direct access to account and
   158  // storage data to avoid expensive multi-level trie lookups; and to allow sorted,
   159  // cheap iteration of the account/storage tries for sync aid.
   160  type Tree struct {
   161  	diskdb ethdb.KeyValueStore      // Persistent database to store the snapshot
   162  	triedb *trie.Database           // In-memory cache to access the trie through
   163  	cache  int                      // Megabytes permitted to use for read caches
   164  	layers map[common.Hash]snapshot // Collection of all known layers
   165  	lock   sync.RWMutex
   166  
   167  	// Test hooks
   168  	onFlatten func() // Hook invoked when the bottom most diff layers are flattened
   169  }
   170  
   171  // New attempts to load an already existing snapshot from a persistent key-value
   172  // store (with a number of memory layers from a journal), ensuring that the head
   173  // of the snapshot matches the expected one.
   174  //
   175  // If the snapshot is missing or the disk layer is broken, the snapshot will be
   176  // reconstructed using both the existing data and the state trie.
   177  // The repair happens on a background thread.
   178  //
   179  // If the memory layers in the journal do not match the disk layer (e.g. there is
   180  // a gap) or the journal is missing, there are two repair cases:
   181  //
   182  // - if the 'recovery' parameter is true, all memory diff-layers will be discarded.
   183  //   This case happens when the snapshot is 'ahead' of the state trie.
   184  // - otherwise, the entire snapshot is considered invalid and will be recreated on
   185  //   a background thread.
   186  func New(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int, root common.Hash, async bool, rebuild bool, recovery bool) (*Tree, error) {
   187  	// Create a new, empty snapshot tree
   188  	if triedb.Zktrie {
   189  		panic("zktrie does not support snapshot yet")
   190  	}
   191  	snap := &Tree{
   192  		diskdb: diskdb,
   193  		triedb: triedb,
   194  		cache:  cache,
   195  		layers: make(map[common.Hash]snapshot),
   196  	}
   197  	if !async {
   198  		defer snap.waitBuild()
   199  	}
   200  	// Attempt to load a previously persisted snapshot and rebuild one if failed
   201  	head, disabled, err := loadSnapshot(diskdb, triedb, cache, root, recovery)
   202  	if disabled {
   203  		log.Warn("Snapshot maintenance disabled (syncing)")
   204  		return snap, nil
   205  	}
   206  	if err != nil {
   207  		if rebuild {
   208  			log.Warn("Failed to load snapshot, regenerating", "err", err)
   209  			snap.Rebuild(root)
   210  			return snap, nil
   211  		}
   212  		return nil, err // Bail out the error, don't rebuild automatically.
   213  	}
   214  	// Existing snapshot loaded, seed all the layers
   215  	for head != nil {
   216  		snap.layers[head.Root()] = head
   217  		head = head.Parent()
   218  	}
   219  	return snap, nil
   220  }
   221  
   222  // waitBuild blocks until the snapshot finishes rebuilding. This method is meant
   223  // to be used by tests to ensure we're testing what we believe we are.
   224  func (t *Tree) waitBuild() {
   225  	// Find the rebuild termination channel
   226  	var done chan struct{}
   227  
   228  	t.lock.RLock()
   229  	for _, layer := range t.layers {
   230  		if layer, ok := layer.(*diskLayer); ok {
   231  			done = layer.genPending
   232  			break
   233  		}
   234  	}
   235  	t.lock.RUnlock()
   236  
   237  	// Wait until the snapshot is generated
   238  	if done != nil {
   239  		<-done
   240  	}
   241  }
   242  
   243  // Disable interrupts any pending snapshot generator, deletes all the snapshot
   244  // layers in memory and marks snapshots disabled globally. In order to resume
   245  // the snapshot functionality, the caller must invoke Rebuild.
   246  func (t *Tree) Disable() {
   247  	// Interrupt any live snapshot layers
   248  	t.lock.Lock()
   249  	defer t.lock.Unlock()
   250  
   251  	for _, layer := range t.layers {
   252  		switch layer := layer.(type) {
   253  		case *diskLayer:
   254  			// If the base layer is generating, abort it
   255  			if layer.genAbort != nil {
   256  				abort := make(chan *generatorStats)
   257  				layer.genAbort <- abort
   258  				<-abort
   259  			}
   260  			// Layer should be inactive now, mark it as stale
   261  			layer.lock.Lock()
   262  			layer.stale = true
   263  			layer.lock.Unlock()
   264  
   265  		case *diffLayer:
   266  			// If the layer is a simple diff, simply mark as stale
   267  			layer.lock.Lock()
   268  			atomic.StoreUint32(&layer.stale, 1)
   269  			layer.lock.Unlock()
   270  
   271  		default:
   272  			panic(fmt.Sprintf("unknown layer type: %T", layer))
   273  		}
   274  	}
   275  	t.layers = map[common.Hash]snapshot{}
   276  
   277  	// Delete all snapshot liveness information from the database
   278  	batch := t.diskdb.NewBatch()
   279  
   280  	rawdb.WriteSnapshotDisabled(batch)
   281  	rawdb.DeleteSnapshotRoot(batch)
   282  	rawdb.DeleteSnapshotJournal(batch)
   283  	rawdb.DeleteSnapshotGenerator(batch)
   284  	rawdb.DeleteSnapshotRecoveryNumber(batch)
   285  	// Note, we don't delete the sync progress
   286  
   287  	if err := batch.Write(); err != nil {
   288  		log.Crit("Failed to disable snapshots", "err", err)
   289  	}
   290  }
   291  
   292  // Snapshot retrieves a snapshot belonging to the given block root, or nil if no
   293  // snapshot is maintained for that block.
   294  func (t *Tree) Snapshot(blockRoot common.Hash) Snapshot {
   295  	t.lock.RLock()
   296  	defer t.lock.RUnlock()
   297  
   298  	return t.layers[blockRoot]
   299  }
   300  
   301  // Snapshots returns all visited layers from the topmost layer with specific
   302  // root and traverses downward. The layer amount is limited by the given number.
   303  // If nodisk is set, then disk layer is excluded.
   304  func (t *Tree) Snapshots(root common.Hash, limits int, nodisk bool) []Snapshot {
   305  	t.lock.RLock()
   306  	defer t.lock.RUnlock()
   307  
   308  	if limits == 0 {
   309  		return nil
   310  	}
   311  	layer := t.layers[root]
   312  	if layer == nil {
   313  		return nil
   314  	}
   315  	var ret []Snapshot
   316  	for {
   317  		if _, isdisk := layer.(*diskLayer); isdisk && nodisk {
   318  			break
   319  		}
   320  		ret = append(ret, layer)
   321  		limits -= 1
   322  		if limits == 0 {
   323  			break
   324  		}
   325  		parent := layer.Parent()
   326  		if parent == nil {
   327  			break
   328  		}
   329  		layer = parent
   330  	}
   331  	return ret
   332  }
   333  
   334  // Update adds a new snapshot into the tree, if that can be linked to an existing
   335  // old parent. It is disallowed to insert a disk layer (the origin of all).
   336  func (t *Tree) Update(blockRoot common.Hash, parentRoot common.Hash, destructs map[common.Hash]struct{}, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) error {
   337  	// Reject noop updates to avoid self-loops in the snapshot tree. This is a
   338  	// special case that can only happen for Clique networks where empty blocks
   339  	// don't modify the state (0 block subsidy).
   340  	//
   341  	// Although we could silently ignore this internally, it should be the caller's
   342  	// responsibility to avoid even attempting to insert such a snapshot.
   343  	if blockRoot == parentRoot {
   344  		return errSnapshotCycle
   345  	}
   346  	// Generate a new snapshot on top of the parent
   347  	parent := t.Snapshot(parentRoot)
   348  	if parent == nil {
   349  		return fmt.Errorf("parent [%#x] snapshot missing", parentRoot)
   350  	}
   351  	snap := parent.(snapshot).Update(blockRoot, destructs, accounts, storage)
   352  
   353  	// Save the new snapshot for later
   354  	t.lock.Lock()
   355  	defer t.lock.Unlock()
   356  
   357  	t.layers[snap.root] = snap
   358  	return nil
   359  }
   360  
   361  // Cap traverses downwards the snapshot tree from a head block hash until the
   362  // number of allowed layers are crossed. All layers beyond the permitted number
   363  // are flattened downwards.
   364  //
   365  // Note, the final diff layer count in general will be one more than the amount
   366  // requested. This happens because the bottom-most diff layer is the accumulator
   367  // which may or may not overflow and cascade to disk. Since this last layer's
   368  // survival is only known *after* capping, we need to omit it from the count if
   369  // we want to ensure that *at least* the requested number of diff layers remain.
   370  func (t *Tree) Cap(root common.Hash, layers int) error {
   371  	// Retrieve the head snapshot to cap from
   372  	snap := t.Snapshot(root)
   373  	if snap == nil {
   374  		return fmt.Errorf("snapshot [%#x] missing", root)
   375  	}
   376  	diff, ok := snap.(*diffLayer)
   377  	if !ok {
   378  		return fmt.Errorf("snapshot [%#x] is disk layer", root)
   379  	}
   380  	// If the generator is still running, use a more aggressive cap
   381  	diff.origin.lock.RLock()
   382  	if diff.origin.genMarker != nil && layers > 8 {
   383  		layers = 8
   384  	}
   385  	diff.origin.lock.RUnlock()
   386  
   387  	// Run the internal capping and discard all stale layers
   388  	t.lock.Lock()
   389  	defer t.lock.Unlock()
   390  
   391  	// Flattening the bottom-most diff layer requires special casing since there's
   392  	// no child to rewire to the grandparent. In that case we can fake a temporary
   393  	// child for the capping and then remove it.
   394  	if layers == 0 {
   395  		// If full commit was requested, flatten the diffs and merge onto disk
   396  		diff.lock.RLock()
   397  		base := diffToDisk(diff.flatten().(*diffLayer))
   398  		diff.lock.RUnlock()
   399  
   400  		// Replace the entire snapshot tree with the flat base
   401  		t.layers = map[common.Hash]snapshot{base.root: base}
   402  		return nil
   403  	}
   404  	persisted := t.cap(diff, layers)
   405  
   406  	// Remove any layer that is stale or links into a stale layer
   407  	children := make(map[common.Hash][]common.Hash)
   408  	for root, snap := range t.layers {
   409  		if diff, ok := snap.(*diffLayer); ok {
   410  			parent := diff.parent.Root()
   411  			children[parent] = append(children[parent], root)
   412  		}
   413  	}
   414  	var remove func(root common.Hash)
   415  	remove = func(root common.Hash) {
   416  		delete(t.layers, root)
   417  		for _, child := range children[root] {
   418  			remove(child)
   419  		}
   420  		delete(children, root)
   421  	}
   422  	for root, snap := range t.layers {
   423  		if snap.Stale() {
   424  			remove(root)
   425  		}
   426  	}
   427  	// If the disk layer was modified, regenerate all the cumulative blooms
   428  	if persisted != nil {
   429  		var rebloom func(root common.Hash)
   430  		rebloom = func(root common.Hash) {
   431  			if diff, ok := t.layers[root].(*diffLayer); ok {
   432  				diff.rebloom(persisted)
   433  			}
   434  			for _, child := range children[root] {
   435  				rebloom(child)
   436  			}
   437  		}
   438  		rebloom(persisted.root)
   439  	}
   440  	return nil
   441  }
   442  
   443  // cap traverses downwards the diff tree until the number of allowed layers are
   444  // crossed. All diffs beyond the permitted number are flattened downwards. If the
   445  // layer limit is reached, memory cap is also enforced (but not before).
   446  //
   447  // The method returns the new disk layer if diffs were persisted into it.
   448  //
   449  // Note, the final diff layer count in general will be one more than the amount
   450  // requested. This happens because the bottom-most diff layer is the accumulator
   451  // which may or may not overflow and cascade to disk. Since this last layer's
   452  // survival is only known *after* capping, we need to omit it from the count if
   453  // we want to ensure that *at least* the requested number of diff layers remain.
   454  func (t *Tree) cap(diff *diffLayer, layers int) *diskLayer {
   455  	// Dive until we run out of layers or reach the persistent database
   456  	for i := 0; i < layers-1; i++ {
   457  		// If we still have diff layers below, continue down
   458  		if parent, ok := diff.parent.(*diffLayer); ok {
   459  			diff = parent
   460  		} else {
   461  			// Diff stack too shallow, return without modifications
   462  			return nil
   463  		}
   464  	}
   465  	// We're out of layers, flatten anything below, stopping if it's the disk or if
   466  	// the memory limit is not yet exceeded.
   467  	switch parent := diff.parent.(type) {
   468  	case *diskLayer:
   469  		return nil
   470  
   471  	case *diffLayer:
   472  		// Hold the write lock until the flattened parent is linked correctly.
   473  		// Otherwise, the stale layer may be accessed by external reads in the
   474  		// meantime.
   475  		diff.lock.Lock()
   476  		defer diff.lock.Unlock()
   477  
   478  		// Flatten the parent into the grandparent. The flattening internally obtains a
   479  		// write lock on grandparent.
   480  		flattened := parent.flatten().(*diffLayer)
   481  		t.layers[flattened.root] = flattened
   482  
   483  		// Invoke the hook if it's registered. Ugly hack.
   484  		if t.onFlatten != nil {
   485  			t.onFlatten()
   486  		}
   487  		diff.parent = flattened
   488  		if flattened.memory < aggregatorMemoryLimit {
   489  			// Accumulator layer is smaller than the limit, so we can abort, unless
   490  			// there's a snapshot being generated currently. In that case, the trie
   491  			// will move from underneath the generator so we **must** merge all the
   492  			// partial data down into the snapshot and restart the generation.
   493  			if flattened.parent.(*diskLayer).genAbort == nil {
   494  				return nil
   495  			}
   496  		}
   497  	default:
   498  		panic(fmt.Sprintf("unknown data layer: %T", parent))
   499  	}
   500  	// If the bottom-most layer is larger than our memory cap, persist to disk
   501  	bottom := diff.parent.(*diffLayer)
   502  
   503  	bottom.lock.RLock()
   504  	base := diffToDisk(bottom)
   505  	bottom.lock.RUnlock()
   506  
   507  	t.layers[base.root] = base
   508  	diff.parent = base
   509  	return base
   510  }
   511  
   512  // diffToDisk merges a bottom-most diff into the persistent disk layer underneath
   513  // it. The method will panic if called onto a non-bottom-most diff layer.
   514  //
   515  // The disk layer persistence should be operated in an atomic way. All updates should
   516  // be discarded if the whole transition if not finished.
   517  func diffToDisk(bottom *diffLayer) *diskLayer {
   518  	var (
   519  		base  = bottom.parent.(*diskLayer)
   520  		batch = base.diskdb.NewBatch()
   521  		stats *generatorStats
   522  	)
   523  	// If the disk layer is running a snapshot generator, abort it
   524  	if base.genAbort != nil {
   525  		abort := make(chan *generatorStats)
   526  		base.genAbort <- abort
   527  		stats = <-abort
   528  	}
   529  	// Put the deletion in the batch writer, flush all updates in the final step.
   530  	rawdb.DeleteSnapshotRoot(batch)
   531  
   532  	// Mark the original base as stale as we're going to create a new wrapper
   533  	base.lock.Lock()
   534  	if base.stale {
   535  		panic("parent disk layer is stale") // we've committed into the same base from two children, boo
   536  	}
   537  	base.stale = true
   538  	base.lock.Unlock()
   539  
   540  	// Destroy all the destructed accounts from the database
   541  	for hash := range bottom.destructSet {
   542  		// Skip any account not covered yet by the snapshot
   543  		if base.genMarker != nil && bytes.Compare(hash[:], base.genMarker) > 0 {
   544  			continue
   545  		}
   546  		// Remove all storage slots
   547  		rawdb.DeleteAccountSnapshot(batch, hash)
   548  		base.cache.Set(hash[:], nil)
   549  
   550  		it := rawdb.IterateStorageSnapshots(base.diskdb, hash)
   551  		for it.Next() {
   552  			if key := it.Key(); len(key) == 65 { // TODO(karalabe): Yuck, we should move this into the iterator
   553  				batch.Delete(key)
   554  				base.cache.Del(key[1:])
   555  				snapshotFlushStorageItemMeter.Mark(1)
   556  
   557  				// Ensure we don't delete too much data blindly (contract can be
   558  				// huge). It's ok to flush, the root will go missing in case of a
   559  				// crash and we'll detect and regenerate the snapshot.
   560  				if batch.ValueSize() > ethdb.IdealBatchSize {
   561  					if err := batch.Write(); err != nil {
   562  						log.Crit("Failed to write storage deletions", "err", err)
   563  					}
   564  					batch.Reset()
   565  				}
   566  			}
   567  		}
   568  		it.Release()
   569  	}
   570  	// Push all updated accounts into the database
   571  	for hash, data := range bottom.accountData {
   572  		// Skip any account not covered yet by the snapshot
   573  		if base.genMarker != nil && bytes.Compare(hash[:], base.genMarker) > 0 {
   574  			continue
   575  		}
   576  		// Push the account to disk
   577  		rawdb.WriteAccountSnapshot(batch, hash, data)
   578  		base.cache.Set(hash[:], data)
   579  		snapshotCleanAccountWriteMeter.Mark(int64(len(data)))
   580  
   581  		snapshotFlushAccountItemMeter.Mark(1)
   582  		snapshotFlushAccountSizeMeter.Mark(int64(len(data)))
   583  
   584  		// Ensure we don't write too much data blindly. It's ok to flush, the
   585  		// root will go missing in case of a crash and we'll detect and regen
   586  		// the snapshot.
   587  		if batch.ValueSize() > ethdb.IdealBatchSize {
   588  			if err := batch.Write(); err != nil {
   589  				log.Crit("Failed to write storage deletions", "err", err)
   590  			}
   591  			batch.Reset()
   592  		}
   593  	}
   594  	// Push all the storage slots into the database
   595  	for accountHash, storage := range bottom.storageData {
   596  		// Skip any account not covered yet by the snapshot
   597  		if base.genMarker != nil && bytes.Compare(accountHash[:], base.genMarker) > 0 {
   598  			continue
   599  		}
   600  		// Generation might be mid-account, track that case too
   601  		midAccount := base.genMarker != nil && bytes.Equal(accountHash[:], base.genMarker[:common.HashLength])
   602  
   603  		for storageHash, data := range storage {
   604  			// Skip any slot not covered yet by the snapshot
   605  			if midAccount && bytes.Compare(storageHash[:], base.genMarker[common.HashLength:]) > 0 {
   606  				continue
   607  			}
   608  			if len(data) > 0 {
   609  				rawdb.WriteStorageSnapshot(batch, accountHash, storageHash, data)
   610  				base.cache.Set(append(accountHash[:], storageHash[:]...), data)
   611  				snapshotCleanStorageWriteMeter.Mark(int64(len(data)))
   612  			} else {
   613  				rawdb.DeleteStorageSnapshot(batch, accountHash, storageHash)
   614  				base.cache.Set(append(accountHash[:], storageHash[:]...), nil)
   615  			}
   616  			snapshotFlushStorageItemMeter.Mark(1)
   617  			snapshotFlushStorageSizeMeter.Mark(int64(len(data)))
   618  		}
   619  	}
   620  	// Update the snapshot block marker and write any remainder data
   621  	rawdb.WriteSnapshotRoot(batch, bottom.root)
   622  
   623  	// Write out the generator progress marker and report
   624  	journalProgress(batch, base.genMarker, stats)
   625  
   626  	// Flush all the updates in the single db operation. Ensure the
   627  	// disk layer transition is atomic.
   628  	if err := batch.Write(); err != nil {
   629  		log.Crit("Failed to write leftover snapshot", "err", err)
   630  	}
   631  	log.Debug("Journalled disk layer", "root", bottom.root, "complete", base.genMarker == nil)
   632  	res := &diskLayer{
   633  		root:       bottom.root,
   634  		cache:      base.cache,
   635  		diskdb:     base.diskdb,
   636  		triedb:     base.triedb,
   637  		genMarker:  base.genMarker,
   638  		genPending: base.genPending,
   639  	}
   640  	// If snapshot generation hasn't finished yet, port over all the starts and
   641  	// continue where the previous round left off.
   642  	//
   643  	// Note, the `base.genAbort` comparison is not used normally, it's checked
   644  	// to allow the tests to play with the marker without triggering this path.
   645  	if base.genMarker != nil && base.genAbort != nil {
   646  		res.genMarker = base.genMarker
   647  		res.genAbort = make(chan chan *generatorStats)
   648  		go res.generate(stats)
   649  	}
   650  	return res
   651  }
   652  
   653  // Journal commits an entire diff hierarchy to disk into a single journal entry.
   654  // This is meant to be used during shutdown to persist the snapshot without
   655  // flattening everything down (bad for reorgs).
   656  //
   657  // The method returns the root hash of the base layer that needs to be persisted
   658  // to disk as a trie too to allow continuing any pending generation op.
   659  func (t *Tree) Journal(root common.Hash) (common.Hash, error) {
   660  	// Retrieve the head snapshot to journal from var snap snapshot
   661  	snap := t.Snapshot(root)
   662  	if snap == nil {
   663  		return common.Hash{}, fmt.Errorf("snapshot [%#x] missing", root)
   664  	}
   665  	// Run the journaling
   666  	t.lock.Lock()
   667  	defer t.lock.Unlock()
   668  
   669  	// Firstly write out the metadata of journal
   670  	journal := new(bytes.Buffer)
   671  	if err := rlp.Encode(journal, journalVersion); err != nil {
   672  		return common.Hash{}, err
   673  	}
   674  	diskroot := t.diskRoot()
   675  	if diskroot == (common.Hash{}) {
   676  		return common.Hash{}, errors.New("invalid disk root")
   677  	}
   678  	// Secondly write out the disk layer root, ensure the
   679  	// diff journal is continuous with disk.
   680  	if err := rlp.Encode(journal, diskroot); err != nil {
   681  		return common.Hash{}, err
   682  	}
   683  	// Finally write out the journal of each layer in reverse order.
   684  	base, err := snap.(snapshot).Journal(journal)
   685  	if err != nil {
   686  		return common.Hash{}, err
   687  	}
   688  	// Store the journal into the database and return
   689  	rawdb.WriteSnapshotJournal(t.diskdb, journal.Bytes())
   690  	return base, nil
   691  }
   692  
   693  // Rebuild wipes all available snapshot data from the persistent database and
   694  // discard all caches and diff layers. Afterwards, it starts a new snapshot
   695  // generator with the given root hash.
   696  func (t *Tree) Rebuild(root common.Hash) {
   697  	t.lock.Lock()
   698  	defer t.lock.Unlock()
   699  
   700  	// Firstly delete any recovery flag in the database. Because now we are
   701  	// building a brand new snapshot. Also reenable the snapshot feature.
   702  	rawdb.DeleteSnapshotRecoveryNumber(t.diskdb)
   703  	rawdb.DeleteSnapshotDisabled(t.diskdb)
   704  
   705  	// Iterate over and mark all layers stale
   706  	for _, layer := range t.layers {
   707  		switch layer := layer.(type) {
   708  		case *diskLayer:
   709  			// If the base layer is generating, abort it and save
   710  			if layer.genAbort != nil {
   711  				abort := make(chan *generatorStats)
   712  				layer.genAbort <- abort
   713  				<-abort
   714  			}
   715  			// Layer should be inactive now, mark it as stale
   716  			layer.lock.Lock()
   717  			layer.stale = true
   718  			layer.lock.Unlock()
   719  
   720  		case *diffLayer:
   721  			// If the layer is a simple diff, simply mark as stale
   722  			layer.lock.Lock()
   723  			atomic.StoreUint32(&layer.stale, 1)
   724  			layer.lock.Unlock()
   725  
   726  		default:
   727  			panic(fmt.Sprintf("unknown layer type: %T", layer))
   728  		}
   729  	}
   730  	// Start generating a new snapshot from scratch on a background thread. The
   731  	// generator will run a wiper first if there's not one running right now.
   732  	log.Info("Rebuilding state snapshot")
   733  	t.layers = map[common.Hash]snapshot{
   734  		root: generateSnapshot(t.diskdb, t.triedb, t.cache, root),
   735  	}
   736  }
   737  
   738  // AccountIterator creates a new account iterator for the specified root hash and
   739  // seeks to a starting account hash.
   740  func (t *Tree) AccountIterator(root common.Hash, seek common.Hash) (AccountIterator, error) {
   741  	ok, err := t.generating()
   742  	if err != nil {
   743  		return nil, err
   744  	}
   745  	if ok {
   746  		return nil, ErrNotConstructed
   747  	}
   748  	return newFastAccountIterator(t, root, seek)
   749  }
   750  
   751  // StorageIterator creates a new storage iterator for the specified root hash and
   752  // account. The iterator will be move to the specific start position.
   753  func (t *Tree) StorageIterator(root common.Hash, account common.Hash, seek common.Hash) (StorageIterator, error) {
   754  	ok, err := t.generating()
   755  	if err != nil {
   756  		return nil, err
   757  	}
   758  	if ok {
   759  		return nil, ErrNotConstructed
   760  	}
   761  	return newFastStorageIterator(t, root, account, seek)
   762  }
   763  
   764  // Verify iterates the whole state(all the accounts as well as the corresponding storages)
   765  // with the specific root and compares the re-computed hash with the original one.
   766  func (t *Tree) Verify(root common.Hash) error {
   767  	acctIt, err := t.AccountIterator(root, common.Hash{})
   768  	if err != nil {
   769  		return err
   770  	}
   771  	defer acctIt.Release()
   772  
   773  	got, err := generateTrieRoot(nil, acctIt, common.Hash{}, stackTrieGenerate, func(db ethdb.KeyValueWriter, accountHash, codeHash common.Hash, stat *generateStats) (common.Hash, error) {
   774  		storageIt, err := t.StorageIterator(root, accountHash, common.Hash{})
   775  		if err != nil {
   776  			return common.Hash{}, err
   777  		}
   778  		defer storageIt.Release()
   779  
   780  		hash, err := generateTrieRoot(nil, storageIt, accountHash, stackTrieGenerate, nil, stat, false)
   781  		if err != nil {
   782  			return common.Hash{}, err
   783  		}
   784  		return hash, nil
   785  	}, newGenerateStats(), true)
   786  
   787  	if err != nil {
   788  		return err
   789  	}
   790  	if got != root {
   791  		return fmt.Errorf("state root hash mismatch: got %x, want %x", got, root)
   792  	}
   793  	return nil
   794  }
   795  
   796  // disklayer is an internal helper function to return the disk layer.
   797  // The lock of snapTree is assumed to be held already.
   798  func (t *Tree) disklayer() *diskLayer {
   799  	var snap snapshot
   800  	for _, s := range t.layers {
   801  		snap = s
   802  		break
   803  	}
   804  	if snap == nil {
   805  		return nil
   806  	}
   807  	switch layer := snap.(type) {
   808  	case *diskLayer:
   809  		return layer
   810  	case *diffLayer:
   811  		return layer.origin
   812  	default:
   813  		panic(fmt.Sprintf("%T: undefined layer", snap))
   814  	}
   815  }
   816  
   817  // diskRoot is a internal helper function to return the disk layer root.
   818  // The lock of snapTree is assumed to be held already.
   819  func (t *Tree) diskRoot() common.Hash {
   820  	disklayer := t.disklayer()
   821  	if disklayer == nil {
   822  		return common.Hash{}
   823  	}
   824  	return disklayer.Root()
   825  }
   826  
   827  // generating is an internal helper function which reports whether the snapshot
   828  // is still under the construction.
   829  func (t *Tree) generating() (bool, error) {
   830  	t.lock.Lock()
   831  	defer t.lock.Unlock()
   832  
   833  	layer := t.disklayer()
   834  	if layer == nil {
   835  		return false, errors.New("disk layer is missing")
   836  	}
   837  	layer.lock.RLock()
   838  	defer layer.lock.RUnlock()
   839  	return layer.genMarker != nil, nil
   840  }
   841  
   842  // diskRoot is a external helper function to return the disk layer root.
   843  func (t *Tree) DiskRoot() common.Hash {
   844  	t.lock.Lock()
   845  	defer t.lock.Unlock()
   846  
   847  	return t.diskRoot()
   848  }