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