github.com/ethereum/go-ethereum@v1.16.1/core/state/snapshot/generate.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
    18  
    19  import (
    20  	"bytes"
    21  	"errors"
    22  	"fmt"
    23  	"time"
    24  
    25  	"github.com/VictoriaMetrics/fastcache"
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/common/hexutil"
    28  	"github.com/ethereum/go-ethereum/core/rawdb"
    29  	"github.com/ethereum/go-ethereum/core/types"
    30  	"github.com/ethereum/go-ethereum/ethdb"
    31  	"github.com/ethereum/go-ethereum/log"
    32  	"github.com/ethereum/go-ethereum/rlp"
    33  	"github.com/ethereum/go-ethereum/trie"
    34  	"github.com/ethereum/go-ethereum/triedb"
    35  )
    36  
    37  var (
    38  	// accountCheckRange is the upper limit of the number of accounts involved in
    39  	// each range check. This is a value estimated based on experience. If this
    40  	// range is too large, the failure rate of range proof will increase. Otherwise,
    41  	// if the range is too small, the efficiency of the state recovery will decrease.
    42  	accountCheckRange = 128
    43  
    44  	// storageCheckRange is the upper limit of the number of storage slots involved
    45  	// in each range check. This is a value estimated based on experience. If this
    46  	// range is too large, the failure rate of range proof will increase. Otherwise,
    47  	// if the range is too small, the efficiency of the state recovery will decrease.
    48  	storageCheckRange = 1024
    49  
    50  	// errMissingTrie is returned if the target trie is missing while the generation
    51  	// is running. In this case the generation is aborted and wait the new signal.
    52  	errMissingTrie = errors.New("missing trie")
    53  )
    54  
    55  // generateSnapshot regenerates a brand new snapshot based on an existing state
    56  // database and head block asynchronously. The snapshot is returned immediately
    57  // and generation is continued in the background until done.
    58  func generateSnapshot(diskdb ethdb.KeyValueStore, triedb *triedb.Database, cache int, root common.Hash) *diskLayer {
    59  	// Create a new disk layer with an initialized state marker at zero
    60  	var (
    61  		stats     = &generatorStats{start: time.Now()}
    62  		batch     = diskdb.NewBatch()
    63  		genMarker = []byte{} // Initialized but empty!
    64  	)
    65  	rawdb.WriteSnapshotRoot(batch, root)
    66  	journalProgress(batch, genMarker, stats)
    67  	if err := batch.Write(); err != nil {
    68  		log.Crit("Failed to write initialized state marker", "err", err)
    69  	}
    70  	base := &diskLayer{
    71  		diskdb:     diskdb,
    72  		triedb:     triedb,
    73  		root:       root,
    74  		cache:      fastcache.New(cache * 1024 * 1024),
    75  		genMarker:  genMarker,
    76  		genPending: make(chan struct{}),
    77  		genAbort:   make(chan chan *generatorStats),
    78  	}
    79  	go base.generate(stats)
    80  	log.Debug("Start snapshot generation", "root", root)
    81  	return base
    82  }
    83  
    84  // journalProgress persists the generator stats into the database to resume later.
    85  func journalProgress(db ethdb.KeyValueWriter, marker []byte, stats *generatorStats) {
    86  	// Write out the generator marker. Note it's a standalone disk layer generator
    87  	// which is not mixed with journal. It's ok if the generator is persisted while
    88  	// journal is not.
    89  	entry := journalGenerator{
    90  		Done:   marker == nil,
    91  		Marker: marker,
    92  	}
    93  	if stats != nil {
    94  		entry.Accounts = stats.accounts
    95  		entry.Slots = stats.slots
    96  		entry.Storage = uint64(stats.storage)
    97  	}
    98  	blob, err := rlp.EncodeToBytes(entry)
    99  	if err != nil {
   100  		panic(err) // Cannot happen, here to catch dev errors
   101  	}
   102  	var logstr string
   103  	switch {
   104  	case marker == nil:
   105  		logstr = "done"
   106  	case bytes.Equal(marker, []byte{}):
   107  		logstr = "empty"
   108  	case len(marker) == common.HashLength:
   109  		logstr = fmt.Sprintf("%#x", marker)
   110  	default:
   111  		logstr = fmt.Sprintf("%#x:%#x", marker[:common.HashLength], marker[common.HashLength:])
   112  	}
   113  	log.Debug("Journalled generator progress", "progress", logstr)
   114  	rawdb.WriteSnapshotGenerator(db, blob)
   115  }
   116  
   117  // proofResult contains the output of range proving which can be used
   118  // for further processing regardless if it is successful or not.
   119  type proofResult struct {
   120  	keys     [][]byte   // The key set of all elements being iterated, even proving is failed
   121  	vals     [][]byte   // The val set of all elements being iterated, even proving is failed
   122  	diskMore bool       // Set when the database has extra snapshot states since last iteration
   123  	trieMore bool       // Set when the trie has extra snapshot states(only meaningful for successful proving)
   124  	proofErr error      // Indicator whether the given state range is valid or not
   125  	tr       *trie.Trie // The trie, in case the trie was resolved by the prover (may be nil)
   126  }
   127  
   128  // valid returns the indicator that range proof is successful or not.
   129  func (result *proofResult) valid() bool {
   130  	return result.proofErr == nil
   131  }
   132  
   133  // last returns the last verified element key regardless of whether the range proof is
   134  // successful or not. Nil is returned if nothing involved in the proving.
   135  func (result *proofResult) last() []byte {
   136  	var last []byte
   137  	if len(result.keys) > 0 {
   138  		last = result.keys[len(result.keys)-1]
   139  	}
   140  	return last
   141  }
   142  
   143  // forEach iterates all the visited elements and applies the given callback on them.
   144  // The iteration is aborted if the callback returns non-nil error.
   145  func (result *proofResult) forEach(callback func(key []byte, val []byte) error) error {
   146  	for i := 0; i < len(result.keys); i++ {
   147  		key, val := result.keys[i], result.vals[i]
   148  		if err := callback(key, val); err != nil {
   149  			return err
   150  		}
   151  	}
   152  	return nil
   153  }
   154  
   155  // proveRange proves the snapshot segment with particular prefix is "valid".
   156  // The iteration start point will be assigned if the iterator is restored from
   157  // the last interruption. Max will be assigned in order to limit the maximum
   158  // amount of data involved in each iteration.
   159  //
   160  // The proof result will be returned if the range proving is finished, otherwise
   161  // the error will be returned to abort the entire procedure.
   162  func (dl *diskLayer) proveRange(ctx *generatorContext, trieId *trie.ID, prefix []byte, kind string, origin []byte, max int, valueConvertFn func([]byte) ([]byte, error)) (*proofResult, error) {
   163  	var (
   164  		keys     [][]byte
   165  		vals     [][]byte
   166  		proof    = rawdb.NewMemoryDatabase()
   167  		diskMore = false
   168  		iter     = ctx.iterator(kind)
   169  		start    = time.Now()
   170  		min      = append(prefix, origin...)
   171  	)
   172  	for iter.Next() {
   173  		// Ensure the iterated item is always equal or larger than the given origin.
   174  		key := iter.Key()
   175  		if bytes.Compare(key, min) < 0 {
   176  			return nil, errors.New("invalid iteration position")
   177  		}
   178  		// Ensure the iterated item still fall in the specified prefix. If
   179  		// not which means the items in the specified area are all visited.
   180  		// Move the iterator a step back since we iterate one extra element
   181  		// out.
   182  		if !bytes.Equal(key[:len(prefix)], prefix) {
   183  			iter.Hold()
   184  			break
   185  		}
   186  		// Break if we've reached the max size, and signal that we're not
   187  		// done yet. Move the iterator a step back since we iterate one
   188  		// extra element out.
   189  		if len(keys) == max {
   190  			iter.Hold()
   191  			diskMore = true
   192  			break
   193  		}
   194  		keys = append(keys, common.CopyBytes(key[len(prefix):]))
   195  
   196  		if valueConvertFn == nil {
   197  			vals = append(vals, common.CopyBytes(iter.Value()))
   198  		} else {
   199  			val, err := valueConvertFn(iter.Value())
   200  			if err != nil {
   201  				// Special case, the state data is corrupted (invalid slim-format account),
   202  				// don't abort the entire procedure directly. Instead, let the fallback
   203  				// generation to heal the invalid data.
   204  				//
   205  				// Here append the original value to ensure that the number of key and
   206  				// value are aligned.
   207  				vals = append(vals, common.CopyBytes(iter.Value()))
   208  				log.Error("Failed to convert account state data", "err", err)
   209  			} else {
   210  				vals = append(vals, val)
   211  			}
   212  		}
   213  	}
   214  	// Update metrics for database iteration and merkle proving
   215  	if kind == snapStorage {
   216  		snapStorageSnapReadCounter.Inc(time.Since(start).Nanoseconds())
   217  	} else {
   218  		snapAccountSnapReadCounter.Inc(time.Since(start).Nanoseconds())
   219  	}
   220  	defer func(start time.Time) {
   221  		if kind == snapStorage {
   222  			snapStorageProveCounter.Inc(time.Since(start).Nanoseconds())
   223  		} else {
   224  			snapAccountProveCounter.Inc(time.Since(start).Nanoseconds())
   225  		}
   226  	}(time.Now())
   227  
   228  	// The snap state is exhausted, pass the entire key/val set for verification
   229  	root := trieId.Root
   230  	if origin == nil && !diskMore {
   231  		stackTr := trie.NewStackTrie(nil)
   232  		for i, key := range keys {
   233  			if err := stackTr.Update(key, vals[i]); err != nil {
   234  				return nil, err
   235  			}
   236  		}
   237  		if gotRoot := stackTr.Hash(); gotRoot != root {
   238  			return &proofResult{
   239  				keys:     keys,
   240  				vals:     vals,
   241  				proofErr: fmt.Errorf("wrong root: have %#x want %#x", gotRoot, root),
   242  			}, nil
   243  		}
   244  		return &proofResult{keys: keys, vals: vals}, nil
   245  	}
   246  	// Snap state is chunked, generate edge proofs for verification.
   247  	tr, err := trie.New(trieId, dl.triedb)
   248  	if err != nil {
   249  		ctx.stats.Log("Trie missing, state snapshotting paused", dl.root, dl.genMarker)
   250  		return nil, errMissingTrie
   251  	}
   252  	// Generate the Merkle proofs for the first and last element
   253  	if origin == nil {
   254  		origin = common.Hash{}.Bytes()
   255  	}
   256  	if err := tr.Prove(origin, proof); err != nil {
   257  		log.Debug("Failed to prove range", "kind", kind, "origin", origin, "err", err)
   258  		return &proofResult{
   259  			keys:     keys,
   260  			vals:     vals,
   261  			diskMore: diskMore,
   262  			proofErr: err,
   263  			tr:       tr,
   264  		}, nil
   265  	}
   266  	if len(keys) > 0 {
   267  		if err := tr.Prove(keys[len(keys)-1], proof); err != nil {
   268  			log.Debug("Failed to prove range", "kind", kind, "last", keys[len(keys)-1], "err", err)
   269  			return &proofResult{
   270  				keys:     keys,
   271  				vals:     vals,
   272  				diskMore: diskMore,
   273  				proofErr: err,
   274  				tr:       tr,
   275  			}, nil
   276  		}
   277  	}
   278  	// Verify the snapshot segment with range prover, ensure that all flat states
   279  	// in this range correspond to merkle trie.
   280  	cont, err := trie.VerifyRangeProof(root, origin, keys, vals, proof)
   281  	return &proofResult{
   282  			keys:     keys,
   283  			vals:     vals,
   284  			diskMore: diskMore,
   285  			trieMore: cont,
   286  			proofErr: err,
   287  			tr:       tr},
   288  		nil
   289  }
   290  
   291  // onStateCallback is a function that is called by generateRange, when processing a range of
   292  // accounts or storage slots. For each element, the callback is invoked.
   293  //
   294  // - If 'delete' is true, then this element (and potential slots) needs to be deleted from the snapshot.
   295  // - If 'write' is true, then this element needs to be updated with the 'val'.
   296  // - If 'write' is false, then this element is already correct, and needs no update.
   297  // The 'val' is the canonical encoding of the value (not the slim format for accounts)
   298  //
   299  // However, for accounts, the storage trie of the account needs to be checked. Also,
   300  // dangling storages(storage exists but the corresponding account is missing) need to
   301  // be cleaned up.
   302  type onStateCallback func(key []byte, val []byte, write bool, delete bool) error
   303  
   304  // generateRange generates the state segment with particular prefix. Generation can
   305  // either verify the correctness of existing state through range-proof and skip
   306  // generation, or iterate trie to regenerate state on demand.
   307  func (dl *diskLayer) generateRange(ctx *generatorContext, trieId *trie.ID, prefix []byte, kind string, origin []byte, max int, onState onStateCallback, valueConvertFn func([]byte) ([]byte, error)) (bool, []byte, error) {
   308  	// Use range prover to check the validity of the flat state in the range
   309  	result, err := dl.proveRange(ctx, trieId, prefix, kind, origin, max, valueConvertFn)
   310  	if err != nil {
   311  		return false, nil, err
   312  	}
   313  	last := result.last()
   314  
   315  	// Construct contextual logger
   316  	logCtx := []interface{}{"kind", kind, "prefix", hexutil.Encode(prefix)}
   317  	if len(origin) > 0 {
   318  		logCtx = append(logCtx, "origin", hexutil.Encode(origin))
   319  	}
   320  	logger := log.New(logCtx...)
   321  
   322  	// The range prover says the range is correct, skip trie iteration
   323  	if result.valid() {
   324  		snapSuccessfulRangeProofMeter.Mark(1)
   325  		logger.Trace("Proved state range", "last", hexutil.Encode(last))
   326  
   327  		// The verification is passed, process each state with the given
   328  		// callback function. If this state represents a contract, the
   329  		// corresponding storage check will be performed in the callback
   330  		if err := result.forEach(func(key []byte, val []byte) error { return onState(key, val, false, false) }); err != nil {
   331  			return false, nil, err
   332  		}
   333  		// Only abort the iteration when both database and trie are exhausted
   334  		return !result.diskMore && !result.trieMore, last, nil
   335  	}
   336  	logger.Trace("Detected outdated state range", "last", hexutil.Encode(last), "err", result.proofErr)
   337  	snapFailedRangeProofMeter.Mark(1)
   338  
   339  	// Special case, the entire trie is missing. In the original trie scheme,
   340  	// all the duplicated subtries will be filtered out (only one copy of data
   341  	// will be stored). While in the snapshot model, all the storage tries
   342  	// belong to different contracts will be kept even they are duplicated.
   343  	// Track it to a certain extent remove the noise data used for statistics.
   344  	if origin == nil && last == nil {
   345  		meter := snapMissallAccountMeter
   346  		if kind == snapStorage {
   347  			meter = snapMissallStorageMeter
   348  		}
   349  		meter.Mark(1)
   350  	}
   351  	// We use the snap data to build up a cache which can be used by the
   352  	// main account trie as a primary lookup when resolving hashes
   353  	var resolver trie.NodeResolver
   354  	if len(result.keys) > 0 {
   355  		tr := trie.NewEmpty(nil)
   356  		for i, key := range result.keys {
   357  			tr.Update(key, result.vals[i])
   358  		}
   359  		_, nodes := tr.Commit(false)
   360  		hashSet := nodes.HashSet()
   361  		resolver = func(owner common.Hash, path []byte, hash common.Hash) []byte {
   362  			return hashSet[hash]
   363  		}
   364  	}
   365  	// Construct the trie for state iteration, reuse the trie
   366  	// if it's already opened with some nodes resolved.
   367  	tr := result.tr
   368  	if tr == nil {
   369  		tr, err = trie.New(trieId, dl.triedb)
   370  		if err != nil {
   371  			ctx.stats.Log("Trie missing, state snapshotting paused", dl.root, dl.genMarker)
   372  			return false, nil, errMissingTrie
   373  		}
   374  	}
   375  	var (
   376  		trieMore       bool
   377  		kvkeys, kvvals = result.keys, result.vals
   378  
   379  		// counters
   380  		count     = 0 // number of states delivered by iterator
   381  		created   = 0 // states created from the trie
   382  		updated   = 0 // states updated from the trie
   383  		deleted   = 0 // states not in trie, but were in snapshot
   384  		untouched = 0 // states already correct
   385  
   386  		// timers
   387  		start    = time.Now()
   388  		internal time.Duration
   389  	)
   390  	nodeIt, err := tr.NodeIterator(origin)
   391  	if err != nil {
   392  		return false, nil, err
   393  	}
   394  	nodeIt.AddResolver(resolver)
   395  	iter := trie.NewIterator(nodeIt)
   396  
   397  	for iter.Next() {
   398  		if last != nil && bytes.Compare(iter.Key, last) > 0 {
   399  			trieMore = true
   400  			break
   401  		}
   402  		count++
   403  		write := true
   404  		created++
   405  		for len(kvkeys) > 0 {
   406  			if cmp := bytes.Compare(kvkeys[0], iter.Key); cmp < 0 {
   407  				// delete the key
   408  				istart := time.Now()
   409  				if err := onState(kvkeys[0], nil, false, true); err != nil {
   410  					return false, nil, err
   411  				}
   412  				kvkeys = kvkeys[1:]
   413  				kvvals = kvvals[1:]
   414  				deleted++
   415  				internal += time.Since(istart)
   416  				continue
   417  			} else if cmp == 0 {
   418  				// the snapshot key can be overwritten
   419  				created--
   420  				if write = !bytes.Equal(kvvals[0], iter.Value); write {
   421  					updated++
   422  				} else {
   423  					untouched++
   424  				}
   425  				kvkeys = kvkeys[1:]
   426  				kvvals = kvvals[1:]
   427  			}
   428  			break
   429  		}
   430  		istart := time.Now()
   431  		if err := onState(iter.Key, iter.Value, write, false); err != nil {
   432  			return false, nil, err
   433  		}
   434  		internal += time.Since(istart)
   435  	}
   436  	if iter.Err != nil {
   437  		// Trie errors should never happen. Still, in case of a bug, expose the
   438  		// error here, as the outer code will presume errors are interrupts, not
   439  		// some deeper issues.
   440  		log.Error("State snapshotter failed to iterate trie", "err", iter.Err)
   441  		return false, nil, iter.Err
   442  	}
   443  	// Delete all stale snapshot states remaining
   444  	istart := time.Now()
   445  	for _, key := range kvkeys {
   446  		if err := onState(key, nil, false, true); err != nil {
   447  			return false, nil, err
   448  		}
   449  		deleted += 1
   450  	}
   451  	internal += time.Since(istart)
   452  
   453  	// Update metrics for counting trie iteration
   454  	if kind == snapStorage {
   455  		snapStorageTrieReadCounter.Inc((time.Since(start) - internal).Nanoseconds())
   456  	} else {
   457  		snapAccountTrieReadCounter.Inc((time.Since(start) - internal).Nanoseconds())
   458  	}
   459  	logger.Debug("Regenerated state range", "root", trieId.Root, "last", hexutil.Encode(last),
   460  		"count", count, "created", created, "updated", updated, "untouched", untouched, "deleted", deleted)
   461  
   462  	// If there are either more trie items, or there are more snap items
   463  	// (in the next segment), then we need to keep working
   464  	return !trieMore && !result.diskMore, last, nil
   465  }
   466  
   467  // checkAndFlush checks if an interruption signal is received or the
   468  // batch size has exceeded the allowance.
   469  func (dl *diskLayer) checkAndFlush(ctx *generatorContext, current []byte) error {
   470  	var abort chan *generatorStats
   471  	select {
   472  	case abort = <-dl.genAbort:
   473  	default:
   474  	}
   475  	if ctx.batch.ValueSize() > ethdb.IdealBatchSize || abort != nil {
   476  		if bytes.Compare(current, dl.genMarker) < 0 {
   477  			log.Error("Snapshot generator went backwards", "current", fmt.Sprintf("%x", current), "genMarker", fmt.Sprintf("%x", dl.genMarker))
   478  		}
   479  		// Flush out the batch anyway no matter it's empty or not.
   480  		// It's possible that all the states are recovered and the
   481  		// generation indeed makes progress.
   482  		journalProgress(ctx.batch, current, ctx.stats)
   483  
   484  		if err := ctx.batch.Write(); err != nil {
   485  			return err
   486  		}
   487  		ctx.batch.Reset()
   488  
   489  		dl.lock.Lock()
   490  		dl.genMarker = current
   491  		dl.lock.Unlock()
   492  
   493  		if abort != nil {
   494  			ctx.stats.Log("Aborting state snapshot generation", dl.root, current)
   495  			return newAbortErr(abort) // bubble up an error for interruption
   496  		}
   497  		// Don't hold the iterators too long, release them to let compactor works
   498  		ctx.reopenIterator(snapAccount)
   499  		ctx.reopenIterator(snapStorage)
   500  	}
   501  	if time.Since(ctx.logged) > 8*time.Second {
   502  		ctx.stats.Log("Generating state snapshot", dl.root, current)
   503  		ctx.logged = time.Now()
   504  	}
   505  	return nil
   506  }
   507  
   508  // generateStorages generates the missing storage slots of the specific contract.
   509  // It's supposed to restart the generation from the given origin position.
   510  func generateStorages(ctx *generatorContext, dl *diskLayer, stateRoot common.Hash, account common.Hash, storageRoot common.Hash, storeMarker []byte) error {
   511  	onStorage := func(key []byte, val []byte, write bool, delete bool) error {
   512  		defer func(start time.Time) {
   513  			snapStorageWriteCounter.Inc(time.Since(start).Nanoseconds())
   514  		}(time.Now())
   515  
   516  		if delete {
   517  			rawdb.DeleteStorageSnapshot(ctx.batch, account, common.BytesToHash(key))
   518  			snapWipedStorageMeter.Mark(1)
   519  			return nil
   520  		}
   521  		if write {
   522  			rawdb.WriteStorageSnapshot(ctx.batch, account, common.BytesToHash(key), val)
   523  			snapGeneratedStorageMeter.Mark(1)
   524  		} else {
   525  			snapRecoveredStorageMeter.Mark(1)
   526  		}
   527  		ctx.stats.storage += common.StorageSize(1 + 2*common.HashLength + len(val))
   528  		ctx.stats.slots++
   529  
   530  		// If we've exceeded our batch allowance or termination was requested, flush to disk
   531  		if err := dl.checkAndFlush(ctx, append(account[:], key...)); err != nil {
   532  			return err
   533  		}
   534  		return nil
   535  	}
   536  	// Loop for re-generating the missing storage slots.
   537  	var origin = common.CopyBytes(storeMarker)
   538  	for {
   539  		id := trie.StorageTrieID(stateRoot, account, storageRoot)
   540  		exhausted, last, err := dl.generateRange(ctx, id, append(rawdb.SnapshotStoragePrefix, account.Bytes()...), snapStorage, origin, storageCheckRange, onStorage, nil)
   541  		if err != nil {
   542  			return err // The procedure it aborted, either by external signal or internal error.
   543  		}
   544  		// Abort the procedure if the entire contract storage is generated
   545  		if exhausted {
   546  			break
   547  		}
   548  		if origin = increaseKey(last); origin == nil {
   549  			break // special case, the last is 0xffffffff...fff
   550  		}
   551  	}
   552  	return nil
   553  }
   554  
   555  // generateAccounts generates the missing snapshot accounts as well as their
   556  // storage slots in the main trie. It's supposed to restart the generation
   557  // from the given origin position.
   558  func generateAccounts(ctx *generatorContext, dl *diskLayer, accMarker []byte) error {
   559  	onAccount := func(key []byte, val []byte, write bool, delete bool) error {
   560  		// Make sure to clear all dangling storages before this account
   561  		account := common.BytesToHash(key)
   562  		ctx.removeStorageBefore(account)
   563  
   564  		start := time.Now()
   565  		if delete {
   566  			rawdb.DeleteAccountSnapshot(ctx.batch, account)
   567  			snapWipedAccountMeter.Mark(1)
   568  			snapAccountWriteCounter.Inc(time.Since(start).Nanoseconds())
   569  
   570  			ctx.removeStorageAt(account)
   571  			return nil
   572  		}
   573  		// Retrieve the current account and flatten it into the internal format
   574  		var acc types.StateAccount
   575  		if err := rlp.DecodeBytes(val, &acc); err != nil {
   576  			log.Crit("Invalid account encountered during snapshot creation", "err", err)
   577  		}
   578  		// If the account is not yet in-progress, write it out
   579  		if accMarker == nil || !bytes.Equal(account[:], accMarker) {
   580  			dataLen := len(val) // Approximate size, saves us a round of RLP-encoding
   581  			if !write {
   582  				if bytes.Equal(acc.CodeHash, types.EmptyCodeHash[:]) {
   583  					dataLen -= 32
   584  				}
   585  				if acc.Root == types.EmptyRootHash {
   586  					dataLen -= 32
   587  				}
   588  				snapRecoveredAccountMeter.Mark(1)
   589  			} else {
   590  				data := types.SlimAccountRLP(acc)
   591  				dataLen = len(data)
   592  				rawdb.WriteAccountSnapshot(ctx.batch, account, data)
   593  				snapGeneratedAccountMeter.Mark(1)
   594  			}
   595  			ctx.stats.storage += common.StorageSize(1 + common.HashLength + dataLen)
   596  			ctx.stats.accounts++
   597  		}
   598  		// If the snap generation goes here after interrupted, genMarker may go backward
   599  		// when last genMarker is consisted of accountHash and storageHash
   600  		marker := account[:]
   601  		if accMarker != nil && bytes.Equal(marker, accMarker) && len(dl.genMarker) > common.HashLength {
   602  			marker = dl.genMarker[:]
   603  		}
   604  		// If we've exceeded our batch allowance or termination was requested, flush to disk
   605  		if err := dl.checkAndFlush(ctx, marker); err != nil {
   606  			return err
   607  		}
   608  		snapAccountWriteCounter.Inc(time.Since(start).Nanoseconds()) // let's count flush time as well
   609  
   610  		// If the iterated account is the contract, create a further loop to
   611  		// verify or regenerate the contract storage.
   612  		if acc.Root == types.EmptyRootHash {
   613  			ctx.removeStorageAt(account)
   614  		} else {
   615  			var storeMarker []byte
   616  			if accMarker != nil && bytes.Equal(account[:], accMarker) && len(dl.genMarker) > common.HashLength {
   617  				storeMarker = dl.genMarker[common.HashLength:]
   618  			}
   619  			if err := generateStorages(ctx, dl, dl.root, account, acc.Root, storeMarker); err != nil {
   620  				return err
   621  			}
   622  		}
   623  		// Some account processed, unmark the marker
   624  		accMarker = nil
   625  		return nil
   626  	}
   627  	origin := common.CopyBytes(accMarker)
   628  	for {
   629  		id := trie.StateTrieID(dl.root)
   630  		exhausted, last, err := dl.generateRange(ctx, id, rawdb.SnapshotAccountPrefix, snapAccount, origin, accountCheckRange, onAccount, types.FullAccountRLP)
   631  		if err != nil {
   632  			return err // The procedure it aborted, either by external signal or internal error.
   633  		}
   634  		origin = increaseKey(last)
   635  
   636  		// Last step, cleanup the storages after the last account.
   637  		// All the left storages should be treated as dangling.
   638  		if origin == nil || exhausted {
   639  			ctx.removeStorageLeft()
   640  			break
   641  		}
   642  	}
   643  	return nil
   644  }
   645  
   646  // generate is a background thread that iterates over the state and storage tries,
   647  // constructing the state snapshot. All the arguments are purely for statistics
   648  // gathering and logging, since the method surfs the blocks as they arrive, often
   649  // being restarted.
   650  func (dl *diskLayer) generate(stats *generatorStats) {
   651  	var (
   652  		accMarker []byte
   653  		abort     chan *generatorStats
   654  	)
   655  	if len(dl.genMarker) > 0 { // []byte{} is the start, use nil for that
   656  		accMarker = dl.genMarker[:common.HashLength]
   657  	}
   658  	stats.Log("Resuming state snapshot generation", dl.root, dl.genMarker)
   659  
   660  	// Initialize the global generator context. The snapshot iterators are
   661  	// opened at the interrupted position because the assumption is held
   662  	// that all the snapshot data are generated correctly before the marker.
   663  	// Even if the snapshot data is updated during the interruption (before
   664  	// or at the marker), the assumption is still held.
   665  	// For the account or storage slot at the interruption, they will be
   666  	// processed twice by the generator(they are already processed in the
   667  	// last run) but it's fine.
   668  	ctx := newGeneratorContext(stats, dl.diskdb, accMarker, dl.genMarker)
   669  	defer ctx.close()
   670  
   671  	if err := generateAccounts(ctx, dl, accMarker); err != nil {
   672  		// Extract the received interruption signal if exists
   673  		if aerr, ok := err.(*abortErr); ok {
   674  			abort = aerr.abort
   675  		}
   676  		// Aborted by internal error, wait the signal
   677  		if abort == nil {
   678  			abort = <-dl.genAbort
   679  		}
   680  		abort <- stats
   681  		return
   682  	}
   683  	// Snapshot fully generated, set the marker to nil.
   684  	// Note even there is nothing to commit, persist the
   685  	// generator anyway to mark the snapshot is complete.
   686  	journalProgress(ctx.batch, nil, stats)
   687  	if err := ctx.batch.Write(); err != nil {
   688  		log.Error("Failed to flush batch", "err", err)
   689  
   690  		abort = <-dl.genAbort
   691  		abort <- stats
   692  		return
   693  	}
   694  	ctx.batch.Reset()
   695  
   696  	log.Info("Generated state snapshot", "accounts", stats.accounts, "slots", stats.slots,
   697  		"storage", stats.storage, "dangling", stats.dangling, "elapsed", common.PrettyDuration(time.Since(stats.start)))
   698  
   699  	dl.lock.Lock()
   700  	dl.genMarker = nil
   701  	close(dl.genPending)
   702  	dl.lock.Unlock()
   703  
   704  	// Someone will be looking for us, wait it out
   705  	abort = <-dl.genAbort
   706  	abort <- nil
   707  }
   708  
   709  // increaseKey increase the input key by one bit. Return nil if the entire
   710  // addition operation overflows.
   711  func increaseKey(key []byte) []byte {
   712  	for i := len(key) - 1; i >= 0; i-- {
   713  		key[i]++
   714  		if key[i] != 0x0 {
   715  			return key
   716  		}
   717  	}
   718  	return nil
   719  }
   720  
   721  // abortErr wraps an interruption signal received to represent the
   722  // generation is aborted by external processes.
   723  type abortErr struct {
   724  	abort chan *generatorStats
   725  }
   726  
   727  func newAbortErr(abort chan *generatorStats) error {
   728  	return &abortErr{abort: abort}
   729  }
   730  
   731  func (err *abortErr) Error() string {
   732  	return "aborted"
   733  }