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