github.com/tirogen/go-ethereum@v1.10.12-0.20221226051715-250cfede41b6/core/state/snapshot/journal.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  	"errors"
    23  	"fmt"
    24  	"io"
    25  	"time"
    26  
    27  	"github.com/VictoriaMetrics/fastcache"
    28  	"github.com/tirogen/go-ethereum/common"
    29  	"github.com/tirogen/go-ethereum/core/rawdb"
    30  	"github.com/tirogen/go-ethereum/ethdb"
    31  	"github.com/tirogen/go-ethereum/log"
    32  	"github.com/tirogen/go-ethereum/rlp"
    33  	"github.com/tirogen/go-ethereum/trie"
    34  )
    35  
    36  const journalVersion uint64 = 0
    37  
    38  // journalGenerator is a disk layer entry containing the generator progress marker.
    39  type journalGenerator struct {
    40  	// Indicator that whether the database was in progress of being wiped.
    41  	// It's deprecated but keep it here for background compatibility.
    42  	Wiping bool
    43  
    44  	Done     bool // Whether the generator finished creating the snapshot
    45  	Marker   []byte
    46  	Accounts uint64
    47  	Slots    uint64
    48  	Storage  uint64
    49  }
    50  
    51  // journalDestruct is an account deletion entry in a diffLayer's disk journal.
    52  type journalDestruct struct {
    53  	Hash common.Hash
    54  }
    55  
    56  // journalAccount is an account entry in a diffLayer's disk journal.
    57  type journalAccount struct {
    58  	Hash common.Hash
    59  	Blob []byte
    60  }
    61  
    62  // journalStorage is an account's storage map in a diffLayer's disk journal.
    63  type journalStorage struct {
    64  	Hash common.Hash
    65  	Keys []common.Hash
    66  	Vals [][]byte
    67  }
    68  
    69  func ParseGeneratorStatus(generatorBlob []byte) string {
    70  	if len(generatorBlob) == 0 {
    71  		return ""
    72  	}
    73  	var generator journalGenerator
    74  	if err := rlp.DecodeBytes(generatorBlob, &generator); err != nil {
    75  		log.Warn("failed to decode snapshot generator", "err", err)
    76  		return ""
    77  	}
    78  	// Figure out whether we're after or within an account
    79  	var m string
    80  	switch marker := generator.Marker; len(marker) {
    81  	case common.HashLength:
    82  		m = fmt.Sprintf("at %#x", marker)
    83  	case 2 * common.HashLength:
    84  		m = fmt.Sprintf("in %#x at %#x", marker[:common.HashLength], marker[common.HashLength:])
    85  	default:
    86  		m = fmt.Sprintf("%#x", marker)
    87  	}
    88  	return fmt.Sprintf(`Done: %v, Accounts: %d, Slots: %d, Storage: %d, Marker: %s`,
    89  		generator.Done, generator.Accounts, generator.Slots, generator.Storage, m)
    90  }
    91  
    92  // loadAndParseJournal tries to parse the snapshot journal in latest format.
    93  func loadAndParseJournal(db ethdb.KeyValueStore, base *diskLayer) (snapshot, journalGenerator, error) {
    94  	// Retrieve the disk layer generator. It must exist, no matter the
    95  	// snapshot is fully generated or not. Otherwise the entire disk
    96  	// layer is invalid.
    97  	generatorBlob := rawdb.ReadSnapshotGenerator(db)
    98  	if len(generatorBlob) == 0 {
    99  		return nil, journalGenerator{}, errors.New("missing snapshot generator")
   100  	}
   101  	var generator journalGenerator
   102  	if err := rlp.DecodeBytes(generatorBlob, &generator); err != nil {
   103  		return nil, journalGenerator{}, fmt.Errorf("failed to decode snapshot generator: %v", err)
   104  	}
   105  	// Retrieve the diff layer journal. It's possible that the journal is
   106  	// not existent, e.g. the disk layer is generating while that the Geth
   107  	// crashes without persisting the diff journal.
   108  	// So if there is no journal, or the journal is invalid(e.g. the journal
   109  	// is not matched with disk layer; or the it's the legacy-format journal,
   110  	// etc.), we just discard all diffs and try to recover them later.
   111  	var current snapshot = base
   112  	err := iterateJournal(db, func(parent common.Hash, root common.Hash, destructSet map[common.Hash]struct{}, accountData map[common.Hash][]byte, storageData map[common.Hash]map[common.Hash][]byte) error {
   113  		current = newDiffLayer(current, root, destructSet, accountData, storageData)
   114  		return nil
   115  	})
   116  	if err != nil {
   117  		return base, generator, nil
   118  	}
   119  	return current, generator, nil
   120  }
   121  
   122  // loadSnapshot loads a pre-existing state snapshot backed by a key-value store.
   123  func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, root common.Hash, cache int, recovery bool, noBuild bool) (snapshot, bool, error) {
   124  	// If snapshotting is disabled (initial sync in progress), don't do anything,
   125  	// wait for the chain to permit us to do something meaningful
   126  	if rawdb.ReadSnapshotDisabled(diskdb) {
   127  		return nil, true, nil
   128  	}
   129  	// Retrieve the block number and hash of the snapshot, failing if no snapshot
   130  	// is present in the database (or crashed mid-update).
   131  	baseRoot := rawdb.ReadSnapshotRoot(diskdb)
   132  	if baseRoot == (common.Hash{}) {
   133  		return nil, false, errors.New("missing or corrupted snapshot")
   134  	}
   135  	base := &diskLayer{
   136  		diskdb: diskdb,
   137  		triedb: triedb,
   138  		cache:  fastcache.New(cache * 1024 * 1024),
   139  		root:   baseRoot,
   140  	}
   141  	snapshot, generator, err := loadAndParseJournal(diskdb, base)
   142  	if err != nil {
   143  		log.Warn("Failed to load journal", "error", err)
   144  		return nil, false, err
   145  	}
   146  	// Entire snapshot journal loaded, sanity check the head. If the loaded
   147  	// snapshot is not matched with current state root, print a warning log
   148  	// or discard the entire snapshot it's legacy snapshot.
   149  	//
   150  	// Possible scenario: Geth was crashed without persisting journal and then
   151  	// restart, the head is rewound to the point with available state(trie)
   152  	// which is below the snapshot. In this case the snapshot can be recovered
   153  	// by re-executing blocks but right now it's unavailable.
   154  	if head := snapshot.Root(); head != root {
   155  		// If it's legacy snapshot, or it's new-format snapshot but
   156  		// it's not in recovery mode, returns the error here for
   157  		// rebuilding the entire snapshot forcibly.
   158  		if !recovery {
   159  			return nil, false, fmt.Errorf("head doesn't match snapshot: have %#x, want %#x", head, root)
   160  		}
   161  		// It's in snapshot recovery, the assumption is held that
   162  		// the disk layer is always higher than chain head. It can
   163  		// be eventually recovered when the chain head beyonds the
   164  		// disk layer.
   165  		log.Warn("Snapshot is not continuous with chain", "snaproot", head, "chainroot", root)
   166  	}
   167  	// Load the disk layer status from the generator if it's not complete
   168  	if !generator.Done {
   169  		base.genMarker = generator.Marker
   170  		if base.genMarker == nil {
   171  			base.genMarker = []byte{}
   172  		}
   173  	}
   174  	// Everything loaded correctly, resume any suspended operations
   175  	// if the background generation is allowed
   176  	if !generator.Done && !noBuild {
   177  		base.genPending = make(chan struct{})
   178  		base.genAbort = make(chan chan *generatorStats)
   179  
   180  		var origin uint64
   181  		if len(generator.Marker) >= 8 {
   182  			origin = binary.BigEndian.Uint64(generator.Marker)
   183  		}
   184  		go base.generate(&generatorStats{
   185  			origin:   origin,
   186  			start:    time.Now(),
   187  			accounts: generator.Accounts,
   188  			slots:    generator.Slots,
   189  			storage:  common.StorageSize(generator.Storage),
   190  		})
   191  	}
   192  	return snapshot, false, nil
   193  }
   194  
   195  // Journal terminates any in-progress snapshot generation, also implicitly pushing
   196  // the progress into the database.
   197  func (dl *diskLayer) Journal(buffer *bytes.Buffer) (common.Hash, error) {
   198  	// If the snapshot is currently being generated, abort it
   199  	var stats *generatorStats
   200  	if dl.genAbort != nil {
   201  		abort := make(chan *generatorStats)
   202  		dl.genAbort <- abort
   203  
   204  		if stats = <-abort; stats != nil {
   205  			stats.Log("Journalling in-progress snapshot", dl.root, dl.genMarker)
   206  		}
   207  	}
   208  	// Ensure the layer didn't get stale
   209  	dl.lock.RLock()
   210  	defer dl.lock.RUnlock()
   211  
   212  	if dl.stale {
   213  		return common.Hash{}, ErrSnapshotStale
   214  	}
   215  	// Ensure the generator stats is written even if none was ran this cycle
   216  	journalProgress(dl.diskdb, dl.genMarker, stats)
   217  
   218  	log.Debug("Journalled disk layer", "root", dl.root)
   219  	return dl.root, nil
   220  }
   221  
   222  // Journal writes the memory layer contents into a buffer to be stored in the
   223  // database as the snapshot journal.
   224  func (dl *diffLayer) Journal(buffer *bytes.Buffer) (common.Hash, error) {
   225  	// Journal the parent first
   226  	base, err := dl.parent.Journal(buffer)
   227  	if err != nil {
   228  		return common.Hash{}, err
   229  	}
   230  	// Ensure the layer didn't get stale
   231  	dl.lock.RLock()
   232  	defer dl.lock.RUnlock()
   233  
   234  	if dl.Stale() {
   235  		return common.Hash{}, ErrSnapshotStale
   236  	}
   237  	// Everything below was journalled, persist this layer too
   238  	if err := rlp.Encode(buffer, dl.root); err != nil {
   239  		return common.Hash{}, err
   240  	}
   241  	destructs := make([]journalDestruct, 0, len(dl.destructSet))
   242  	for hash := range dl.destructSet {
   243  		destructs = append(destructs, journalDestruct{Hash: hash})
   244  	}
   245  	if err := rlp.Encode(buffer, destructs); err != nil {
   246  		return common.Hash{}, err
   247  	}
   248  	accounts := make([]journalAccount, 0, len(dl.accountData))
   249  	for hash, blob := range dl.accountData {
   250  		accounts = append(accounts, journalAccount{Hash: hash, Blob: blob})
   251  	}
   252  	if err := rlp.Encode(buffer, accounts); err != nil {
   253  		return common.Hash{}, err
   254  	}
   255  	storage := make([]journalStorage, 0, len(dl.storageData))
   256  	for hash, slots := range dl.storageData {
   257  		keys := make([]common.Hash, 0, len(slots))
   258  		vals := make([][]byte, 0, len(slots))
   259  		for key, val := range slots {
   260  			keys = append(keys, key)
   261  			vals = append(vals, val)
   262  		}
   263  		storage = append(storage, journalStorage{Hash: hash, Keys: keys, Vals: vals})
   264  	}
   265  	if err := rlp.Encode(buffer, storage); err != nil {
   266  		return common.Hash{}, err
   267  	}
   268  	log.Debug("Journalled diff layer", "root", dl.root, "parent", dl.parent.Root())
   269  	return base, nil
   270  }
   271  
   272  // journalCallback is a function which is invoked by iterateJournal, every
   273  // time a difflayer is loaded from disk.
   274  type journalCallback = func(parent common.Hash, root common.Hash, destructs map[common.Hash]struct{}, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) error
   275  
   276  // iterateJournal iterates through the journalled difflayers, loading them from
   277  // the database, and invoking the callback for each loaded layer.
   278  // The order is incremental; starting with the bottom-most difflayer, going towards
   279  // the most recent layer.
   280  // This method returns error either if there was some error reading from disk,
   281  // OR if the callback returns an error when invoked.
   282  func iterateJournal(db ethdb.KeyValueReader, callback journalCallback) error {
   283  	journal := rawdb.ReadSnapshotJournal(db)
   284  	if len(journal) == 0 {
   285  		log.Warn("Loaded snapshot journal", "diffs", "missing")
   286  		return nil
   287  	}
   288  	r := rlp.NewStream(bytes.NewReader(journal), 0)
   289  	// Firstly, resolve the first element as the journal version
   290  	version, err := r.Uint64()
   291  	if err != nil {
   292  		log.Warn("Failed to resolve the journal version", "error", err)
   293  		return errors.New("failed to resolve journal version")
   294  	}
   295  	if version != journalVersion {
   296  		log.Warn("Discarded the snapshot journal with wrong version", "required", journalVersion, "got", version)
   297  		return errors.New("wrong journal version")
   298  	}
   299  	// Secondly, resolve the disk layer root, ensure it's continuous
   300  	// with disk layer. Note now we can ensure it's the snapshot journal
   301  	// correct version, so we expect everything can be resolved properly.
   302  	var parent common.Hash
   303  	if err := r.Decode(&parent); err != nil {
   304  		return errors.New("missing disk layer root")
   305  	}
   306  	if baseRoot := rawdb.ReadSnapshotRoot(db); baseRoot != parent {
   307  		log.Warn("Loaded snapshot journal", "diskroot", baseRoot, "diffs", "unmatched")
   308  		return fmt.Errorf("mismatched disk and diff layers")
   309  	}
   310  	for {
   311  		var (
   312  			root        common.Hash
   313  			destructs   []journalDestruct
   314  			accounts    []journalAccount
   315  			storage     []journalStorage
   316  			destructSet = make(map[common.Hash]struct{})
   317  			accountData = make(map[common.Hash][]byte)
   318  			storageData = make(map[common.Hash]map[common.Hash][]byte)
   319  		)
   320  		// Read the next diff journal entry
   321  		if err := r.Decode(&root); err != nil {
   322  			// The first read may fail with EOF, marking the end of the journal
   323  			if errors.Is(err, io.EOF) {
   324  				return nil
   325  			}
   326  			return fmt.Errorf("load diff root: %v", err)
   327  		}
   328  		if err := r.Decode(&destructs); err != nil {
   329  			return fmt.Errorf("load diff destructs: %v", err)
   330  		}
   331  		if err := r.Decode(&accounts); err != nil {
   332  			return fmt.Errorf("load diff accounts: %v", err)
   333  		}
   334  		if err := r.Decode(&storage); err != nil {
   335  			return fmt.Errorf("load diff storage: %v", err)
   336  		}
   337  		for _, entry := range destructs {
   338  			destructSet[entry.Hash] = struct{}{}
   339  		}
   340  		for _, entry := range accounts {
   341  			if len(entry.Blob) > 0 { // RLP loses nil-ness, but `[]byte{}` is not a valid item, so reinterpret that
   342  				accountData[entry.Hash] = entry.Blob
   343  			} else {
   344  				accountData[entry.Hash] = nil
   345  			}
   346  		}
   347  		for _, entry := range storage {
   348  			slots := make(map[common.Hash][]byte)
   349  			for i, key := range entry.Keys {
   350  				if len(entry.Vals[i]) > 0 { // RLP loses nil-ness, but `[]byte{}` is not a valid item, so reinterpret that
   351  					slots[key] = entry.Vals[i]
   352  				} else {
   353  					slots[key] = nil
   354  				}
   355  			}
   356  			storageData[entry.Hash] = slots
   357  		}
   358  		if err := callback(parent, root, destructSet, accountData, storageData); err != nil {
   359  			return err
   360  		}
   361  		parent = root
   362  	}
   363  }