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