github.com/klaytn/klaytn@v1.10.2/node/cn/state_accessor.go (about)

     1  // Modifications Copyright 2022 The klaytn Authors
     2  // Copyright 2021 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  // This file is derived from eth/state_accessor.go (2022/08/08).
    19  // Modified and improved for the klaytn development.
    20  
    21  package cn
    22  
    23  import (
    24  	"errors"
    25  	"fmt"
    26  	"time"
    27  
    28  	"github.com/klaytn/klaytn/blockchain"
    29  	"github.com/klaytn/klaytn/blockchain/state"
    30  	"github.com/klaytn/klaytn/blockchain/types"
    31  	"github.com/klaytn/klaytn/blockchain/vm"
    32  	"github.com/klaytn/klaytn/common"
    33  	statedb2 "github.com/klaytn/klaytn/storage/statedb"
    34  )
    35  
    36  // stateAtBlock retrieves the state database associated with a certain block.
    37  // If no state is locally available for the given block, a number of blocks
    38  // are attempted to be reexecuted to generate the desired state. The optional
    39  // base layer statedb can be passed then it's regarded as the statedb of the
    40  // parent block.
    41  // Parameters:
    42  // - block: The block for which we want the state (== state at the stateRoot of the parent)
    43  // - reexec: The maximum number of blocks to reprocess trying to obtain the desired state
    44  // - base: If the caller is tracing multiple blocks, the caller can provide the parent state
    45  //         continuously from the callsite.
    46  // - checklive: if true, then the live 'blockchain' state database is used. If the caller want to
    47  //        perform Commit or other 'save-to-disk' changes, this should be set to false to avoid
    48  //        storing trash persistently
    49  // - preferDisk: this arg can be used by the caller to signal that even though the 'base' is provided,
    50  //        it would be preferrable to start from a fresh state, if we have it on disk.
    51  func (cn *CN) stateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (statedb *state.StateDB, err error) {
    52  	var (
    53  		current  *types.Block
    54  		database state.Database
    55  		report   = true
    56  		origin   = block.NumberU64()
    57  	)
    58  	// Check the live database first if we have the state fully available, use that.
    59  	if checkLive {
    60  		statedb, err = cn.blockchain.StateAt(block.Root())
    61  		if err == nil {
    62  			return statedb, nil
    63  		}
    64  	}
    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  			database = state.NewDatabaseWithExistingCache(cn.ChainDB(), cn.blockchain.StateCache().TrieDB().TrieNodeCache())
    70  			if statedb, err = state.New(block.Root(), database, nil); err == nil {
    71  				logger.Info("Found disk backend for state trie", "root", block.Root(), "number", block.Number())
    72  				return statedb, nil
    73  			}
    74  		}
    75  		// The optional base statedb is given, mark the start point as parent block
    76  		statedb, database, report = base, base.Database(), false
    77  		current = cn.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
    78  	} else {
    79  		// Otherwise try to reexec blocks until we find a state or reach our limit
    80  		current = block
    81  
    82  		// Create an ephemeral trie.Database for isolating the live one. Otherwise
    83  		// the internal junks created by tracing will be persisted into the disk.
    84  		database = state.NewDatabaseWithExistingCache(cn.ChainDB(), cn.blockchain.StateCache().TrieDB().TrieNodeCache())
    85  
    86  		for i := uint64(0); i < reexec; i++ {
    87  			if current.NumberU64() == 0 {
    88  				return nil, errors.New("genesis state is missing")
    89  			}
    90  			parent := cn.blockchain.GetBlock(current.ParentHash(), current.NumberU64()-1)
    91  			if parent == nil {
    92  				return nil, fmt.Errorf("missing block %v %d", current.ParentHash(), current.NumberU64()-1)
    93  			}
    94  			current = parent
    95  
    96  			statedb, err = state.New(current.Root(), database, nil)
    97  			if err == nil {
    98  				break
    99  			}
   100  		}
   101  		if err != nil {
   102  			switch err.(type) {
   103  			case *statedb2.MissingNodeError:
   104  				return nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec)
   105  			default:
   106  				return nil, err
   107  			}
   108  		}
   109  	}
   110  	// State was available at historical point, regenerate
   111  	var (
   112  		start  = time.Now()
   113  		logged time.Time
   114  		parent common.Hash
   115  	)
   116  	for current.NumberU64() < origin {
   117  		// Print progress logs if long enough time elapsed
   118  		if time.Since(logged) > 8*time.Second && report {
   119  			logger.Info("Regenerating historical state", "block", current.NumberU64()+1, "target", origin, "remaining", origin-block.NumberU64()-1, "elapsed", time.Since(start))
   120  			logged = time.Now()
   121  		}
   122  		// Retrieve the next block to regenerate and process it
   123  		next := current.NumberU64() + 1
   124  		if current = cn.blockchain.GetBlockByNumber(next); current == nil {
   125  			return nil, fmt.Errorf("block #%d not found", next)
   126  		}
   127  		_, _, _, _, _, err := cn.blockchain.Processor().Process(current, statedb, vm.Config{UseOpcodeComputationCost: true})
   128  		if err != nil {
   129  			return nil, fmt.Errorf("processing block %d failed: %v", current.NumberU64(), err)
   130  		}
   131  		// Finalize the state so any modifications are written to the trie
   132  		root, err := statedb.Commit(true)
   133  		if err != nil {
   134  			return nil, err
   135  		}
   136  		if err := statedb.Reset(root); err != nil {
   137  			return nil, fmt.Errorf("state reset after block %d failed: %v", current.NumberU64(), err)
   138  		}
   139  		database.TrieDB().Reference(root, common.Hash{})
   140  		if !common.EmptyHash(parent) {
   141  			database.TrieDB().Dereference(parent)
   142  		}
   143  		parent = root
   144  	}
   145  	if report {
   146  		nodes, _, imgs := database.TrieDB().Size()
   147  		logger.Info("Historical state regenerated", "block", current.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
   148  	}
   149  
   150  	return statedb, nil
   151  }
   152  
   153  // stateAtTransaction returns the execution environment of a certain transaction.
   154  func (cn *CN) stateAtTransaction(block *types.Block, txIndex int, reexec uint64) (blockchain.Message, vm.Context, *state.StateDB, error) {
   155  	// Short circuit if it's genesis block.
   156  	if block.NumberU64() == 0 {
   157  		return nil, vm.Context{}, nil, errors.New("no transaction in genesis")
   158  	}
   159  	// Create the parent state database
   160  	parent := cn.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
   161  	if parent == nil {
   162  		return nil, vm.Context{}, nil, fmt.Errorf("parent %#x not found", block.ParentHash())
   163  	}
   164  	// Lookup the statedb of parent block from the live database,
   165  	// otherwise regenerate it on the flight.
   166  	statedb, err := cn.stateAtBlock(parent, reexec, nil, true, false)
   167  	if err != nil {
   168  		return nil, vm.Context{}, nil, err
   169  	}
   170  	if txIndex == 0 && len(block.Transactions()) == 0 {
   171  		return nil, vm.Context{}, statedb, nil
   172  	}
   173  	// Recompute transactions up to the target index.
   174  	signer := types.MakeSigner(cn.blockchain.Config(), block.Number())
   175  	for idx, tx := range block.Transactions() {
   176  		// Assemble the transaction call message and return if the requested offset
   177  		msg, err := tx.AsMessageWithAccountKeyPicker(signer, statedb, block.NumberU64())
   178  		if err != nil {
   179  			logger.Warn("stateAtTransition failed", "hash", tx.Hash(), "block", block.NumberU64(), "err", err)
   180  			return nil, vm.Context{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
   181  		}
   182  
   183  		context := blockchain.NewEVMContext(msg, block.Header(), cn.blockchain, nil)
   184  		if idx == txIndex {
   185  			return msg, context, statedb, nil
   186  		}
   187  		// Not yet the searched for transaction, execute on top of the current state
   188  		vmenv := vm.NewEVM(context, statedb, cn.blockchain.Config(), &vm.Config{UseOpcodeComputationCost: true})
   189  		if _, _, kerr := blockchain.ApplyMessage(vmenv, msg); kerr.ErrTxInvalid != nil {
   190  			return nil, vm.Context{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
   191  		}
   192  		// Ensure any modifications are committed to the state
   193  		// Since klaytn is forked after EIP158/161 (a.k.a Spurious Dragon), deleting empty object is always effective
   194  		statedb.Finalise(true, true)
   195  	}
   196  	return nil, vm.Context{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
   197  }