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