github.com/ccm-chain/ccmchain@v1.0.0/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  	"encoding/binary"
    22  	"math/big"
    23  	"time"
    24  
    25  	"github.com/VictoriaMetrics/fastcache"
    26  	"github.com/ccm-chain/ccmchain/common"
    27  	"github.com/ccm-chain/ccmchain/common/math"
    28  	"github.com/ccm-chain/ccmchain/core/rawdb"
    29  	"github.com/ccm-chain/ccmchain/crypto"
    30  	"github.com/ccm-chain/ccmchain/database"
    31  	"github.com/ccm-chain/ccmchain/log"
    32  	"github.com/ccm-chain/ccmchain/rlp"
    33  	"github.com/ccm-chain/ccmchain/trie"
    34  )
    35  
    36  var (
    37  	// emptyRoot is the known root hash of an empty trie.
    38  	emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
    39  
    40  	// emptyCode is the known hash of the empty EVM bytecode.
    41  	emptyCode = crypto.Keccak256Hash(nil)
    42  )
    43  
    44  // generatorStats is a collection of statistics gathered by the snapshot generator
    45  // for logging purposes.
    46  type generatorStats struct {
    47  	wiping   chan struct{}      // Notification channel if wiping is in progress
    48  	origin   uint64             // Origin prefix where generation started
    49  	start    time.Time          // Timestamp when generation started
    50  	accounts uint64             // Number of accounts indexed
    51  	slots    uint64             // Number of storage slots indexed
    52  	storage  common.StorageSize // Account and storage slot size
    53  }
    54  
    55  // Log creates an contextual log with the given message and the context pulled
    56  // from the internally maintained statistics.
    57  func (gs *generatorStats) Log(msg string, root common.Hash, marker []byte) {
    58  	var ctx []interface{}
    59  	if root != (common.Hash{}) {
    60  		ctx = append(ctx, []interface{}{"root", root}...)
    61  	}
    62  	// Figure out whether we're after or within an account
    63  	switch len(marker) {
    64  	case common.HashLength:
    65  		ctx = append(ctx, []interface{}{"at", common.BytesToHash(marker)}...)
    66  	case 2 * common.HashLength:
    67  		ctx = append(ctx, []interface{}{
    68  			"in", common.BytesToHash(marker[:common.HashLength]),
    69  			"at", common.BytesToHash(marker[common.HashLength:]),
    70  		}...)
    71  	}
    72  	// Add the usual measurements
    73  	ctx = append(ctx, []interface{}{
    74  		"accounts", gs.accounts,
    75  		"slots", gs.slots,
    76  		"storage", gs.storage,
    77  		"elapsed", common.PrettyDuration(time.Since(gs.start)),
    78  	}...)
    79  	// Calculate the estimated indexing time based on current stats
    80  	if len(marker) > 0 {
    81  		if done := binary.BigEndian.Uint64(marker[:8]) - gs.origin; done > 0 {
    82  			left := math.MaxUint64 - binary.BigEndian.Uint64(marker[:8])
    83  
    84  			speed := done/uint64(time.Since(gs.start)/time.Millisecond+1) + 1 // +1s to avoid division by zero
    85  			ctx = append(ctx, []interface{}{
    86  				"eta", common.PrettyDuration(time.Duration(left/speed) * time.Millisecond),
    87  			}...)
    88  		}
    89  	}
    90  	log.Info(msg, ctx...)
    91  }
    92  
    93  // generateSnapshot regenerates a brand new snapshot based on an existing state
    94  // database and head block asynchronously. The snapshot is returned immediately
    95  // and generation is continued in the background until done.
    96  func generateSnapshot(diskdb database.KeyValueStore, triedb *trie.Database, cache int, root common.Hash, wiper chan struct{}) *diskLayer {
    97  	// Wipe any previously existing snapshot from the database if no wiper is
    98  	// currently in progress.
    99  	if wiper == nil {
   100  		wiper = wipeSnapshot(diskdb, true)
   101  	}
   102  	// Create a new disk layer with an initialized state marker at zero
   103  	rawdb.WriteSnapshotRoot(diskdb, root)
   104  
   105  	base := &diskLayer{
   106  		diskdb:     diskdb,
   107  		triedb:     triedb,
   108  		root:       root,
   109  		cache:      fastcache.New(cache * 1024 * 1024),
   110  		genMarker:  []byte{}, // Initialized but empty!
   111  		genPending: make(chan struct{}),
   112  		genAbort:   make(chan chan *generatorStats),
   113  	}
   114  	go base.generate(&generatorStats{wiping: wiper, start: time.Now()})
   115  	return base
   116  }
   117  
   118  // generate is a background thread that iterates over the state and storage tries,
   119  // constructing the state snapshot. All the arguments are purely for statistics
   120  // gethering and logging, since the method surfs the blocks as they arrive, often
   121  // being restarted.
   122  func (dl *diskLayer) generate(stats *generatorStats) {
   123  	// If a database wipe is in operation, wait until it's done
   124  	if stats.wiping != nil {
   125  		stats.Log("Wiper running, state snapshotting paused", common.Hash{}, dl.genMarker)
   126  		select {
   127  		// If wiper is done, resume normal mode of operation
   128  		case <-stats.wiping:
   129  			stats.wiping = nil
   130  			stats.start = time.Now()
   131  
   132  		// If generator was aboted during wipe, return
   133  		case abort := <-dl.genAbort:
   134  			abort <- stats
   135  			return
   136  		}
   137  	}
   138  	// Create an account and state iterator pointing to the current generator marker
   139  	accTrie, err := trie.NewSecure(dl.root, dl.triedb)
   140  	if err != nil {
   141  		// The account trie is missing (GC), surf the chain until one becomes available
   142  		stats.Log("Trie missing, state snapshotting paused", dl.root, dl.genMarker)
   143  
   144  		abort := <-dl.genAbort
   145  		abort <- stats
   146  		return
   147  	}
   148  	stats.Log("Resuming state snapshot generation", dl.root, dl.genMarker)
   149  
   150  	var accMarker []byte
   151  	if len(dl.genMarker) > 0 { // []byte{} is the start, use nil for that
   152  		accMarker = dl.genMarker[:common.HashLength]
   153  	}
   154  	accIt := trie.NewIterator(accTrie.NodeIterator(accMarker))
   155  	batch := dl.diskdb.NewBatch()
   156  
   157  	// Iterate from the previous marker and continue generating the state snapshot
   158  	logged := time.Now()
   159  	for accIt.Next() {
   160  		// Retrieve the current account and flatten it into the internal format
   161  		accountHash := common.BytesToHash(accIt.Key)
   162  
   163  		var acc struct {
   164  			Nonce    uint64
   165  			Balance  *big.Int
   166  			Root     common.Hash
   167  			CodeHash []byte
   168  		}
   169  		if err := rlp.DecodeBytes(accIt.Value, &acc); err != nil {
   170  			log.Crit("Invalid account encountered during snapshot creation", "err", err)
   171  		}
   172  		data := SlimAccountRLP(acc.Nonce, acc.Balance, acc.Root, acc.CodeHash)
   173  
   174  		// If the account is not yet in-progress, write it out
   175  		if accMarker == nil || !bytes.Equal(accountHash[:], accMarker) {
   176  			rawdb.WriteAccountSnapshot(batch, accountHash, data)
   177  			stats.storage += common.StorageSize(1 + common.HashLength + len(data))
   178  			stats.accounts++
   179  		}
   180  		// If we've exceeded our batch allowance or termination was requested, flush to disk
   181  		var abort chan *generatorStats
   182  		select {
   183  		case abort = <-dl.genAbort:
   184  		default:
   185  		}
   186  		if batch.ValueSize() > database.IdealBatchSize || abort != nil {
   187  			// Only write and set the marker if we actually did something useful
   188  			if batch.ValueSize() > 0 {
   189  				batch.Write()
   190  				batch.Reset()
   191  
   192  				dl.lock.Lock()
   193  				dl.genMarker = accountHash[:]
   194  				dl.lock.Unlock()
   195  			}
   196  			if abort != nil {
   197  				stats.Log("Aborting state snapshot generation", dl.root, accountHash[:])
   198  				abort <- stats
   199  				return
   200  			}
   201  		}
   202  		// If the account is in-progress, continue where we left off (otherwise iterate all)
   203  		if acc.Root != emptyRoot {
   204  			storeTrie, err := trie.NewSecure(acc.Root, dl.triedb)
   205  			if err != nil {
   206  				log.Crit("Storage trie inaccessible for snapshot generation", "err", err)
   207  			}
   208  			var storeMarker []byte
   209  			if accMarker != nil && bytes.Equal(accountHash[:], accMarker) && len(dl.genMarker) > common.HashLength {
   210  				storeMarker = dl.genMarker[common.HashLength:]
   211  			}
   212  			storeIt := trie.NewIterator(storeTrie.NodeIterator(storeMarker))
   213  			for storeIt.Next() {
   214  				rawdb.WriteStorageSnapshot(batch, accountHash, common.BytesToHash(storeIt.Key), storeIt.Value)
   215  				stats.storage += common.StorageSize(1 + 2*common.HashLength + len(storeIt.Value))
   216  				stats.slots++
   217  
   218  				// If we've exceeded our batch allowance or termination was requested, flush to disk
   219  				var abort chan *generatorStats
   220  				select {
   221  				case abort = <-dl.genAbort:
   222  				default:
   223  				}
   224  				if batch.ValueSize() > database.IdealBatchSize || abort != nil {
   225  					// Only write and set the marker if we actually did something useful
   226  					if batch.ValueSize() > 0 {
   227  						batch.Write()
   228  						batch.Reset()
   229  
   230  						dl.lock.Lock()
   231  						dl.genMarker = append(accountHash[:], storeIt.Key...)
   232  						dl.lock.Unlock()
   233  					}
   234  					if abort != nil {
   235  						stats.Log("Aborting state snapshot generation", dl.root, append(accountHash[:], storeIt.Key...))
   236  						abort <- stats
   237  						return
   238  					}
   239  				}
   240  			}
   241  		}
   242  		if time.Since(logged) > 8*time.Second {
   243  			stats.Log("Generating state snapshot", dl.root, accIt.Key)
   244  			logged = time.Now()
   245  		}
   246  		// Some account processed, unmark the marker
   247  		accMarker = nil
   248  	}
   249  	// Snapshot fully generated, set the marker to nil
   250  	if batch.ValueSize() > 0 {
   251  		batch.Write()
   252  	}
   253  	log.Info("Generated state snapshot", "accounts", stats.accounts, "slots", stats.slots,
   254  		"storage", stats.storage, "elapsed", common.PrettyDuration(time.Since(stats.start)))
   255  
   256  	dl.lock.Lock()
   257  	dl.genMarker = nil
   258  	close(dl.genPending)
   259  	dl.lock.Unlock()
   260  
   261  	// Someone will be looking for us, wait it out
   262  	abort := <-dl.genAbort
   263  	abort <- nil
   264  }