github.com/tacshi/go-ethereum@v0.0.0-20230616113857-84a434e20921/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  	"math/big"
    21  	"sync/atomic"
    22  
    23  	"github.com/holiman/uint256"
    24  
    25  	"github.com/tacshi/go-ethereum/common"
    26  	"github.com/tacshi/go-ethereum/crypto"
    27  	"github.com/tacshi/go-ethereum/params"
    28  )
    29  
    30  // emptyCodeHash is used by create to ensure deployment is disallowed to already
    31  // deployed contract addresses (relevant after the account abstraction).
    32  var emptyCodeHash = crypto.Keccak256Hash(nil)
    33  
    34  type (
    35  	// CanTransferFunc is the signature of a transfer guard function
    36  	CanTransferFunc func(StateDB, common.Address, *big.Int) bool
    37  	// TransferFunc is the signature of a transfer function
    38  	TransferFunc func(StateDB, common.Address, common.Address, *big.Int)
    39  	// GetHashFunc returns the n'th block hash in the blockchain
    40  	// and is used by the BLOCKHASH EVM op code.
    41  	GetHashFunc func(uint64) common.Hash
    42  )
    43  
    44  func (evm *EVM) precompile(addr common.Address) (PrecompiledContract, bool) {
    45  	var precompiles map[common.Address]PrecompiledContract
    46  	switch {
    47  	case evm.chainRules.IsArbitrum:
    48  		precompiles = PrecompiledContractsArbitrum
    49  	case evm.chainRules.IsBerlin:
    50  		precompiles = PrecompiledContractsBerlin
    51  	case evm.chainRules.IsIstanbul:
    52  		precompiles = PrecompiledContractsIstanbul
    53  	case evm.chainRules.IsByzantium:
    54  		precompiles = PrecompiledContractsByzantium
    55  	default:
    56  		precompiles = PrecompiledContractsHomestead
    57  	}
    58  	p, ok := precompiles[addr]
    59  	return p, ok
    60  }
    61  
    62  // BlockContext provides the EVM with auxiliary information. Once provided
    63  // it shouldn't be modified.
    64  type BlockContext struct {
    65  	// CanTransfer returns whether the account contains
    66  	// sufficient ether to transfer the value
    67  	CanTransfer CanTransferFunc
    68  	// Transfer transfers ether from one account to the other
    69  	Transfer TransferFunc
    70  	// GetHash returns the hash corresponding to n
    71  	GetHash GetHashFunc
    72  
    73  	// Block information
    74  	Coinbase    common.Address // Provides information for COINBASE
    75  	GasLimit    uint64         // Provides information for GASLIMIT
    76  	BlockNumber *big.Int       // Provides information for NUMBER
    77  	Time        uint64         // Provides information for TIME
    78  	Difficulty  *big.Int       // Provides information for DIFFICULTY
    79  	BaseFee     *big.Int       // Provides information for BASEFEE
    80  	Random      *common.Hash   // Provides information for PREVRANDAO
    81  
    82  	// Arbitrum information
    83  	ArbOSVersion uint64
    84  }
    85  
    86  // TxContext provides the EVM with information about a transaction.
    87  // All fields can change between transactions.
    88  type TxContext struct {
    89  	// Message information
    90  	Origin   common.Address // Provides information for ORIGIN
    91  	GasPrice *big.Int       // Provides information for GASPRICE
    92  }
    93  
    94  // EVM is the Ethereum Virtual Machine base object and provides
    95  // the necessary tools to run a contract on the given state with
    96  // the provided context. It should be noted that any error
    97  // generated through any of the calls should be considered a
    98  // revert-state-and-consume-all-gas operation, no checks on
    99  // specific errors should ever be performed. The interpreter makes
   100  // sure that any errors generated are to be considered faulty code.
   101  //
   102  // The EVM should never be reused and is not thread safe.
   103  type EVM struct {
   104  	ProcessingHook TxProcessingHook
   105  
   106  	// Context provides auxiliary blockchain related information
   107  	Context BlockContext
   108  	TxContext
   109  	// StateDB gives access to the underlying state
   110  	StateDB StateDB
   111  	// Depth is the current call stack
   112  	depth int
   113  
   114  	// chainConfig contains information about the current chain
   115  	chainConfig *params.ChainConfig
   116  	// chain rules contains the chain rules for the current epoch
   117  	chainRules params.Rules
   118  	// virtual machine configuration options used to initialise the
   119  	// evm.
   120  	Config Config
   121  	// global (to this context) ethereum virtual machine
   122  	// used throughout the execution of the tx.
   123  	interpreter *EVMInterpreter
   124  	// abort is used to abort the EVM calling operations
   125  	// NOTE: must be set atomically
   126  	abort int32
   127  	// callGasTemp holds the gas available for the current call. This is needed because the
   128  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   129  	// applied in opCall*.
   130  	callGasTemp uint64
   131  }
   132  
   133  // NewEVM returns a new EVM. The returned EVM is not thread safe and should
   134  // only ever be used *once*.
   135  func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb StateDB, chainConfig *params.ChainConfig, config Config) *EVM {
   136  	evm := &EVM{
   137  		Context:     blockCtx,
   138  		TxContext:   txCtx,
   139  		StateDB:     statedb,
   140  		Config:      config,
   141  		chainConfig: chainConfig,
   142  		chainRules:  chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time, blockCtx.ArbOSVersion),
   143  	}
   144  	evm.ProcessingHook = DefaultTxProcessor{evm: evm}
   145  	evm.interpreter = NewEVMInterpreter(evm)
   146  	return evm
   147  }
   148  
   149  // Reset resets the EVM with a new transaction context.Reset
   150  // This is not threadsafe and should only be done very cautiously.
   151  func (evm *EVM) Reset(txCtx TxContext, statedb StateDB) {
   152  	evm.TxContext = txCtx
   153  	evm.StateDB = statedb
   154  }
   155  
   156  // Cancel cancels any running EVM operation. This may be called concurrently and
   157  // it's safe to be called multiple times.
   158  func (evm *EVM) Cancel() {
   159  	atomic.StoreInt32(&evm.abort, 1)
   160  }
   161  
   162  // Cancelled returns true if Cancel has been called
   163  func (evm *EVM) Cancelled() bool {
   164  	return atomic.LoadInt32(&evm.abort) == 1
   165  }
   166  
   167  // Interpreter returns the current interpreter
   168  func (evm *EVM) Interpreter() *EVMInterpreter {
   169  	return evm.interpreter
   170  }
   171  
   172  // SetBlockContext updates the block context of the EVM.
   173  func (evm *EVM) SetBlockContext(blockCtx BlockContext) {
   174  	evm.Context = blockCtx
   175  	num := blockCtx.BlockNumber
   176  	timestamp := blockCtx.Time
   177  	evm.chainRules = evm.chainConfig.Rules(num, blockCtx.Random != nil, timestamp, blockCtx.ArbOSVersion)
   178  }
   179  
   180  // Call executes the contract associated with the addr with the given input as
   181  // parameters. It also handles any necessary value transfer required and takes
   182  // the necessary steps to create accounts and reverses the state in case of an
   183  // execution error or failed value transfer.
   184  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   185  	// Fail if we're trying to execute above the call depth limit
   186  	if evm.depth > int(params.CallCreateDepth) {
   187  		return nil, gas, ErrDepth
   188  	}
   189  	// Fail if we're trying to transfer more than the available balance
   190  	if value.Sign() != 0 && !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   191  		return nil, gas, ErrInsufficientBalance
   192  	}
   193  	snapshot := evm.StateDB.Snapshot()
   194  	p, isPrecompile := evm.precompile(addr)
   195  
   196  	if !evm.StateDB.Exist(addr) {
   197  		if !isPrecompile && evm.chainRules.IsEIP158 && value.Sign() == 0 {
   198  			// Calling a non existing account, don't do anything, but ping the tracer
   199  			if evm.Config.Debug {
   200  				if evm.depth == 0 {
   201  					evm.Config.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value)
   202  					evm.Config.Tracer.CaptureEnd(ret, 0, nil)
   203  				} else {
   204  					evm.Config.Tracer.CaptureEnter(CALL, caller.Address(), addr, input, gas, value)
   205  					evm.Config.Tracer.CaptureExit(ret, 0, nil)
   206  				}
   207  			}
   208  			return nil, gas, nil
   209  		}
   210  		evm.StateDB.CreateAccount(addr)
   211  	}
   212  	evm.Context.Transfer(evm.StateDB, caller.Address(), addr, value)
   213  
   214  	// Capture the tracer start/end events in debug mode
   215  	if evm.Config.Debug {
   216  		if evm.depth == 0 {
   217  			evm.Config.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value)
   218  			defer func(startGas uint64) { // Lazy evaluation of the parameters
   219  				evm.Config.Tracer.CaptureEnd(ret, startGas-gas, err)
   220  			}(gas)
   221  		} else {
   222  			// Handle tracer events for entering and exiting a call frame
   223  			evm.Config.Tracer.CaptureEnter(CALL, caller.Address(), addr, input, gas, value)
   224  			defer func(startGas uint64) {
   225  				evm.Config.Tracer.CaptureExit(ret, startGas-gas, err)
   226  			}(gas)
   227  		}
   228  	}
   229  
   230  	if isPrecompile {
   231  		info := &AdvancedPrecompileCall{
   232  			PrecompileAddress: addr,
   233  			ActingAsAddress:   addr,
   234  			Caller:            caller.Address(),
   235  			Value:             value,
   236  			ReadOnly:          false,
   237  			Evm:               evm,
   238  		}
   239  		ret, gas, err = RunPrecompiledContract(p, input, gas, info)
   240  	} else {
   241  		// Initialise a new contract and set the code that is to be used by the EVM.
   242  		// The contract is a scoped environment for this execution context only.
   243  		code := evm.StateDB.GetCode(addr)
   244  		if len(code) == 0 {
   245  			ret, err = nil, nil // gas is unchanged
   246  		} else {
   247  			addrCopy := addr
   248  			// If the account has no code, we can abort here
   249  			// The depth-check is already done, and precompiles handled above
   250  			contract := NewContract(caller, AccountRef(addrCopy), value, gas)
   251  			contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), code)
   252  			ret, err = evm.interpreter.Run(contract, input, false)
   253  			gas = contract.Gas
   254  		}
   255  	}
   256  	// When an error was returned by the EVM or when setting the creation code
   257  	// above we revert to the snapshot and consume any gas remaining. Additionally
   258  	// when we're in homestead this also counts for code storage gas errors.
   259  	if err != nil {
   260  		evm.StateDB.RevertToSnapshot(snapshot)
   261  		if err != ErrExecutionReverted {
   262  			gas = 0
   263  		}
   264  		// TODO: consider clearing up unused snapshots:
   265  		//} else {
   266  		//	evm.StateDB.DiscardSnapshot(snapshot)
   267  	}
   268  	return ret, gas, err
   269  }
   270  
   271  // CallCode executes the contract associated with the addr with the given input
   272  // as parameters. It also handles any necessary value transfer required and takes
   273  // the necessary steps to create accounts and reverses the state in case of an
   274  // execution error or failed value transfer.
   275  //
   276  // CallCode differs from Call in the sense that it executes the given address'
   277  // code with the caller as context.
   278  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   279  	// Fail if we're trying to execute above the call depth limit
   280  	if evm.depth > int(params.CallCreateDepth) {
   281  		return nil, gas, ErrDepth
   282  	}
   283  	// Fail if we're trying to transfer more than the available balance
   284  	// Note although it's noop to transfer X ether to caller itself. But
   285  	// if caller doesn't have enough balance, it would be an error to allow
   286  	// over-charging itself. So the check here is necessary.
   287  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   288  		return nil, gas, ErrInsufficientBalance
   289  	}
   290  	var snapshot = evm.StateDB.Snapshot()
   291  
   292  	// Invoke tracer hooks that signal entering/exiting a call frame
   293  	if evm.Config.Debug {
   294  		evm.Config.Tracer.CaptureEnter(CALLCODE, caller.Address(), addr, input, gas, value)
   295  		defer func(startGas uint64) {
   296  			evm.Config.Tracer.CaptureExit(ret, startGas-gas, err)
   297  		}(gas)
   298  	}
   299  
   300  	// It is allowed to call precompiles, even via delegatecall
   301  	if p, isPrecompile := evm.precompile(addr); isPrecompile {
   302  		info := &AdvancedPrecompileCall{
   303  			PrecompileAddress: addr,
   304  			ActingAsAddress:   caller.Address(),
   305  			Caller:            caller.Address(),
   306  			Value:             value,
   307  			ReadOnly:          false,
   308  			Evm:               evm,
   309  		}
   310  		ret, gas, err = RunPrecompiledContract(p, input, gas, info)
   311  	} else {
   312  		addrCopy := addr
   313  		// Initialise a new contract and set the code that is to be used by the EVM.
   314  		// The contract is a scoped environment for this execution context only.
   315  		contract := NewContract(caller, AccountRef(caller.Address()), value, gas)
   316  		contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy))
   317  		ret, err = evm.interpreter.Run(contract, input, false)
   318  		gas = contract.Gas
   319  	}
   320  	if err != nil {
   321  		evm.StateDB.RevertToSnapshot(snapshot)
   322  		if err != ErrExecutionReverted {
   323  			gas = 0
   324  		}
   325  	}
   326  	return ret, gas, err
   327  }
   328  
   329  // DelegateCall executes the contract associated with the addr with the given input
   330  // as parameters. It reverses the state in case of an execution error.
   331  //
   332  // DelegateCall differs from CallCode in the sense that it executes the given address'
   333  // code with the caller as context and the caller is set to the caller of the caller.
   334  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   335  	// Fail if we're trying to execute above the call depth limit
   336  	if evm.depth > int(params.CallCreateDepth) {
   337  		return nil, gas, ErrDepth
   338  	}
   339  	var snapshot = evm.StateDB.Snapshot()
   340  
   341  	// Invoke tracer hooks that signal entering/exiting a call frame
   342  	if evm.Config.Debug {
   343  		// NOTE: caller must, at all times be a contract. It should never happen
   344  		// that caller is something other than a Contract.
   345  		parent := caller.(*Contract)
   346  		// DELEGATECALL inherits value from parent call
   347  		evm.Config.Tracer.CaptureEnter(DELEGATECALL, caller.Address(), addr, input, gas, parent.value)
   348  		defer func(startGas uint64) {
   349  			evm.Config.Tracer.CaptureExit(ret, startGas-gas, err)
   350  		}(gas)
   351  	}
   352  
   353  	// It is allowed to call precompiles, even via delegatecall
   354  	if p, isPrecompile := evm.precompile(addr); isPrecompile {
   355  		caller := caller.(*Contract)
   356  		info := &AdvancedPrecompileCall{
   357  			PrecompileAddress: addr,
   358  			ActingAsAddress:   caller.Address(),
   359  			Caller:            caller.CallerAddress,
   360  			Value:             caller.Value(),
   361  			ReadOnly:          false,
   362  			Evm:               evm,
   363  		}
   364  		ret, gas, err = RunPrecompiledContract(p, input, gas, info)
   365  	} else {
   366  		addrCopy := addr
   367  		// Initialise a new contract and make initialise the delegate values
   368  		contract := NewContract(caller, AccountRef(caller.Address()), nil, gas).AsDelegate()
   369  		contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy))
   370  		ret, err = evm.interpreter.Run(contract, input, false)
   371  		gas = contract.Gas
   372  	}
   373  	if err != nil {
   374  		evm.StateDB.RevertToSnapshot(snapshot)
   375  		if err != ErrExecutionReverted {
   376  			gas = 0
   377  		}
   378  	}
   379  	return ret, gas, err
   380  }
   381  
   382  // StaticCall executes the contract associated with the addr with the given input
   383  // as parameters while disallowing any modifications to the state during the call.
   384  // Opcodes that attempt to perform such modifications will result in exceptions
   385  // instead of performing the modifications.
   386  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   387  	// Fail if we're trying to execute above the call depth limit
   388  	if evm.depth > int(params.CallCreateDepth) {
   389  		return nil, gas, ErrDepth
   390  	}
   391  	// We take a snapshot here. This is a bit counter-intuitive, and could probably be skipped.
   392  	// However, even a staticcall is considered a 'touch'. On mainnet, static calls were introduced
   393  	// after all empty accounts were deleted, so this is not required. However, if we omit this,
   394  	// then certain tests start failing; stRevertTest/RevertPrecompiledTouchExactOOG.json.
   395  	// We could change this, but for now it's left for legacy reasons
   396  	var snapshot = evm.StateDB.Snapshot()
   397  
   398  	// We do an AddBalance of zero here, just in order to trigger a touch.
   399  	// This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium,
   400  	// but is the correct thing to do and matters on other networks, in tests, and potential
   401  	// future scenarios
   402  	evm.StateDB.AddBalance(addr, big0)
   403  
   404  	// Invoke tracer hooks that signal entering/exiting a call frame
   405  	if evm.Config.Debug {
   406  		evm.Config.Tracer.CaptureEnter(STATICCALL, caller.Address(), addr, input, gas, nil)
   407  		defer func(startGas uint64) {
   408  			evm.Config.Tracer.CaptureExit(ret, startGas-gas, err)
   409  		}(gas)
   410  	}
   411  
   412  	if p, isPrecompile := evm.precompile(addr); isPrecompile {
   413  		info := &AdvancedPrecompileCall{
   414  			PrecompileAddress: addr,
   415  			ActingAsAddress:   addr,
   416  			Caller:            caller.Address(),
   417  			Value:             new(big.Int),
   418  			ReadOnly:          true,
   419  			Evm:               evm,
   420  		}
   421  		ret, gas, err = RunPrecompiledContract(p, input, gas, info)
   422  	} else {
   423  		// At this point, we use a copy of address. If we don't, the go compiler will
   424  		// leak the 'contract' to the outer scope, and make allocation for 'contract'
   425  		// even if the actual execution ends on RunPrecompiled above.
   426  		addrCopy := addr
   427  		// Initialise a new contract and set the code that is to be used by the EVM.
   428  		// The contract is a scoped environment for this execution context only.
   429  		contract := NewContract(caller, AccountRef(addrCopy), new(big.Int), gas)
   430  		contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy))
   431  		// When an error was returned by the EVM or when setting the creation code
   432  		// above we revert to the snapshot and consume any gas remaining. Additionally
   433  		// when we're in Homestead this also counts for code storage gas errors.
   434  		ret, err = evm.interpreter.Run(contract, input, true)
   435  		gas = contract.Gas
   436  	}
   437  	if err != nil {
   438  		evm.StateDB.RevertToSnapshot(snapshot)
   439  		if err != ErrExecutionReverted {
   440  			gas = 0
   441  		}
   442  	}
   443  	return ret, gas, err
   444  }
   445  
   446  type codeAndHash struct {
   447  	code []byte
   448  	hash common.Hash
   449  }
   450  
   451  func (c *codeAndHash) Hash() common.Hash {
   452  	if c.hash == (common.Hash{}) {
   453  		c.hash = crypto.Keccak256Hash(c.code)
   454  	}
   455  	return c.hash
   456  }
   457  
   458  // create creates a new contract using code as deployment code.
   459  func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address, typ OpCode) ([]byte, common.Address, uint64, error) {
   460  	// Depth check execution. Fail if we're trying to execute above the
   461  	// limit.
   462  	if evm.depth > int(params.CallCreateDepth) {
   463  		return nil, common.Address{}, gas, ErrDepth
   464  	}
   465  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   466  		return nil, common.Address{}, gas, ErrInsufficientBalance
   467  	}
   468  	nonce := evm.StateDB.GetNonce(caller.Address())
   469  	if nonce+1 < nonce {
   470  		return nil, common.Address{}, gas, ErrNonceUintOverflow
   471  	}
   472  	evm.StateDB.SetNonce(caller.Address(), nonce+1)
   473  	// We add this to the access list _before_ taking a snapshot. Even if the creation fails,
   474  	// the access-list change should not be rolled back
   475  	if evm.chainRules.IsBerlin {
   476  		evm.StateDB.AddAddressToAccessList(address)
   477  	}
   478  	// Ensure there's no existing contract already at the designated address
   479  	contractHash := evm.StateDB.GetCodeHash(address)
   480  	if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   481  		return nil, common.Address{}, 0, ErrContractAddressCollision
   482  	}
   483  	// Create a new account on the state
   484  	snapshot := evm.StateDB.Snapshot()
   485  	evm.StateDB.CreateAccount(address)
   486  	if evm.chainRules.IsEIP158 {
   487  		evm.StateDB.SetNonce(address, 1)
   488  	}
   489  	evm.Context.Transfer(evm.StateDB, caller.Address(), address, value)
   490  
   491  	// Initialise a new contract and set the code that is to be used by the EVM.
   492  	// The contract is a scoped environment for this execution context only.
   493  	contract := NewContract(caller, AccountRef(address), value, gas)
   494  	contract.SetCodeOptionalHash(&address, codeAndHash)
   495  
   496  	if evm.Config.Debug {
   497  		if evm.depth == 0 {
   498  			evm.Config.Tracer.CaptureStart(evm, caller.Address(), address, true, codeAndHash.code, gas, value)
   499  		} else {
   500  			evm.Config.Tracer.CaptureEnter(typ, caller.Address(), address, codeAndHash.code, gas, value)
   501  		}
   502  	}
   503  
   504  	ret, err := evm.interpreter.Run(contract, nil, false)
   505  
   506  	// Check whether the max code size has been exceeded, assign err if the case.
   507  	if err == nil && evm.chainRules.IsEIP158 && len(ret) > params.MaxCodeSize {
   508  		err = ErrMaxCodeSizeExceeded
   509  	}
   510  
   511  	// Reject code starting with 0xEF if EIP-3541 is enabled.
   512  	if err == nil && len(ret) >= 1 && ret[0] == 0xEF && evm.chainRules.IsLondon {
   513  		err = ErrInvalidCode
   514  	}
   515  
   516  	// if the contract creation ran successfully and no errors were returned
   517  	// calculate the gas required to store the code. If the code could not
   518  	// be stored due to not enough gas set an error and let it be handled
   519  	// by the error checking condition below.
   520  	if err == nil {
   521  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   522  		if contract.UseGas(createDataGas) {
   523  			evm.StateDB.SetCode(address, ret)
   524  		} else {
   525  			err = ErrCodeStoreOutOfGas
   526  		}
   527  	}
   528  
   529  	// When an error was returned by the EVM or when setting the creation code
   530  	// above we revert to the snapshot and consume any gas remaining. Additionally
   531  	// when we're in homestead this also counts for code storage gas errors.
   532  	if err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas) {
   533  		evm.StateDB.RevertToSnapshot(snapshot)
   534  		if err != ErrExecutionReverted {
   535  			contract.UseGas(contract.Gas)
   536  		}
   537  	}
   538  
   539  	if evm.Config.Debug {
   540  		if evm.depth == 0 {
   541  			evm.Config.Tracer.CaptureEnd(ret, gas-contract.Gas, err)
   542  		} else {
   543  			evm.Config.Tracer.CaptureExit(ret, gas-contract.Gas, err)
   544  		}
   545  	}
   546  	return ret, address, contract.Gas, err
   547  }
   548  
   549  // Create creates a new contract using code as deployment code.
   550  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   551  	contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
   552  	return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr, CREATE)
   553  }
   554  
   555  // Create2 creates a new contract using code as deployment code.
   556  //
   557  // The different between Create2 with Create is Create2 uses keccak256(0xff ++ msg.sender ++ salt ++ keccak256(init_code))[12:]
   558  // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
   559  func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   560  	codeAndHash := &codeAndHash{code: code}
   561  	contractAddr = crypto.CreateAddress2(caller.Address(), salt.Bytes32(), codeAndHash.Hash().Bytes())
   562  	return evm.create(caller, codeAndHash, gas, endowment, contractAddr, CREATE2)
   563  }
   564  
   565  // ChainConfig returns the environment's chain configuration
   566  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }