github.com/ethereum/go-ethereum@v1.16.1/core/vm/evm.go (about)

     1  // Copyright 2014 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 vm
    18  
    19  import (
    20  	"errors"
    21  	"math/big"
    22  	"sync/atomic"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/core/state"
    26  	"github.com/ethereum/go-ethereum/core/tracing"
    27  	"github.com/ethereum/go-ethereum/core/types"
    28  	"github.com/ethereum/go-ethereum/crypto"
    29  	"github.com/ethereum/go-ethereum/params"
    30  	"github.com/holiman/uint256"
    31  )
    32  
    33  type (
    34  	// CanTransferFunc is the signature of a transfer guard function
    35  	CanTransferFunc func(StateDB, common.Address, *uint256.Int) bool
    36  	// TransferFunc is the signature of a transfer function
    37  	TransferFunc func(StateDB, common.Address, common.Address, *uint256.Int)
    38  	// GetHashFunc returns the n'th block hash in the blockchain
    39  	// and is used by the BLOCKHASH EVM op code.
    40  	GetHashFunc func(uint64) common.Hash
    41  )
    42  
    43  func (evm *EVM) precompile(addr common.Address) (PrecompiledContract, bool) {
    44  	p, ok := evm.precompiles[addr]
    45  	return p, ok
    46  }
    47  
    48  // BlockContext provides the EVM with auxiliary information. Once provided
    49  // it shouldn't be modified.
    50  type BlockContext struct {
    51  	// CanTransfer returns whether the account contains
    52  	// sufficient ether to transfer the value
    53  	CanTransfer CanTransferFunc
    54  	// Transfer transfers ether from one account to the other
    55  	Transfer TransferFunc
    56  	// GetHash returns the hash corresponding to n
    57  	GetHash GetHashFunc
    58  
    59  	// Block information
    60  	Coinbase    common.Address // Provides information for COINBASE
    61  	GasLimit    uint64         // Provides information for GASLIMIT
    62  	BlockNumber *big.Int       // Provides information for NUMBER
    63  	Time        uint64         // Provides information for TIME
    64  	Difficulty  *big.Int       // Provides information for DIFFICULTY
    65  	BaseFee     *big.Int       // Provides information for BASEFEE (0 if vm runs with NoBaseFee flag and 0 gas price)
    66  	BlobBaseFee *big.Int       // Provides information for BLOBBASEFEE (0 if vm runs with NoBaseFee flag and 0 blob gas price)
    67  	Random      *common.Hash   // Provides information for PREVRANDAO
    68  }
    69  
    70  // TxContext provides the EVM with information about a transaction.
    71  // All fields can change between transactions.
    72  type TxContext struct {
    73  	// Message information
    74  	Origin       common.Address      // Provides information for ORIGIN
    75  	GasPrice     *big.Int            // Provides information for GASPRICE (and is used to zero the basefee if NoBaseFee is set)
    76  	BlobHashes   []common.Hash       // Provides information for BLOBHASH
    77  	BlobFeeCap   *big.Int            // Is used to zero the blobbasefee if NoBaseFee is set
    78  	AccessEvents *state.AccessEvents // Capture all state accesses for this tx
    79  }
    80  
    81  // EVM is the Ethereum Virtual Machine base object and provides
    82  // the necessary tools to run a contract on the given state with
    83  // the provided context. It should be noted that any error
    84  // generated through any of the calls should be considered a
    85  // revert-state-and-consume-all-gas operation, no checks on
    86  // specific errors should ever be performed. The interpreter makes
    87  // sure that any errors generated are to be considered faulty code.
    88  //
    89  // The EVM should never be reused and is not thread safe.
    90  type EVM struct {
    91  	// Context provides auxiliary blockchain related information
    92  	Context BlockContext
    93  	TxContext
    94  
    95  	// StateDB gives access to the underlying state
    96  	StateDB StateDB
    97  
    98  	// depth is the current call stack
    99  	depth int
   100  
   101  	// chainConfig contains information about the current chain
   102  	chainConfig *params.ChainConfig
   103  
   104  	// chain rules contains the chain rules for the current epoch
   105  	chainRules params.Rules
   106  
   107  	// virtual machine configuration options used to initialise the evm
   108  	Config Config
   109  
   110  	// global (to this context) ethereum virtual machine used throughout
   111  	// the execution of the tx
   112  	interpreter *EVMInterpreter
   113  
   114  	// abort is used to abort the EVM calling operations
   115  	abort atomic.Bool
   116  
   117  	// callGasTemp holds the gas available for the current call. This is needed because the
   118  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   119  	// applied in opCall*.
   120  	callGasTemp uint64
   121  
   122  	// precompiles holds the precompiled contracts for the current epoch
   123  	precompiles map[common.Address]PrecompiledContract
   124  
   125  	// jumpDests is the aggregated result of JUMPDEST analysis made through
   126  	// the life cycle of EVM.
   127  	jumpDests map[common.Hash]bitvec
   128  }
   129  
   130  // NewEVM constructs an EVM instance with the supplied block context, state
   131  // database and several configs. It meant to be used throughout the entire
   132  // state transition of a block, with the transaction context switched as
   133  // needed by calling evm.SetTxContext.
   134  func NewEVM(blockCtx BlockContext, statedb StateDB, chainConfig *params.ChainConfig, config Config) *EVM {
   135  	evm := &EVM{
   136  		Context:     blockCtx,
   137  		StateDB:     statedb,
   138  		Config:      config,
   139  		chainConfig: chainConfig,
   140  		chainRules:  chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time),
   141  		jumpDests:   make(map[common.Hash]bitvec),
   142  	}
   143  	evm.precompiles = activePrecompiledContracts(evm.chainRules)
   144  	evm.interpreter = NewEVMInterpreter(evm)
   145  	return evm
   146  }
   147  
   148  // SetPrecompiles sets the precompiled contracts for the EVM.
   149  // This method is only used through RPC calls.
   150  // It is not thread-safe.
   151  func (evm *EVM) SetPrecompiles(precompiles PrecompiledContracts) {
   152  	evm.precompiles = precompiles
   153  }
   154  
   155  // SetTxContext resets the EVM with a new transaction context.
   156  // This is not threadsafe and should only be done very cautiously.
   157  func (evm *EVM) SetTxContext(txCtx TxContext) {
   158  	if evm.chainRules.IsEIP4762 {
   159  		txCtx.AccessEvents = state.NewAccessEvents(evm.StateDB.PointCache())
   160  	}
   161  	evm.TxContext = txCtx
   162  }
   163  
   164  // Cancel cancels any running EVM operation. This may be called concurrently and
   165  // it's safe to be called multiple times.
   166  func (evm *EVM) Cancel() {
   167  	evm.abort.Store(true)
   168  }
   169  
   170  // Cancelled returns true if Cancel has been called
   171  func (evm *EVM) Cancelled() bool {
   172  	return evm.abort.Load()
   173  }
   174  
   175  // Interpreter returns the current interpreter
   176  func (evm *EVM) Interpreter() *EVMInterpreter {
   177  	return evm.interpreter
   178  }
   179  
   180  func isSystemCall(caller common.Address) bool {
   181  	return caller == params.SystemAddress
   182  }
   183  
   184  // Call executes the contract associated with the addr with the given input as
   185  // parameters. It also handles any necessary value transfer required and takse
   186  // the necessary steps to create accounts and reverses the state in case of an
   187  // execution error or failed value transfer.
   188  func (evm *EVM) Call(caller common.Address, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) {
   189  	// Capture the tracer start/end events in debug mode
   190  	if evm.Config.Tracer != nil {
   191  		evm.captureBegin(evm.depth, CALL, caller, addr, input, gas, value.ToBig())
   192  		defer func(startGas uint64) {
   193  			evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
   194  		}(gas)
   195  	}
   196  	// Fail if we're trying to execute above the call depth limit
   197  	if evm.depth > int(params.CallCreateDepth) {
   198  		return nil, gas, ErrDepth
   199  	}
   200  	// Fail if we're trying to transfer more than the available balance
   201  	if !value.IsZero() && !evm.Context.CanTransfer(evm.StateDB, caller, value) {
   202  		return nil, gas, ErrInsufficientBalance
   203  	}
   204  	snapshot := evm.StateDB.Snapshot()
   205  	p, isPrecompile := evm.precompile(addr)
   206  
   207  	if !evm.StateDB.Exist(addr) {
   208  		if !isPrecompile && evm.chainRules.IsEIP4762 && !isSystemCall(caller) {
   209  			// Add proof of absence to witness
   210  			// At this point, the read costs have already been charged, either because this
   211  			// is a direct tx call, in which case it's covered by the intrinsic gas, or because
   212  			// of a CALL instruction, in which case BASIC_DATA has been added to the access
   213  			// list in write mode. If there is enough gas paying for the addition of the code
   214  			// hash leaf to the access list, then account creation will proceed unimpaired.
   215  			// Thus, only pay for the creation of the code hash leaf here.
   216  			wgas := evm.AccessEvents.CodeHashGas(addr, true, gas, false)
   217  			if gas < wgas {
   218  				evm.StateDB.RevertToSnapshot(snapshot)
   219  				return nil, 0, ErrOutOfGas
   220  			}
   221  			gas -= wgas
   222  		}
   223  
   224  		if !isPrecompile && evm.chainRules.IsEIP158 && value.IsZero() {
   225  			// Calling a non-existing account, don't do anything.
   226  			return nil, gas, nil
   227  		}
   228  		evm.StateDB.CreateAccount(addr)
   229  	}
   230  	evm.Context.Transfer(evm.StateDB, caller, addr, value)
   231  
   232  	if isPrecompile {
   233  		ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
   234  	} else {
   235  		// Initialise a new contract and set the code that is to be used by the EVM.
   236  		code := evm.resolveCode(addr)
   237  		if len(code) == 0 {
   238  			ret, err = nil, nil // gas is unchanged
   239  		} else {
   240  			// The contract is a scoped environment for this execution context only.
   241  			contract := NewContract(caller, addr, value, gas, evm.jumpDests)
   242  			contract.IsSystemCall = isSystemCall(caller)
   243  			contract.SetCallCode(evm.resolveCodeHash(addr), code)
   244  			ret, err = evm.interpreter.Run(contract, input, false)
   245  			gas = contract.Gas
   246  		}
   247  	}
   248  	// When an error was returned by the EVM or when setting the creation code
   249  	// above we revert to the snapshot and consume any gas remaining. Additionally,
   250  	// when we're in homestead this also counts for code storage gas errors.
   251  	if err != nil {
   252  		evm.StateDB.RevertToSnapshot(snapshot)
   253  		if err != ErrExecutionReverted {
   254  			if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil {
   255  				evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution)
   256  			}
   257  
   258  			gas = 0
   259  		}
   260  		// TODO: consider clearing up unused snapshots:
   261  		//} else {
   262  		//	evm.StateDB.DiscardSnapshot(snapshot)
   263  	}
   264  	return ret, gas, err
   265  }
   266  
   267  // CallCode executes the contract associated with the addr with the given input
   268  // as parameters. It also handles any necessary value transfer required and takes
   269  // the necessary steps to create accounts and reverses the state in case of an
   270  // execution error or failed value transfer.
   271  //
   272  // CallCode differs from Call in the sense that it executes the given address'
   273  // code with the caller as context.
   274  func (evm *EVM) CallCode(caller common.Address, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) {
   275  	// Invoke tracer hooks that signal entering/exiting a call frame
   276  	if evm.Config.Tracer != nil {
   277  		evm.captureBegin(evm.depth, CALLCODE, caller, addr, input, gas, value.ToBig())
   278  		defer func(startGas uint64) {
   279  			evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
   280  		}(gas)
   281  	}
   282  	// Fail if we're trying to execute above the call depth limit
   283  	if evm.depth > int(params.CallCreateDepth) {
   284  		return nil, gas, ErrDepth
   285  	}
   286  	// Fail if we're trying to transfer more than the available balance
   287  	// Note although it's noop to transfer X ether to caller itself. But
   288  	// if caller doesn't have enough balance, it would be an error to allow
   289  	// over-charging itself. So the check here is necessary.
   290  	if !evm.Context.CanTransfer(evm.StateDB, caller, value) {
   291  		return nil, gas, ErrInsufficientBalance
   292  	}
   293  	var snapshot = evm.StateDB.Snapshot()
   294  
   295  	// It is allowed to call precompiles, even via delegatecall
   296  	if p, isPrecompile := evm.precompile(addr); isPrecompile {
   297  		ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
   298  	} else {
   299  		// Initialise a new contract and set the code that is to be used by the EVM.
   300  		// The contract is a scoped environment for this execution context only.
   301  		contract := NewContract(caller, caller, value, gas, evm.jumpDests)
   302  		contract.SetCallCode(evm.resolveCodeHash(addr), evm.resolveCode(addr))
   303  		ret, err = evm.interpreter.Run(contract, input, false)
   304  		gas = contract.Gas
   305  	}
   306  	if err != nil {
   307  		evm.StateDB.RevertToSnapshot(snapshot)
   308  		if err != ErrExecutionReverted {
   309  			if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil {
   310  				evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution)
   311  			}
   312  			gas = 0
   313  		}
   314  	}
   315  	return ret, gas, err
   316  }
   317  
   318  // DelegateCall executes the contract associated with the addr with the given input
   319  // as parameters. It reverses the state in case of an execution error.
   320  //
   321  // DelegateCall differs from CallCode in the sense that it executes the given address'
   322  // code with the caller as context and the caller is set to the caller of the caller.
   323  func (evm *EVM) DelegateCall(originCaller common.Address, caller common.Address, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) {
   324  	// Invoke tracer hooks that signal entering/exiting a call frame
   325  	if evm.Config.Tracer != nil {
   326  		// DELEGATECALL inherits value from parent call
   327  		evm.captureBegin(evm.depth, DELEGATECALL, caller, addr, input, gas, value.ToBig())
   328  		defer func(startGas uint64) {
   329  			evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
   330  		}(gas)
   331  	}
   332  	// Fail if we're trying to execute above the call depth limit
   333  	if evm.depth > int(params.CallCreateDepth) {
   334  		return nil, gas, ErrDepth
   335  	}
   336  	var snapshot = evm.StateDB.Snapshot()
   337  
   338  	// It is allowed to call precompiles, even via delegatecall
   339  	if p, isPrecompile := evm.precompile(addr); isPrecompile {
   340  		ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
   341  	} else {
   342  		// Initialise a new contract and make initialise the delegate values
   343  		//
   344  		// Note: The value refers to the original value from the parent call.
   345  		contract := NewContract(originCaller, caller, value, gas, evm.jumpDests)
   346  		contract.SetCallCode(evm.resolveCodeHash(addr), evm.resolveCode(addr))
   347  		ret, err = evm.interpreter.Run(contract, input, false)
   348  		gas = contract.Gas
   349  	}
   350  	if err != nil {
   351  		evm.StateDB.RevertToSnapshot(snapshot)
   352  		if err != ErrExecutionReverted {
   353  			if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil {
   354  				evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution)
   355  			}
   356  			gas = 0
   357  		}
   358  	}
   359  	return ret, gas, err
   360  }
   361  
   362  // StaticCall executes the contract associated with the addr with the given input
   363  // as parameters while disallowing any modifications to the state during the call.
   364  // Opcodes that attempt to perform such modifications will result in exceptions
   365  // instead of performing the modifications.
   366  func (evm *EVM) StaticCall(caller common.Address, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   367  	// Invoke tracer hooks that signal entering/exiting a call frame
   368  	if evm.Config.Tracer != nil {
   369  		evm.captureBegin(evm.depth, STATICCALL, caller, addr, input, gas, nil)
   370  		defer func(startGas uint64) {
   371  			evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
   372  		}(gas)
   373  	}
   374  	// Fail if we're trying to execute above the call depth limit
   375  	if evm.depth > int(params.CallCreateDepth) {
   376  		return nil, gas, ErrDepth
   377  	}
   378  	// We take a snapshot here. This is a bit counter-intuitive, and could probably be skipped.
   379  	// However, even a staticcall is considered a 'touch'. On mainnet, static calls were introduced
   380  	// after all empty accounts were deleted, so this is not required. However, if we omit this,
   381  	// then certain tests start failing; stRevertTest/RevertPrecompiledTouchExactOOG.json.
   382  	// We could change this, but for now it's left for legacy reasons
   383  	var snapshot = evm.StateDB.Snapshot()
   384  
   385  	// We do an AddBalance of zero here, just in order to trigger a touch.
   386  	// This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium,
   387  	// but is the correct thing to do and matters on other networks, in tests, and potential
   388  	// future scenarios
   389  	evm.StateDB.AddBalance(addr, new(uint256.Int), tracing.BalanceChangeTouchAccount)
   390  
   391  	if p, isPrecompile := evm.precompile(addr); isPrecompile {
   392  		ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer)
   393  	} else {
   394  		// Initialise a new contract and set the code that is to be used by the EVM.
   395  		// The contract is a scoped environment for this execution context only.
   396  		contract := NewContract(caller, addr, new(uint256.Int), gas, evm.jumpDests)
   397  		contract.SetCallCode(evm.resolveCodeHash(addr), evm.resolveCode(addr))
   398  
   399  		// When an error was returned by the EVM or when setting the creation code
   400  		// above we revert to the snapshot and consume any gas remaining. Additionally
   401  		// when we're in Homestead this also counts for code storage gas errors.
   402  		ret, err = evm.interpreter.Run(contract, input, true)
   403  		gas = contract.Gas
   404  	}
   405  	if err != nil {
   406  		evm.StateDB.RevertToSnapshot(snapshot)
   407  		if err != ErrExecutionReverted {
   408  			if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil {
   409  				evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution)
   410  			}
   411  
   412  			gas = 0
   413  		}
   414  	}
   415  	return ret, gas, err
   416  }
   417  
   418  // create creates a new contract using code as deployment code.
   419  func (evm *EVM) create(caller common.Address, code []byte, gas uint64, value *uint256.Int, address common.Address, typ OpCode) (ret []byte, createAddress common.Address, leftOverGas uint64, err error) {
   420  	if evm.Config.Tracer != nil {
   421  		evm.captureBegin(evm.depth, typ, caller, address, code, gas, value.ToBig())
   422  		defer func(startGas uint64) {
   423  			evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err)
   424  		}(gas)
   425  	}
   426  	// Depth check execution. Fail if we're trying to execute above the
   427  	// limit.
   428  	if evm.depth > int(params.CallCreateDepth) {
   429  		return nil, common.Address{}, gas, ErrDepth
   430  	}
   431  	if !evm.Context.CanTransfer(evm.StateDB, caller, value) {
   432  		return nil, common.Address{}, gas, ErrInsufficientBalance
   433  	}
   434  	nonce := evm.StateDB.GetNonce(caller)
   435  	if nonce+1 < nonce {
   436  		return nil, common.Address{}, gas, ErrNonceUintOverflow
   437  	}
   438  	evm.StateDB.SetNonce(caller, nonce+1, tracing.NonceChangeContractCreator)
   439  
   440  	// Charge the contract creation init gas in verkle mode
   441  	if evm.chainRules.IsEIP4762 {
   442  		statelessGas := evm.AccessEvents.ContractCreatePreCheckGas(address, gas)
   443  		if statelessGas > gas {
   444  			return nil, common.Address{}, 0, ErrOutOfGas
   445  		}
   446  		if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil {
   447  			evm.Config.Tracer.OnGasChange(gas, gas-statelessGas, tracing.GasChangeWitnessContractCollisionCheck)
   448  		}
   449  		gas = gas - statelessGas
   450  	}
   451  
   452  	// We add this to the access list _before_ taking a snapshot. Even if the
   453  	// creation fails, the access-list change should not be rolled back.
   454  	if evm.chainRules.IsEIP2929 {
   455  		evm.StateDB.AddAddressToAccessList(address)
   456  	}
   457  	// Ensure there's no existing contract already at the designated address.
   458  	// Account is regarded as existent if any of these three conditions is met:
   459  	// - the nonce is non-zero
   460  	// - the code is non-empty
   461  	// - the storage is non-empty
   462  	contractHash := evm.StateDB.GetCodeHash(address)
   463  	storageRoot := evm.StateDB.GetStorageRoot(address)
   464  	if evm.StateDB.GetNonce(address) != 0 ||
   465  		(contractHash != (common.Hash{}) && contractHash != types.EmptyCodeHash) || // non-empty code
   466  		(storageRoot != (common.Hash{}) && storageRoot != types.EmptyRootHash) { // non-empty storage
   467  		if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil {
   468  			evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution)
   469  		}
   470  		return nil, common.Address{}, 0, ErrContractAddressCollision
   471  	}
   472  	// Create a new account on the state only if the object was not present.
   473  	// It might be possible the contract code is deployed to a pre-existent
   474  	// account with non-zero balance.
   475  	snapshot := evm.StateDB.Snapshot()
   476  	if !evm.StateDB.Exist(address) {
   477  		evm.StateDB.CreateAccount(address)
   478  	}
   479  	// CreateContract means that regardless of whether the account previously existed
   480  	// in the state trie or not, it _now_ becomes created as a _contract_ account.
   481  	// This is performed _prior_ to executing the initcode,  since the initcode
   482  	// acts inside that account.
   483  	evm.StateDB.CreateContract(address)
   484  
   485  	if evm.chainRules.IsEIP158 {
   486  		evm.StateDB.SetNonce(address, 1, tracing.NonceChangeNewContract)
   487  	}
   488  	// Charge the contract creation init gas in verkle mode
   489  	if evm.chainRules.IsEIP4762 {
   490  		consumed, wanted := evm.AccessEvents.ContractCreateInitGas(address, gas)
   491  		if consumed < wanted {
   492  			return nil, common.Address{}, 0, ErrOutOfGas
   493  		}
   494  		if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil {
   495  			evm.Config.Tracer.OnGasChange(gas, gas-consumed, tracing.GasChangeWitnessContractInit)
   496  		}
   497  		gas = gas - consumed
   498  	}
   499  	evm.Context.Transfer(evm.StateDB, caller, address, value)
   500  
   501  	// Initialise a new contract and set the code that is to be used by the EVM.
   502  	// The contract is a scoped environment for this execution context only.
   503  	contract := NewContract(caller, address, value, gas, evm.jumpDests)
   504  
   505  	// Explicitly set the code to a null hash to prevent caching of jump analysis
   506  	// for the initialization code.
   507  	contract.SetCallCode(common.Hash{}, code)
   508  	contract.IsDeployment = true
   509  
   510  	ret, err = evm.initNewContract(contract, address)
   511  	if err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas) {
   512  		evm.StateDB.RevertToSnapshot(snapshot)
   513  		if err != ErrExecutionReverted {
   514  			contract.UseGas(contract.Gas, evm.Config.Tracer, tracing.GasChangeCallFailedExecution)
   515  		}
   516  	}
   517  	return ret, address, contract.Gas, err
   518  }
   519  
   520  // initNewContract runs a new contract's creation code, performs checks on the
   521  // resulting code that is to be deployed, and consumes necessary gas.
   522  func (evm *EVM) initNewContract(contract *Contract, address common.Address) ([]byte, error) {
   523  	ret, err := evm.interpreter.Run(contract, nil, false)
   524  	if err != nil {
   525  		return ret, err
   526  	}
   527  
   528  	// Check whether the max code size has been exceeded, assign err if the case.
   529  	if evm.chainRules.IsEIP158 && len(ret) > params.MaxCodeSize {
   530  		return ret, ErrMaxCodeSizeExceeded
   531  	}
   532  
   533  	// Reject code starting with 0xEF if EIP-3541 is enabled.
   534  	if len(ret) >= 1 && ret[0] == 0xEF && evm.chainRules.IsLondon {
   535  		return ret, ErrInvalidCode
   536  	}
   537  
   538  	if !evm.chainRules.IsEIP4762 {
   539  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   540  		if !contract.UseGas(createDataGas, evm.Config.Tracer, tracing.GasChangeCallCodeStorage) {
   541  			return ret, ErrCodeStoreOutOfGas
   542  		}
   543  	} else {
   544  		consumed, wanted := evm.AccessEvents.CodeChunksRangeGas(address, 0, uint64(len(ret)), uint64(len(ret)), true, contract.Gas)
   545  		contract.UseGas(consumed, evm.Config.Tracer, tracing.GasChangeWitnessCodeChunk)
   546  		if len(ret) > 0 && (consumed < wanted) {
   547  			return ret, ErrCodeStoreOutOfGas
   548  		}
   549  	}
   550  
   551  	evm.StateDB.SetCode(address, ret)
   552  	return ret, nil
   553  }
   554  
   555  // Create creates a new contract using code as deployment code.
   556  func (evm *EVM) Create(caller common.Address, code []byte, gas uint64, value *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   557  	contractAddr = crypto.CreateAddress(caller, evm.StateDB.GetNonce(caller))
   558  	return evm.create(caller, code, gas, value, contractAddr, CREATE)
   559  }
   560  
   561  // Create2 creates a new contract using code as deployment code.
   562  //
   563  // The different between Create2 with Create is Create2 uses keccak256(0xff ++ msg.sender ++ salt ++ keccak256(init_code))[12:]
   564  // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
   565  func (evm *EVM) Create2(caller common.Address, code []byte, gas uint64, endowment *uint256.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   566  	inithash := crypto.HashData(evm.interpreter.hasher, code)
   567  	contractAddr = crypto.CreateAddress2(caller, salt.Bytes32(), inithash[:])
   568  	return evm.create(caller, code, gas, endowment, contractAddr, CREATE2)
   569  }
   570  
   571  // resolveCode returns the code associated with the provided account. After
   572  // Prague, it can also resolve code pointed to by a delegation designator.
   573  func (evm *EVM) resolveCode(addr common.Address) []byte {
   574  	code := evm.StateDB.GetCode(addr)
   575  	if !evm.chainRules.IsPrague {
   576  		return code
   577  	}
   578  	if target, ok := types.ParseDelegation(code); ok {
   579  		// Note we only follow one level of delegation.
   580  		return evm.StateDB.GetCode(target)
   581  	}
   582  	return code
   583  }
   584  
   585  // resolveCodeHash returns the code hash associated with the provided address.
   586  // After Prague, it can also resolve code hash of the account pointed to by a
   587  // delegation designator. Although this is not accessible in the EVM it is used
   588  // internally to associate jumpdest analysis to code.
   589  func (evm *EVM) resolveCodeHash(addr common.Address) common.Hash {
   590  	if evm.chainRules.IsPrague {
   591  		code := evm.StateDB.GetCode(addr)
   592  		if target, ok := types.ParseDelegation(code); ok {
   593  			// Note we only follow one level of delegation.
   594  			return evm.StateDB.GetCodeHash(target)
   595  		}
   596  	}
   597  	return evm.StateDB.GetCodeHash(addr)
   598  }
   599  
   600  // ChainConfig returns the environment's chain configuration
   601  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }
   602  
   603  func (evm *EVM) captureBegin(depth int, typ OpCode, from common.Address, to common.Address, input []byte, startGas uint64, value *big.Int) {
   604  	tracer := evm.Config.Tracer
   605  	if tracer.OnEnter != nil {
   606  		tracer.OnEnter(depth, byte(typ), from, to, input, startGas, value)
   607  	}
   608  	if tracer.OnGasChange != nil {
   609  		tracer.OnGasChange(0, startGas, tracing.GasChangeCallInitialBalance)
   610  	}
   611  }
   612  
   613  func (evm *EVM) captureEnd(depth int, startGas uint64, leftOverGas uint64, ret []byte, err error) {
   614  	tracer := evm.Config.Tracer
   615  	if leftOverGas != 0 && tracer.OnGasChange != nil {
   616  		tracer.OnGasChange(leftOverGas, 0, tracing.GasChangeCallLeftOverReturned)
   617  	}
   618  	var reverted bool
   619  	if err != nil {
   620  		reverted = true
   621  	}
   622  	if !evm.chainRules.IsHomestead && errors.Is(err, ErrCodeStoreOutOfGas) {
   623  		reverted = false
   624  	}
   625  	if tracer.OnExit != nil {
   626  		tracer.OnExit(depth, ret, startGas-leftOverGas, VMErrorFromErr(err), reverted)
   627  	}
   628  }
   629  
   630  // GetVMContext provides context about the block being executed as well as state
   631  // to the tracers.
   632  func (evm *EVM) GetVMContext() *tracing.VMContext {
   633  	return &tracing.VMContext{
   634  		Coinbase:    evm.Context.Coinbase,
   635  		BlockNumber: evm.Context.BlockNumber,
   636  		Time:        evm.Context.Time,
   637  		Random:      evm.Context.Random,
   638  		BaseFee:     evm.Context.BaseFee,
   639  		StateDB:     evm.StateDB,
   640  	}
   641  }