github.com/cranelv/ethereum_mpc@v0.0.0-20191031014521-23aeb1415092/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  	"github.com/ethereum/go-ethereum/log"
    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 func(StateDB, common.Address, *big.Int) bool
    36  	TransferFunc    func(StateDB, common.Address, common.Address, *big.Int)
    37  	// GetHashFunc returns the nth block hash in the blockchain
    38  	// and is used by the BLOCKHASH EVM op code.
    39  	GetHashFunc func(uint64) common.Hash
    40  )
    41  
    42  // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
    43  func run(evm *EVM, contract *Contract, input []byte) ([]byte, error) {
    44  	if contract.CodeAddr != nil {
    45  		precompiles := PrecompiledContractsHomestead
    46  		if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
    47  			precompiles = PrecompiledContractsByzantium
    48  		}
    49  		if p := precompiles[*contract.CodeAddr]; p != nil {
    50  			return RunPrecompiledContract(p, input, contract,evm)
    51  		}
    52  	}
    53  	return evm.interpreter.Run(contract, input)
    54  }
    55  
    56  // Context provides the EVM with auxiliary information. Once provided
    57  // it shouldn't be modified.
    58  type Context struct {
    59  	// CanTransfer returns whether the account contains
    60  	// sufficient ether to transfer the value
    61  	CanTransfer CanTransferFunc
    62  	// Transfer transfers ether from one account to the other
    63  	Transfer TransferFunc
    64  	// GetHash returns the hash corresponding to n
    65  	GetHash GetHashFunc
    66  
    67  	// Message information
    68  	Origin   common.Address // Provides information for ORIGIN
    69  	GasPrice *big.Int       // Provides information for GASPRICE
    70  
    71  	// Block information
    72  	Coinbase    common.Address // Provides information for COINBASE
    73  	GasLimit    uint64         // Provides information for GASLIMIT
    74  	BlockNumber *big.Int       // Provides information for NUMBER
    75  	Time        *big.Int       // Provides information for TIME
    76  	Difficulty  *big.Int       // Provides information for DIFFICULTY
    77  }
    78  
    79  // EVM is the Ethereum Virtual Machine base object and provides
    80  // the necessary tools to run a contract on the given state with
    81  // the provided context. It should be noted that any error
    82  // generated through any of the calls should be considered a
    83  // revert-state-and-consume-all-gas operation, no checks on
    84  // specific errors should ever be performed. The interpreter makes
    85  // sure that any errors generated are to be considered faulty code.
    86  //
    87  // The EVM should never be reused and is not thread safe.
    88  type EVM struct {
    89  	// Context provides auxiliary blockchain related information
    90  	Context
    91  	// StateDB gives access to the underlying state
    92  	StateDB StateDB
    93  	// Depth is the current call stack
    94  	depth int
    95  
    96  	// chainConfig contains information about the current chain
    97  	chainConfig *params.ChainConfig
    98  	// chain rules contains the chain rules for the current epoch
    99  	chainRules params.Rules
   100  	// virtual machine configuration options used to initialise the
   101  	// evm.
   102  	vmConfig Config
   103  	// global (to this context) ethereum virtual machine
   104  	// used throughout the execution of the tx.
   105  	interpreter *Interpreter
   106  	// abort is used to abort the EVM calling operations
   107  	// NOTE: must be set atomically
   108  	abort int32
   109  	// callGasTemp holds the gas available for the current call. This is needed because the
   110  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   111  	// applied in opCall*.
   112  	callGasTemp uint64
   113  }
   114  
   115  // NewEVM returns a new EVM. The returned EVM is not thread safe and should
   116  // only ever be used *once*.
   117  func NewEVM(ctx Context, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
   118  	evm := &EVM{
   119  		Context:     ctx,
   120  		StateDB:     statedb,
   121  		vmConfig:    vmConfig,
   122  		chainConfig: chainConfig,
   123  		chainRules:  chainConfig.Rules(ctx.BlockNumber),
   124  	}
   125  
   126  	evm.interpreter = NewInterpreter(evm, vmConfig)
   127  	return evm
   128  }
   129  
   130  // Cancel cancels any running EVM operation. This may be called concurrently and
   131  // it's safe to be called multiple times.
   132  func (evm *EVM) Cancel() {
   133  	atomic.StoreInt32(&evm.abort, 1)
   134  }
   135  
   136  // Call executes the contract associated with the addr with the given input as
   137  // parameters. It also handles any necessary value transfer required and takes
   138  // the necessary steps to create accounts and reverses the state in case of an
   139  // execution error or failed value transfer.
   140  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   141  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   142  		return nil, gas, nil
   143  	}
   144  
   145  	// Fail if we're trying to execute above the call depth limit
   146  	if evm.depth > int(params.CallCreateDepth) {
   147  		return nil, gas, ErrDepth
   148  	}
   149  	// Fail if we're trying to transfer more than the available balance
   150  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   151  		return nil, gas, ErrInsufficientBalance
   152  	}
   153  
   154  	var (
   155  		to       = AccountRef(addr)
   156  		snapshot = evm.StateDB.Snapshot()
   157  	)
   158  	if !evm.StateDB.Exist(addr) {
   159  		precompiles := PrecompiledContractsHomestead
   160  		if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
   161  			precompiles = PrecompiledContractsByzantium
   162  		}
   163  		if precompiles[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 {
   164  			// Calling a non existing account, don't do antything, but ping the tracer
   165  			if evm.vmConfig.Debug && evm.depth == 0 {
   166  				evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   167  				evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
   168  			}
   169  			return nil, gas, nil
   170  		}
   171  		evm.StateDB.CreateAccount(addr)
   172  	}
   173  	log.Error("evm.Transfer")
   174  	evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   175  
   176  	// Initialise a new contract and set the code that is to be used by the EVM.
   177  	// The contract is a scoped environment for this execution context only.
   178  	contract := NewContract(caller, to, value, gas)
   179  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   180  
   181  	start := time.Now()
   182  
   183  	// Capture the tracer start/end events in debug mode
   184  	if evm.vmConfig.Debug && evm.depth == 0 {
   185  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   186  
   187  		defer func() { // Lazy evaluation of the parameters
   188  			evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   189  		}()
   190  	}
   191  	log.Error("evm.run")
   192  	ret, err = run(evm, contract, input)
   193  
   194  	// When an error was returned by the EVM or when setting the creation code
   195  	// above we revert to the snapshot and consume any gas remaining. Additionally
   196  	// when we're in homestead this also counts for code storage gas errors.
   197  	if err != nil {
   198  		log.Error("evm.err","error",err)
   199  		evm.StateDB.RevertToSnapshot(snapshot)
   200  		if err != errExecutionReverted {
   201  			contract.UseGas(contract.Gas)
   202  		}
   203  	}
   204  	return ret, contract.Gas, err
   205  }
   206  
   207  // CallCode executes the contract associated with the addr with the given input
   208  // as parameters. It also handles any necessary value transfer required and takes
   209  // the necessary steps to create accounts and reverses the state in case of an
   210  // execution error or failed value transfer.
   211  //
   212  // CallCode differs from Call in the sense that it executes the given address'
   213  // code with the caller as context.
   214  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   215  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   216  		return nil, gas, nil
   217  	}
   218  
   219  	// Fail if we're trying to execute above the call depth limit
   220  	if evm.depth > int(params.CallCreateDepth) {
   221  		return nil, gas, ErrDepth
   222  	}
   223  	// Fail if we're trying to transfer more than the available balance
   224  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   225  		return nil, gas, ErrInsufficientBalance
   226  	}
   227  
   228  	var (
   229  		snapshot = evm.StateDB.Snapshot()
   230  		to       = AccountRef(caller.Address())
   231  	)
   232  	// initialise a new contract and set the code that is to be used by the
   233  	// EVM. The contract is a scoped environment for this execution context
   234  	// only.
   235  	contract := NewContract(caller, to, value, gas)
   236  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   237  
   238  	ret, err = run(evm, contract, input)
   239  	if err != nil {
   240  		evm.StateDB.RevertToSnapshot(snapshot)
   241  		if err != errExecutionReverted {
   242  			contract.UseGas(contract.Gas)
   243  		}
   244  	}
   245  	return ret, contract.Gas, err
   246  }
   247  
   248  // DelegateCall executes the contract associated with the addr with the given input
   249  // as parameters. It reverses the state in case of an execution error.
   250  //
   251  // DelegateCall differs from CallCode in the sense that it executes the given address'
   252  // code with the caller as context and the caller is set to the caller of the caller.
   253  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   254  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   255  		return nil, gas, nil
   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  
   262  	var (
   263  		snapshot = evm.StateDB.Snapshot()
   264  		to       = AccountRef(caller.Address())
   265  	)
   266  
   267  	// Initialise a new contract and make initialise the delegate values
   268  	contract := NewContract(caller, to, nil, gas).AsDelegate()
   269  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   270  
   271  	ret, err = run(evm, contract, input)
   272  	if err != nil {
   273  		evm.StateDB.RevertToSnapshot(snapshot)
   274  		if err != errExecutionReverted {
   275  			contract.UseGas(contract.Gas)
   276  		}
   277  	}
   278  	return ret, contract.Gas, err
   279  }
   280  
   281  // StaticCall executes the contract associated with the addr with the given input
   282  // as parameters while disallowing any modifications to the state during the call.
   283  // Opcodes that attempt to perform such modifications will result in exceptions
   284  // instead of performing the modifications.
   285  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   286  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   287  		return nil, gas, nil
   288  	}
   289  	// Fail if we're trying to execute above the call depth limit
   290  	if evm.depth > int(params.CallCreateDepth) {
   291  		return nil, gas, ErrDepth
   292  	}
   293  	// Make sure the readonly is only set if we aren't in readonly yet
   294  	// this makes also sure that the readonly flag isn't removed for
   295  	// child calls.
   296  	if !evm.interpreter.readOnly {
   297  		evm.interpreter.readOnly = true
   298  		defer func() { evm.interpreter.readOnly = false }()
   299  	}
   300  
   301  	var (
   302  		to       = AccountRef(addr)
   303  		snapshot = evm.StateDB.Snapshot()
   304  	)
   305  	// Initialise a new contract and set the code that is to be used by the
   306  	// EVM. The contract is a scoped environment for this execution context
   307  	// only.
   308  	contract := NewContract(caller, to, new(big.Int), gas)
   309  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   310  
   311  	// When an error was returned by the EVM or when setting the creation code
   312  	// above we revert to the snapshot and consume any gas remaining. Additionally
   313  	// when we're in Homestead this also counts for code storage gas errors.
   314  	ret, err = run(evm, contract, input)
   315  	if err != nil {
   316  		evm.StateDB.RevertToSnapshot(snapshot)
   317  		if err != errExecutionReverted {
   318  			contract.UseGas(contract.Gas)
   319  		}
   320  	}
   321  	return ret, contract.Gas, err
   322  }
   323  
   324  // Create creates a new contract using code as deployment code.
   325  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   326  
   327  	// Depth check execution. Fail if we're trying to execute above the
   328  	// limit.
   329  	if evm.depth > int(params.CallCreateDepth) {
   330  		return nil, common.Address{}, gas, ErrDepth
   331  	}
   332  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   333  		return nil, common.Address{}, gas, ErrInsufficientBalance
   334  	}
   335  	// Ensure there's no existing contract already at the designated address
   336  	nonce := evm.StateDB.GetNonce(caller.Address())
   337  	evm.StateDB.SetNonce(caller.Address(), nonce+1)
   338  
   339  	contractAddr = crypto.CreateAddress(caller.Address(), nonce)
   340  	contractHash := evm.StateDB.GetCodeHash(contractAddr)
   341  	if evm.StateDB.GetNonce(contractAddr) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   342  		return nil, common.Address{}, 0, ErrContractAddressCollision
   343  	}
   344  	// Create a new account on the state
   345  	snapshot := evm.StateDB.Snapshot()
   346  	evm.StateDB.CreateAccount(contractAddr)
   347  	if evm.ChainConfig().IsEIP158(evm.BlockNumber) {
   348  		evm.StateDB.SetNonce(contractAddr, 1)
   349  	}
   350  	evm.Transfer(evm.StateDB, caller.Address(), contractAddr, value)
   351  
   352  	// initialise a new contract and set the code that is to be used by the
   353  	// EVM. The contract is a scoped environment for this execution context
   354  	// only.
   355  	contract := NewContract(caller, AccountRef(contractAddr), value, gas)
   356  	contract.SetCallCode(&contractAddr, crypto.Keccak256Hash(code), code)
   357  
   358  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   359  		return nil, contractAddr, gas, nil
   360  	}
   361  
   362  	if evm.vmConfig.Debug && evm.depth == 0 {
   363  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), contractAddr, true, code, gas, value)
   364  	}
   365  	start := time.Now()
   366  
   367  	ret, err = run(evm, contract, nil)
   368  
   369  	// check whether the max code size has been exceeded
   370  	maxCodeSizeExceeded := evm.ChainConfig().IsEIP158(evm.BlockNumber) && len(ret) > params.MaxCodeSize
   371  	// if the contract creation ran successfully and no errors were returned
   372  	// calculate the gas required to store the code. If the code could not
   373  	// be stored due to not enough gas set an error and let it be handled
   374  	// by the error checking condition below.
   375  	if err == nil && !maxCodeSizeExceeded {
   376  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   377  		if contract.UseGas(createDataGas) {
   378  			evm.StateDB.SetCode(contractAddr, ret)
   379  		} else {
   380  			err = ErrCodeStoreOutOfGas
   381  		}
   382  	}
   383  
   384  	// When an error was returned by the EVM or when setting the creation code
   385  	// above we revert to the snapshot and consume any gas remaining. Additionally
   386  	// when we're in homestead this also counts for code storage gas errors.
   387  	if maxCodeSizeExceeded || (err != nil && (evm.ChainConfig().IsHomestead(evm.BlockNumber) || err != ErrCodeStoreOutOfGas)) {
   388  		evm.StateDB.RevertToSnapshot(snapshot)
   389  		if err != errExecutionReverted {
   390  			contract.UseGas(contract.Gas)
   391  		}
   392  	}
   393  	// Assign err if contract code size exceeds the max while the err is still empty.
   394  	if maxCodeSizeExceeded && err == nil {
   395  		err = errMaxCodeSizeExceeded
   396  	}
   397  	if evm.vmConfig.Debug && evm.depth == 0 {
   398  		evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   399  	}
   400  	return ret, contractAddr, contract.Gas, err
   401  }
   402  
   403  // ChainConfig returns the environment's chain configuration
   404  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }
   405  
   406  // Interpreter returns the EVM interpreter
   407  func (evm *EVM) Interpreter() *Interpreter { return evm.interpreter }