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