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