github.com/MetalBlockchain/subnet-evm@v0.4.9/eth/state_accessor.go (about)

     1  // (c) 2021, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2021 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package eth
    28  
    29  import (
    30  	"errors"
    31  	"fmt"
    32  	"math/big"
    33  	"time"
    34  
    35  	"github.com/MetalBlockchain/subnet-evm/core"
    36  	"github.com/MetalBlockchain/subnet-evm/core/state"
    37  	"github.com/MetalBlockchain/subnet-evm/core/types"
    38  	"github.com/MetalBlockchain/subnet-evm/core/vm"
    39  	"github.com/MetalBlockchain/subnet-evm/trie"
    40  	"github.com/ethereum/go-ethereum/common"
    41  	"github.com/ethereum/go-ethereum/log"
    42  )
    43  
    44  // StateAtBlock retrieves the state database associated with a certain block.
    45  // If no state is locally available for the given block, a number of blocks
    46  // are attempted to be reexecuted to generate the desired state. The optional
    47  // base layer statedb can be passed then it's regarded as the statedb of the
    48  // parent block.
    49  // Parameters:
    50  //   - block: The block for which we want the state (== state at the stateRoot of the parent)
    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 state
    53  //     continuously from the callsite.
    54  //   - checklive: if true, then the live 'blockchain' state database is used. If the caller want to
    55  //     perform Commit or other 'save-to-disk' changes, this should be set to false to avoid
    56  //     storing trash persistently
    57  //   - preferDisk: this arg can be used by the caller to signal that even though the 'base' is provided,
    58  //     it would be preferable to start from a fresh state, if we have it on disk.
    59  func (eth *Ethereum) StateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (statedb *state.StateDB, err error) {
    60  	var (
    61  		current  *types.Block
    62  		database state.Database
    63  		report   = true
    64  		origin   = block.NumberU64()
    65  	)
    66  	// Check the live database first if we have the state fully available, use that.
    67  	if checkLive {
    68  		statedb, err = eth.blockchain.StateAt(block.Root())
    69  		if err == nil {
    70  			return statedb, nil
    71  		}
    72  	}
    73  	if base != nil {
    74  		if preferDisk {
    75  			// Create an ephemeral trie.Database for isolating the live one. Otherwise
    76  			// the internal junks created by tracing will be persisted into the disk.
    77  			database = state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16})
    78  			if statedb, err = state.New(block.Root(), database, nil); err == nil {
    79  				log.Info("Found disk backend for state trie", "root", block.Root(), "number", block.Number())
    80  				return statedb, nil
    81  			}
    82  		}
    83  		// The optional base statedb is given, mark the start point as parent block
    84  		statedb, database, report = base, base.Database(), false
    85  		current = eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
    86  	} else {
    87  		// Otherwise try to reexec blocks until we find a state or reach our limit
    88  		current = block
    89  
    90  		// Create an ephemeral trie.Database for isolating the live one. Otherwise
    91  		// the internal junks created by tracing will be persisted into the disk.
    92  		database = state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16})
    93  
    94  		// If we didn't check the dirty database, do check the clean one, otherwise
    95  		// we would rewind past a persisted block (specific corner case is chain
    96  		// tracing from the genesis).
    97  		if !checkLive {
    98  			statedb, err = state.New(current.Root(), database, nil)
    99  			if err == nil {
   100  				return statedb, nil
   101  			}
   102  		}
   103  		// Database does not have the state for the given block, try to regenerate
   104  		for i := uint64(0); i < reexec; i++ {
   105  			if current.NumberU64() == 0 {
   106  				return 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, 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, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec)
   123  			default:
   124  				return nil, err
   125  			}
   126  		}
   127  	}
   128  	// State was available at historical point, regenerate
   129  	var (
   130  		start  = time.Now()
   131  		logged time.Time
   132  		parent common.Hash
   133  	)
   134  	for current.NumberU64() < origin {
   135  		// Print progress logs if long enough time elapsed
   136  		if time.Since(logged) > 8*time.Second && report {
   137  			log.Info("Regenerating historical state", "block", current.NumberU64()+1, "target", origin, "remaining", origin-current.NumberU64()-1, "elapsed", time.Since(start))
   138  			logged = time.Now()
   139  		}
   140  		// Retrieve the next block to regenerate and process it
   141  		parentHeader := current.Header()
   142  		next := current.NumberU64() + 1
   143  		if current = eth.blockchain.GetBlockByNumber(next); current == nil {
   144  			return nil, fmt.Errorf("block #%d not found", next)
   145  		}
   146  		_, _, _, err := eth.blockchain.Processor().Process(current, parentHeader, statedb, vm.Config{})
   147  		if err != nil {
   148  			return nil, fmt.Errorf("processing block %d failed: %v", current.NumberU64(), err)
   149  		}
   150  		// Finalize the state so any modifications are written to the trie
   151  		root, err := statedb.Commit(eth.blockchain.Config().IsEIP158(current.Number()), true)
   152  		if err != nil {
   153  			return nil, fmt.Errorf("stateAtBlock commit failed, number %d root %v: %w",
   154  				current.NumberU64(), current.Root().Hex(), err)
   155  		}
   156  		statedb, err = state.New(root, database, nil)
   157  		if err != nil {
   158  			return nil, fmt.Errorf("state reset after block %d failed: %v", current.NumberU64(), err)
   159  		}
   160  		if parent != (common.Hash{}) {
   161  			database.TrieDB().Dereference(parent)
   162  		}
   163  		parent = root
   164  	}
   165  	if report {
   166  		nodes, imgs := database.TrieDB().Size()
   167  		log.Info("Historical state regenerated", "block", current.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
   168  	}
   169  	return statedb, nil
   170  }
   171  
   172  // stateAtTransaction returns the execution environment of a certain transaction.
   173  func (eth *Ethereum) stateAtTransaction(block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) {
   174  	// Short circuit if it's genesis block.
   175  	if block.NumberU64() == 0 {
   176  		return nil, vm.BlockContext{}, nil, errors.New("no transaction in genesis")
   177  	}
   178  	// Create the parent state database
   179  	parent := eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
   180  	if parent == nil {
   181  		return nil, vm.BlockContext{}, nil, fmt.Errorf("parent %#x not found", block.ParentHash())
   182  	}
   183  	// Lookup the statedb of parent block from the live database,
   184  	// otherwise regenerate it on the flight.
   185  	statedb, err := eth.StateAtBlock(parent, reexec, nil, true, false)
   186  	if err != nil {
   187  		return nil, vm.BlockContext{}, nil, err
   188  	}
   189  	if txIndex == 0 && len(block.Transactions()) == 0 {
   190  		return nil, vm.BlockContext{}, statedb, nil
   191  	}
   192  	// Recompute transactions up to the target index.
   193  	signer := types.MakeSigner(eth.blockchain.Config(), block.Number(), new(big.Int).SetUint64(block.Time()))
   194  	for idx, tx := range block.Transactions() {
   195  		// Assemble the transaction call message and return if the requested offset
   196  		msg, _ := tx.AsMessage(signer, block.BaseFee())
   197  		txContext := core.NewEVMTxContext(msg)
   198  		context := core.NewEVMBlockContext(block.Header(), eth.blockchain, nil)
   199  		if idx == txIndex {
   200  			return msg, context, statedb, nil
   201  		}
   202  		// Not yet the searched for transaction, execute on top of the current state
   203  		vmenv := vm.NewEVM(context, txContext, statedb, eth.blockchain.Config(), vm.Config{})
   204  		statedb.Prepare(tx.Hash(), idx)
   205  		if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
   206  			return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
   207  		}
   208  		// Ensure any modifications are committed to the state
   209  		// Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
   210  		statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
   211  	}
   212  	return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
   213  }