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