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