github.com/oskarth/go-ethereum@v1.6.8-0.20191013093314-dac24a9d3494/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  // Interpreter returns the current interpreter
   173  func (evm *EVM) Interpreter() Interpreter {
   174  	return evm.interpreter
   175  }
   176  
   177  // Call executes the contract associated with the addr with the given input as
   178  // parameters. It also handles any necessary value transfer required and takes
   179  // the necessary steps to create accounts and reverses the state in case of an
   180  // execution error or failed value transfer.
   181  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   182  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   183  		return nil, gas, nil
   184  	}
   185  
   186  	// Fail if we're trying to execute above the call depth limit
   187  	if evm.depth > int(params.CallCreateDepth) {
   188  		return nil, gas, ErrDepth
   189  	}
   190  	// Fail if we're trying to transfer more than the available balance
   191  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   192  		return nil, gas, ErrInsufficientBalance
   193  	}
   194  
   195  	var (
   196  		to       = AccountRef(addr)
   197  		snapshot = evm.StateDB.Snapshot()
   198  	)
   199  	if !evm.StateDB.Exist(addr) {
   200  		precompiles := PrecompiledContractsHomestead
   201  		if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
   202  			precompiles = PrecompiledContractsByzantium
   203  		}
   204  		if precompiles[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 {
   205  			// Calling a non existing account, don't do anything, but ping the tracer
   206  			if evm.vmConfig.Debug && evm.depth == 0 {
   207  				evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   208  				evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
   209  			}
   210  			return nil, gas, nil
   211  		}
   212  		evm.StateDB.CreateAccount(addr)
   213  	}
   214  	evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   215  	// Initialise a new contract and set the code that is to be used by the EVM.
   216  	// The contract is a scoped environment for this execution context only.
   217  	contract := NewContract(caller, to, value, gas)
   218  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   219  
   220  	// Even if the account has no code, we need to continue because it might be a precompile
   221  	start := time.Now()
   222  
   223  	// Capture the tracer start/end events in debug mode
   224  	if evm.vmConfig.Debug && evm.depth == 0 {
   225  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   226  
   227  		defer func() { // Lazy evaluation of the parameters
   228  			evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   229  		}()
   230  	}
   231  	ret, err = run(evm, contract, input, false)
   232  
   233  	// When an error was returned by the EVM or when setting the creation code
   234  	// above we revert to the snapshot and consume any gas remaining. Additionally
   235  	// when we're in homestead this also counts for code storage gas errors.
   236  	if err != nil {
   237  		evm.StateDB.RevertToSnapshot(snapshot)
   238  		if err != errExecutionReverted {
   239  			contract.UseGas(contract.Gas)
   240  		}
   241  	}
   242  	return ret, contract.Gas, err
   243  }
   244  
   245  // CallCode executes the contract associated with the addr with the given input
   246  // as parameters. It also handles any necessary value transfer required and takes
   247  // the necessary steps to create accounts and reverses the state in case of an
   248  // execution error or failed value transfer.
   249  //
   250  // CallCode differs from Call in the sense that it executes the given address'
   251  // code with the caller as context.
   252  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   253  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   254  		return nil, gas, nil
   255  	}
   256  
   257  	// Fail if we're trying to execute above the call depth limit
   258  	if evm.depth > int(params.CallCreateDepth) {
   259  		return nil, gas, ErrDepth
   260  	}
   261  	// Fail if we're trying to transfer more than the available balance
   262  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   263  		return nil, gas, ErrInsufficientBalance
   264  	}
   265  
   266  	var (
   267  		snapshot = evm.StateDB.Snapshot()
   268  		to       = AccountRef(caller.Address())
   269  	)
   270  	// initialise a new contract and set the code that is to be used by the
   271  	// EVM. The contract is a scoped environment for this execution context
   272  	// only.
   273  	contract := NewContract(caller, to, value, gas)
   274  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   275  
   276  	ret, err = run(evm, contract, input, false)
   277  	if err != nil {
   278  		evm.StateDB.RevertToSnapshot(snapshot)
   279  		if err != errExecutionReverted {
   280  			contract.UseGas(contract.Gas)
   281  		}
   282  	}
   283  	return ret, contract.Gas, err
   284  }
   285  
   286  // DelegateCall executes the contract associated with the addr with the given input
   287  // as parameters. It reverses the state in case of an execution error.
   288  //
   289  // DelegateCall differs from CallCode in the sense that it executes the given address'
   290  // code with the caller as context and the caller is set to the caller of the caller.
   291  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   292  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   293  		return nil, gas, nil
   294  	}
   295  	// Fail if we're trying to execute above the call depth limit
   296  	if evm.depth > int(params.CallCreateDepth) {
   297  		return nil, gas, ErrDepth
   298  	}
   299  
   300  	var (
   301  		snapshot = evm.StateDB.Snapshot()
   302  		to       = AccountRef(caller.Address())
   303  	)
   304  
   305  	// Initialise a new contract and make initialise the delegate values
   306  	contract := NewContract(caller, to, nil, gas).AsDelegate()
   307  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   308  
   309  	ret, err = run(evm, contract, input, false)
   310  	if err != nil {
   311  		evm.StateDB.RevertToSnapshot(snapshot)
   312  		if err != errExecutionReverted {
   313  			contract.UseGas(contract.Gas)
   314  		}
   315  	}
   316  	return ret, contract.Gas, err
   317  }
   318  
   319  // StaticCall executes the contract associated with the addr with the given input
   320  // as parameters while disallowing any modifications to the state during the call.
   321  // Opcodes that attempt to perform such modifications will result in exceptions
   322  // instead of performing the modifications.
   323  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   324  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   325  		return nil, gas, nil
   326  	}
   327  	// Fail if we're trying to execute above the call depth limit
   328  	if evm.depth > int(params.CallCreateDepth) {
   329  		return nil, gas, ErrDepth
   330  	}
   331  
   332  	var (
   333  		to       = AccountRef(addr)
   334  		snapshot = evm.StateDB.Snapshot()
   335  	)
   336  	// Initialise a new contract and set the code that is to be used by the
   337  	// EVM. The contract is a scoped environment for this execution context
   338  	// only.
   339  	contract := NewContract(caller, to, new(big.Int), gas)
   340  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   341  
   342  	// When an error was returned by the EVM or when setting the creation code
   343  	// above we revert to the snapshot and consume any gas remaining. Additionally
   344  	// when we're in Homestead this also counts for code storage gas errors.
   345  	ret, err = run(evm, contract, input, true)
   346  	if err != nil {
   347  		evm.StateDB.RevertToSnapshot(snapshot)
   348  		if err != errExecutionReverted {
   349  			contract.UseGas(contract.Gas)
   350  		}
   351  	}
   352  	return ret, contract.Gas, err
   353  }
   354  
   355  type codeAndHash struct {
   356  	code []byte
   357  	hash common.Hash
   358  }
   359  
   360  func (c *codeAndHash) Hash() common.Hash {
   361  	if c.hash == (common.Hash{}) {
   362  		c.hash = crypto.Keccak256Hash(c.code)
   363  	}
   364  	return c.hash
   365  }
   366  
   367  // create creates a new contract using code as deployment code.
   368  func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
   369  	// Depth check execution. Fail if we're trying to execute above the
   370  	// limit.
   371  	if evm.depth > int(params.CallCreateDepth) {
   372  		return nil, common.Address{}, gas, ErrDepth
   373  	}
   374  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   375  		return nil, common.Address{}, gas, ErrInsufficientBalance
   376  	}
   377  	nonce := evm.StateDB.GetNonce(caller.Address())
   378  	evm.StateDB.SetNonce(caller.Address(), nonce+1)
   379  
   380  	// Ensure there's no existing contract already at the designated address
   381  	contractHash := evm.StateDB.GetCodeHash(address)
   382  	if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   383  		return nil, common.Address{}, 0, ErrContractAddressCollision
   384  	}
   385  	// Create a new account on the state
   386  	snapshot := evm.StateDB.Snapshot()
   387  	evm.StateDB.CreateAccount(address)
   388  	if evm.ChainConfig().IsEIP158(evm.BlockNumber) {
   389  		evm.StateDB.SetNonce(address, 1)
   390  	}
   391  	evm.Transfer(evm.StateDB, caller.Address(), address, value)
   392  
   393  	// initialise a new contract and set the code that is to be used by the
   394  	// EVM. The contract is a scoped environment for this execution context
   395  	// only.
   396  	contract := NewContract(caller, AccountRef(address), value, gas)
   397  	contract.SetCodeOptionalHash(&address, codeAndHash)
   398  
   399  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   400  		return nil, address, gas, nil
   401  	}
   402  
   403  	if evm.vmConfig.Debug && evm.depth == 0 {
   404  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value)
   405  	}
   406  	start := time.Now()
   407  
   408  	ret, err := run(evm, contract, nil, false)
   409  
   410  	// check whether the max code size has been exceeded
   411  	maxCodeSizeExceeded := evm.ChainConfig().IsEIP158(evm.BlockNumber) && len(ret) > params.MaxCodeSize
   412  	// if the contract creation ran successfully and no errors were returned
   413  	// calculate the gas required to store the code. If the code could not
   414  	// be stored due to not enough gas set an error and let it be handled
   415  	// by the error checking condition below.
   416  	if err == nil && !maxCodeSizeExceeded {
   417  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   418  		if contract.UseGas(createDataGas) {
   419  			evm.StateDB.SetCode(address, ret)
   420  		} else {
   421  			err = ErrCodeStoreOutOfGas
   422  		}
   423  	}
   424  
   425  	// When an error was returned by the EVM or when setting the creation code
   426  	// above we revert to the snapshot and consume any gas remaining. Additionally
   427  	// when we're in homestead this also counts for code storage gas errors.
   428  	if maxCodeSizeExceeded || (err != nil && (evm.ChainConfig().IsHomestead(evm.BlockNumber) || err != ErrCodeStoreOutOfGas)) {
   429  		evm.StateDB.RevertToSnapshot(snapshot)
   430  		if err != errExecutionReverted {
   431  			contract.UseGas(contract.Gas)
   432  		}
   433  	}
   434  	// Assign err if contract code size exceeds the max while the err is still empty.
   435  	if maxCodeSizeExceeded && err == nil {
   436  		err = errMaxCodeSizeExceeded
   437  	}
   438  	if evm.vmConfig.Debug && evm.depth == 0 {
   439  		evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   440  	}
   441  	return ret, address, contract.Gas, err
   442  
   443  }
   444  
   445  // Create creates a new contract using code as deployment code.
   446  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   447  	contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
   448  	return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
   449  }
   450  
   451  // Create2 creates a new contract using code as deployment code.
   452  //
   453  // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
   454  // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
   455  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) {
   456  	codeAndHash := &codeAndHash{code: code}
   457  	contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), codeAndHash.Hash().Bytes())
   458  	return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
   459  }
   460  
   461  // ChainConfig returns the environment's chain configuration
   462  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }