github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/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  	"time"
    24  
    25  	"github.com/zhiqiangxu/go-ethereum/common"
    26  	"github.com/zhiqiangxu/go-ethereum/crypto"
    27  	"github.com/zhiqiangxu/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  // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
    45  func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, error) {
    46  	if contract.CodeAddr != nil {
    47  		precompiles := PrecompiledContractsHomestead
    48  		if evm.chainRules.IsByzantium {
    49  			precompiles = PrecompiledContractsByzantium
    50  		}
    51  		if evm.chainRules.IsIstanbul {
    52  			precompiles = PrecompiledContractsIstanbul
    53  		}
    54  		if evm.chainRules.IsYoloV1 {
    55  			precompiles = PrecompiledContractsYoloV1
    56  		}
    57  		if p := precompiles[*contract.CodeAddr]; p != nil {
    58  			return RunPrecompiledContract(p, input, contract)
    59  		}
    60  	}
    61  	for _, interpreter := range evm.interpreters {
    62  		if interpreter.CanRun(contract.Code) {
    63  			if evm.interpreter != interpreter {
    64  				// Ensure that the interpreter pointer is set back
    65  				// to its current value upon return.
    66  				defer func(i Interpreter) {
    67  					evm.interpreter = i
    68  				}(evm.interpreter)
    69  				evm.interpreter = interpreter
    70  			}
    71  			return interpreter.Run(contract, input, readOnly)
    72  		}
    73  	}
    74  	return nil, errors.New("no compatible interpreter")
    75  }
    76  
    77  // Context provides the EVM with auxiliary information. Once provided
    78  // it shouldn't be modified.
    79  type Context struct {
    80  	// CanTransfer returns whether the account contains
    81  	// sufficient ether to transfer the value
    82  	CanTransfer CanTransferFunc
    83  	// Transfer transfers ether from one account to the other
    84  	Transfer TransferFunc
    85  	// GetHash returns the hash corresponding to n
    86  	GetHash GetHashFunc
    87  
    88  	// Message information
    89  	Origin   common.Address // Provides information for ORIGIN
    90  	GasPrice *big.Int       // Provides information for GASPRICE
    91  
    92  	// Block information
    93  	Coinbase    common.Address // Provides information for COINBASE
    94  	GasLimit    uint64         // Provides information for GASLIMIT
    95  	BlockNumber *big.Int       // Provides information for NUMBER
    96  	Time        *big.Int       // Provides information for TIME
    97  	Difficulty  *big.Int       // Provides information for DIFFICULTY
    98  }
    99  
   100  // EVM is the Ethereum Virtual Machine base object and provides
   101  // the necessary tools to run a contract on the given state with
   102  // the provided context. It should be noted that any error
   103  // generated through any of the calls should be considered a
   104  // revert-state-and-consume-all-gas operation, no checks on
   105  // specific errors should ever be performed. The interpreter makes
   106  // sure that any errors generated are to be considered faulty code.
   107  //
   108  // The EVM should never be reused and is not thread safe.
   109  type EVM struct {
   110  	// Context provides auxiliary blockchain related information
   111  	Context
   112  	// StateDB gives access to the underlying state
   113  	StateDB StateDB
   114  	// Depth is the current call stack
   115  	depth int
   116  
   117  	// chainConfig contains information about the current chain
   118  	chainConfig *params.ChainConfig
   119  	// chain rules contains the chain rules for the current epoch
   120  	chainRules params.Rules
   121  	// virtual machine configuration options used to initialise the
   122  	// evm.
   123  	vmConfig Config
   124  	// global (to this context) ethereum virtual machine
   125  	// used throughout the execution of the tx.
   126  	interpreters []Interpreter
   127  	interpreter  Interpreter
   128  	// abort is used to abort the EVM calling operations
   129  	// NOTE: must be set atomically
   130  	abort int32
   131  	// callGasTemp holds the gas available for the current call. This is needed because the
   132  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   133  	// applied in opCall*.
   134  	callGasTemp uint64
   135  }
   136  
   137  // NewEVM returns a new EVM. The returned EVM is not thread safe and should
   138  // only ever be used *once*.
   139  func NewEVM(ctx Context, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
   140  	evm := &EVM{
   141  		Context:      ctx,
   142  		StateDB:      statedb,
   143  		vmConfig:     vmConfig,
   144  		chainConfig:  chainConfig,
   145  		chainRules:   chainConfig.Rules(ctx.BlockNumber),
   146  		interpreters: make([]Interpreter, 0, 1),
   147  	}
   148  
   149  	if chainConfig.IsEWASM(ctx.BlockNumber) {
   150  		// to be implemented by EVM-C and Wagon PRs.
   151  		// if vmConfig.EWASMInterpreter != "" {
   152  		//  extIntOpts := strings.Split(vmConfig.EWASMInterpreter, ":")
   153  		//  path := extIntOpts[0]
   154  		//  options := []string{}
   155  		//  if len(extIntOpts) > 1 {
   156  		//    options = extIntOpts[1..]
   157  		//  }
   158  		//  evm.interpreters = append(evm.interpreters, NewEVMVCInterpreter(evm, vmConfig, options))
   159  		// } else {
   160  		// 	evm.interpreters = append(evm.interpreters, NewEWASMInterpreter(evm, vmConfig))
   161  		// }
   162  		panic("No supported ewasm interpreter yet.")
   163  	}
   164  
   165  	// vmConfig.EVMInterpreter will be used by EVM-C, it won't be checked here
   166  	// as we always want to have the built-in EVM as the failover option.
   167  	evm.interpreters = append(evm.interpreters, NewEVMInterpreter(evm, vmConfig))
   168  	evm.interpreter = evm.interpreters[0]
   169  
   170  	return evm
   171  }
   172  
   173  // Cancel cancels any running EVM operation. This may be called concurrently and
   174  // it's safe to be called multiple times.
   175  func (evm *EVM) Cancel() {
   176  	atomic.StoreInt32(&evm.abort, 1)
   177  }
   178  
   179  // Cancelled returns true if Cancel has been called
   180  func (evm *EVM) Cancelled() bool {
   181  	return atomic.LoadInt32(&evm.abort) == 1
   182  }
   183  
   184  // Interpreter returns the current interpreter
   185  func (evm *EVM) Interpreter() Interpreter {
   186  	return evm.interpreter
   187  }
   188  
   189  // Call executes the contract associated with the addr with the given input as
   190  // parameters. It also handles any necessary value transfer required and takes
   191  // the necessary steps to create accounts and reverses the state in case of an
   192  // execution error or failed value transfer.
   193  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   194  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   195  		return nil, gas, nil
   196  	}
   197  	// Fail if we're trying to execute above the call depth limit
   198  	if evm.depth > int(params.CallCreateDepth) {
   199  		return nil, gas, ErrDepth
   200  	}
   201  	// Fail if we're trying to transfer more than the available balance
   202  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   203  		return nil, gas, ErrInsufficientBalance
   204  	}
   205  	var (
   206  		to       = AccountRef(addr)
   207  		snapshot = evm.StateDB.Snapshot()
   208  	)
   209  	if !evm.StateDB.Exist(addr) {
   210  		precompiles := PrecompiledContractsHomestead
   211  		if evm.chainRules.IsByzantium {
   212  			precompiles = PrecompiledContractsByzantium
   213  		}
   214  		if evm.chainRules.IsIstanbul {
   215  			precompiles = PrecompiledContractsIstanbul
   216  		}
   217  		if precompiles[addr] == nil && evm.chainRules.IsEIP158 && value.Sign() == 0 {
   218  			// Calling a non existing account, don't do anything, but ping the tracer
   219  			if evm.vmConfig.Debug && evm.depth == 0 {
   220  				evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   221  				evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
   222  			}
   223  			return nil, gas, nil
   224  		}
   225  		evm.StateDB.CreateAccount(addr)
   226  	}
   227  	evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   228  	// Initialise a new contract and set the code that is to be used by the EVM.
   229  	// The contract is a scoped environment for this execution context only.
   230  	contract := NewContract(caller, to, value, gas)
   231  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   232  
   233  	// Even if the account has no code, we need to continue because it might be a precompile
   234  	start := time.Now()
   235  
   236  	// Capture the tracer start/end events in debug mode
   237  	if evm.vmConfig.Debug && evm.depth == 0 {
   238  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   239  
   240  		defer func() { // Lazy evaluation of the parameters
   241  			evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   242  		}()
   243  	}
   244  	ret, err = run(evm, contract, input, false)
   245  
   246  	// When an error was returned by the EVM or when setting the creation code
   247  	// above we revert to the snapshot and consume any gas remaining. Additionally
   248  	// when we're in homestead this also counts for code storage gas errors.
   249  	if err != nil {
   250  		evm.StateDB.RevertToSnapshot(snapshot)
   251  		if err != ErrExecutionReverted {
   252  			contract.UseGas(contract.Gas)
   253  		}
   254  	}
   255  	return ret, contract.Gas, err
   256  }
   257  
   258  // CallCode executes the contract associated with the addr with the given input
   259  // as parameters. It also handles any necessary value transfer required and takes
   260  // the necessary steps to create accounts and reverses the state in case of an
   261  // execution error or failed value transfer.
   262  //
   263  // CallCode differs from Call in the sense that it executes the given address'
   264  // code with the caller as context.
   265  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   266  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   267  		return nil, gas, nil
   268  	}
   269  	// Fail if we're trying to execute above the call depth limit
   270  	if evm.depth > int(params.CallCreateDepth) {
   271  		return nil, gas, ErrDepth
   272  	}
   273  	// Fail if we're trying to transfer more than the available balance
   274  	// Note although it's noop to transfer X ether to caller itself. But
   275  	// if caller doesn't have enough balance, it would be an error to allow
   276  	// over-charging itself. So the check here is necessary.
   277  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   278  		return nil, gas, ErrInsufficientBalance
   279  	}
   280  	var (
   281  		snapshot = evm.StateDB.Snapshot()
   282  		to       = AccountRef(caller.Address())
   283  	)
   284  	// Initialise a new contract and set the code that is to be used by the EVM.
   285  	// The contract is a scoped environment for this execution context only.
   286  	contract := NewContract(caller, to, value, gas)
   287  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   288  
   289  	ret, err = run(evm, contract, input, false)
   290  	if err != nil {
   291  		evm.StateDB.RevertToSnapshot(snapshot)
   292  		if err != ErrExecutionReverted {
   293  			contract.UseGas(contract.Gas)
   294  		}
   295  	}
   296  	return ret, contract.Gas, err
   297  }
   298  
   299  // DelegateCall executes the contract associated with the addr with the given input
   300  // as parameters. It reverses the state in case of an execution error.
   301  //
   302  // DelegateCall differs from CallCode in the sense that it executes the given address'
   303  // code with the caller as context and the caller is set to the caller of the caller.
   304  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   305  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   306  		return nil, gas, nil
   307  	}
   308  	// Fail if we're trying to execute above the call depth limit
   309  	if evm.depth > int(params.CallCreateDepth) {
   310  		return nil, gas, ErrDepth
   311  	}
   312  	var (
   313  		snapshot = evm.StateDB.Snapshot()
   314  		to       = AccountRef(caller.Address())
   315  	)
   316  	// Initialise a new contract and make initialise the delegate values
   317  	contract := NewContract(caller, to, nil, gas).AsDelegate()
   318  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   319  
   320  	ret, err = run(evm, contract, input, false)
   321  	if err != nil {
   322  		evm.StateDB.RevertToSnapshot(snapshot)
   323  		if err != ErrExecutionReverted {
   324  			contract.UseGas(contract.Gas)
   325  		}
   326  	}
   327  	return ret, contract.Gas, err
   328  }
   329  
   330  // StaticCall executes the contract associated with the addr with the given input
   331  // as parameters while disallowing any modifications to the state during the call.
   332  // Opcodes that attempt to perform such modifications will result in exceptions
   333  // instead of performing the modifications.
   334  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   335  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   336  		return nil, gas, nil
   337  	}
   338  	// Fail if we're trying to execute above the call depth limit
   339  	if evm.depth > int(params.CallCreateDepth) {
   340  		return nil, gas, ErrDepth
   341  	}
   342  	var (
   343  		to       = AccountRef(addr)
   344  		snapshot = evm.StateDB.Snapshot()
   345  	)
   346  	// Initialise a new contract and set the code that is to be used by the EVM.
   347  	// The contract is a scoped environment for this execution context only.
   348  	contract := NewContract(caller, to, new(big.Int), gas)
   349  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   350  
   351  	// We do an AddBalance of zero here, just in order to trigger a touch.
   352  	// This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium,
   353  	// but is the correct thing to do and matters on other networks, in tests, and potential
   354  	// future scenarios
   355  	evm.StateDB.AddBalance(addr, bigZero)
   356  
   357  	// When an error was returned by the EVM or when setting the creation code
   358  	// above we revert to the snapshot and consume any gas remaining. Additionally
   359  	// when we're in Homestead this also counts for code storage gas errors.
   360  	ret, err = run(evm, contract, input, true)
   361  	if err != nil {
   362  		evm.StateDB.RevertToSnapshot(snapshot)
   363  		if err != ErrExecutionReverted {
   364  			contract.UseGas(contract.Gas)
   365  		}
   366  	}
   367  	return ret, contract.Gas, err
   368  }
   369  
   370  type codeAndHash struct {
   371  	code []byte
   372  	hash common.Hash
   373  }
   374  
   375  func (c *codeAndHash) Hash() common.Hash {
   376  	if c.hash == (common.Hash{}) {
   377  		c.hash = crypto.Keccak256Hash(c.code)
   378  	}
   379  	return c.hash
   380  }
   381  
   382  // create creates a new contract using code as deployment code.
   383  func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
   384  	// Depth check execution. Fail if we're trying to execute above the
   385  	// limit.
   386  	if evm.depth > int(params.CallCreateDepth) {
   387  		return nil, common.Address{}, gas, ErrDepth
   388  	}
   389  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   390  		return nil, common.Address{}, gas, ErrInsufficientBalance
   391  	}
   392  	nonce := evm.StateDB.GetNonce(caller.Address())
   393  	evm.StateDB.SetNonce(caller.Address(), nonce+1)
   394  
   395  	// Ensure there's no existing contract already at the designated address
   396  	contractHash := evm.StateDB.GetCodeHash(address)
   397  	if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   398  		return nil, common.Address{}, 0, ErrContractAddressCollision
   399  	}
   400  	// Create a new account on the state
   401  	snapshot := evm.StateDB.Snapshot()
   402  	evm.StateDB.CreateAccount(address)
   403  	if evm.chainRules.IsEIP158 {
   404  		evm.StateDB.SetNonce(address, 1)
   405  	}
   406  	evm.Transfer(evm.StateDB, caller.Address(), address, value)
   407  
   408  	// Initialise a new contract and set the code that is to be used by the EVM.
   409  	// The contract is a scoped environment for this execution context only.
   410  	contract := NewContract(caller, AccountRef(address), value, gas)
   411  	contract.SetCodeOptionalHash(&address, codeAndHash)
   412  
   413  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   414  		return nil, address, gas, nil
   415  	}
   416  
   417  	if evm.vmConfig.Debug && evm.depth == 0 {
   418  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value)
   419  	}
   420  	start := time.Now()
   421  
   422  	ret, err := run(evm, contract, nil, false)
   423  
   424  	// check whether the max code size has been exceeded
   425  	maxCodeSizeExceeded := evm.chainRules.IsEIP158 && len(ret) > params.MaxCodeSize
   426  	// if the contract creation ran successfully and no errors were returned
   427  	// calculate the gas required to store the code. If the code could not
   428  	// be stored due to not enough gas set an error and let it be handled
   429  	// by the error checking condition below.
   430  	if err == nil && !maxCodeSizeExceeded {
   431  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   432  		if contract.UseGas(createDataGas) {
   433  			evm.StateDB.SetCode(address, ret)
   434  		} else {
   435  			err = ErrCodeStoreOutOfGas
   436  		}
   437  	}
   438  
   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  	if maxCodeSizeExceeded || (err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas)) {
   443  		evm.StateDB.RevertToSnapshot(snapshot)
   444  		if err != ErrExecutionReverted {
   445  			contract.UseGas(contract.Gas)
   446  		}
   447  	}
   448  	// Assign err if contract code size exceeds the max while the err is still empty.
   449  	if maxCodeSizeExceeded && err == nil {
   450  		err = ErrMaxCodeSizeExceeded
   451  	}
   452  	if evm.vmConfig.Debug && evm.depth == 0 {
   453  		evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   454  	}
   455  	return ret, address, contract.Gas, err
   456  
   457  }
   458  
   459  // Create creates a new contract using code as deployment code.
   460  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   461  	contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
   462  	return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
   463  }
   464  
   465  // Create2 creates a new contract using code as deployment code.
   466  //
   467  // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
   468  // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
   469  func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   470  	codeAndHash := &codeAndHash{code: code}
   471  	contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), codeAndHash.Hash().Bytes())
   472  	return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
   473  }
   474  
   475  // ChainConfig returns the environment's chain configuration
   476  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }