github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/eth/state_accessor.go (about)

     1  // Copyright 2021 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 eth
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"time"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/core"
    26  	"github.com/ethereum/go-ethereum/core/state"
    27  	"github.com/ethereum/go-ethereum/core/types"
    28  	"github.com/ethereum/go-ethereum/core/vm"
    29  	"github.com/ethereum/go-ethereum/eth/tracers"
    30  	"github.com/ethereum/go-ethereum/log"
    31  	"github.com/ethereum/go-ethereum/trie"
    32  )
    33  
    34  // noopReleaser is returned in case there is no operation expected
    35  // for releasing state.
    36  var noopReleaser = tracers.StateReleaseFunc(func() {})
    37  
    38  // StateAtBlock retrieves the state database associated with a certain block.
    39  // If no state is locally available for the given block, a number of blocks
    40  // are attempted to be reexecuted to generate the desired state. The optional
    41  // base layer statedb can be provided which is regarded as the statedb of the
    42  // parent block.
    43  //
    44  // An additional release function will be returned if the requested state is
    45  // available. Release is expected to be invoked when the returned state is no longer needed.
    46  // Its purpose is to prevent resource leaking. Though it can be noop in some cases.
    47  //
    48  // Parameters:
    49  //   - block:      The block for which we want the state(state = block.Root)
    50  //   - reexec:     The maximum number of blocks to reprocess trying to obtain the desired state
    51  //   - base:       If the caller is tracing multiple blocks, the caller can provide the parent
    52  //     state continuously from the callsite.
    53  //   - readOnly:   If true, then the live 'blockchain' state database is used. No mutation should
    54  //     be made from caller, e.g. perform Commit or other 'save-to-disk' changes.
    55  //     Otherwise, the trash generated by caller may be persisted permanently.
    56  //   - preferDisk: this arg can be used by the caller to signal that even though the 'base' is
    57  //     provided, it would be preferable to start from a fresh state, if we have it
    58  //     on disk.
    59  func (eth *Ethereum) StateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, readOnly bool, preferDisk bool) (statedb *state.StateDB, release tracers.StateReleaseFunc, err error) {
    60  	var (
    61  		current  *types.Block
    62  		database state.Database
    63  		report   = true
    64  		origin   = block.NumberU64()
    65  	)
    66  	// The state is only for reading purposes, check the state presence in
    67  	// live database.
    68  	if readOnly {
    69  		// The state is available in live database, create a reference
    70  		// on top to prevent garbage collection and return a release
    71  		// function to deref it.
    72  		if statedb, err = eth.blockchain.StateAt(block.Root()); err == nil {
    73  			statedb.Database().TrieDB().Reference(block.Root(), common.Hash{})
    74  			return statedb, func() {
    75  				statedb.Database().TrieDB().Dereference(block.Root())
    76  			}, nil
    77  		}
    78  	}
    79  	// The state is both for reading and writing, or it's unavailable in disk,
    80  	// try to construct/recover the state over an ephemeral trie.Database for
    81  	// isolating the live one.
    82  	if base != nil {
    83  		if preferDisk {
    84  			// Create an ephemeral trie.Database for isolating the live one. Otherwise
    85  			// the internal junks created by tracing will be persisted into the disk.
    86  			database = state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16})
    87  			if statedb, err = state.New(block.Root(), database, nil); err == nil {
    88  				log.Info("Found disk backend for state trie", "root", block.Root(), "number", block.Number())
    89  				return statedb, noopReleaser, nil
    90  			}
    91  		}
    92  		// The optional base statedb is given, mark the start point as parent block
    93  		statedb, database, report = base, base.Database(), false
    94  		current = eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
    95  	} else {
    96  		// Otherwise, try to reexec blocks until we find a state or reach our limit
    97  		current = block
    98  
    99  		// Create an ephemeral trie.Database for isolating the live one. Otherwise
   100  		// the internal junks created by tracing will be persisted into the disk.
   101  		database = state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16})
   102  
   103  		// If we didn't check the live database, do check state over ephemeral database,
   104  		// otherwise we would rewind past a persisted block (specific corner case is
   105  		// chain tracing from the genesis).
   106  		if !readOnly {
   107  			statedb, err = state.New(current.Root(), database, nil)
   108  			if err == nil {
   109  				return statedb, noopReleaser, nil
   110  			}
   111  		}
   112  		// Database does not have the state for the given block, try to regenerate
   113  		for i := uint64(0); i < reexec; i++ {
   114  			if current.NumberU64() == 0 {
   115  				return nil, nil, errors.New("genesis state is missing")
   116  			}
   117  			parent := eth.blockchain.GetBlock(current.ParentHash(), current.NumberU64()-1)
   118  			if parent == nil {
   119  				return nil, nil, fmt.Errorf("missing block %v %d", current.ParentHash(), current.NumberU64()-1)
   120  			}
   121  			current = parent
   122  
   123  			statedb, err = state.New(current.Root(), database, nil)
   124  			if err == nil {
   125  				break
   126  			}
   127  		}
   128  		if err != nil {
   129  			switch err.(type) {
   130  			case *trie.MissingNodeError:
   131  				return nil, nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec)
   132  			default:
   133  				return nil, nil, err
   134  			}
   135  		}
   136  	}
   137  	// State is available at historical point, re-execute the blocks on top for
   138  	// the desired state.
   139  	var (
   140  		start  = time.Now()
   141  		logged time.Time
   142  		parent common.Hash
   143  	)
   144  	for current.NumberU64() < origin {
   145  		// Print progress logs if long enough time elapsed
   146  		if time.Since(logged) > 8*time.Second && report {
   147  			log.Info("Regenerating historical state", "block", current.NumberU64()+1, "target", origin, "remaining", origin-current.NumberU64()-1, "elapsed", time.Since(start))
   148  			logged = time.Now()
   149  		}
   150  		// Retrieve the next block to regenerate and process it
   151  		next := current.NumberU64() + 1
   152  		if current = eth.blockchain.GetBlockByNumber(next); current == nil {
   153  			return nil, nil, fmt.Errorf("block #%d not found", next)
   154  		}
   155  		_, _, _, err := eth.blockchain.Processor().Process(current, statedb, vm.Config{})
   156  		if err != nil {
   157  			return nil, nil, fmt.Errorf("processing block %d failed: %v", current.NumberU64(), err)
   158  		}
   159  		// Finalize the state so any modifications are written to the trie
   160  		root, err := statedb.Commit(eth.blockchain.Config().IsEIP158(current.Number()))
   161  		if err != nil {
   162  			return nil, nil, fmt.Errorf("stateAtBlock commit failed, number %d root %v: %w",
   163  				current.NumberU64(), current.Root().Hex(), err)
   164  		}
   165  		statedb, err = state.New(root, database, nil)
   166  		if err != nil {
   167  			return nil, nil, fmt.Errorf("state reset after block %d failed: %v", current.NumberU64(), err)
   168  		}
   169  		// Hold the state reference and also drop the parent state
   170  		// to prevent accumulating too many nodes in memory.
   171  		database.TrieDB().Reference(root, common.Hash{})
   172  		if parent != (common.Hash{}) {
   173  			database.TrieDB().Dereference(parent)
   174  		}
   175  		parent = root
   176  	}
   177  	if report {
   178  		nodes, imgs := database.TrieDB().Size()
   179  		log.Info("Historical state regenerated", "block", current.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
   180  	}
   181  	return statedb, func() { database.TrieDB().Dereference(block.Root()) }, nil
   182  }
   183  
   184  // stateAtTransaction returns the execution environment of a certain transaction.
   185  func (eth *Ethereum) stateAtTransaction(block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, tracers.StateReleaseFunc, error) {
   186  	// Short circuit if it's genesis block.
   187  	if block.NumberU64() == 0 {
   188  		return nil, vm.BlockContext{}, nil, nil, errors.New("no transaction in genesis")
   189  	}
   190  	// Create the parent state database
   191  	parent := eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
   192  	if parent == nil {
   193  		return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("parent %#x not found", block.ParentHash())
   194  	}
   195  	// Lookup the statedb of parent block from the live database,
   196  	// otherwise regenerate it on the flight.
   197  	statedb, release, err := eth.StateAtBlock(parent, reexec, nil, true, false)
   198  	if err != nil {
   199  		return nil, vm.BlockContext{}, nil, nil, err
   200  	}
   201  	if txIndex == 0 && len(block.Transactions()) == 0 {
   202  		return nil, vm.BlockContext{}, statedb, release, nil
   203  	}
   204  	// Recompute transactions up to the target index.
   205  	signer := types.MakeSigner(eth.blockchain.Config(), block.Number())
   206  	for idx, tx := range block.Transactions() {
   207  		// Assemble the transaction call message and return if the requested offset
   208  		msg, _ := tx.AsMessage(signer, block.BaseFee())
   209  		txContext := core.NewEVMTxContext(msg)
   210  		context := core.NewEVMBlockContext(block.Header(), eth.blockchain, nil)
   211  		if idx == txIndex {
   212  			return msg, context, statedb, release, nil
   213  		}
   214  		// Not yet the searched for transaction, execute on top of the current state
   215  		vmenv := vm.NewEVM(context, txContext, statedb, eth.blockchain.Config(), vm.Config{})
   216  		statedb.Prepare(tx.Hash(), idx)
   217  		if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
   218  			return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
   219  		}
   220  		// Ensure any modifications are committed to the state
   221  		// Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
   222  		statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
   223  	}
   224  	return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
   225  }