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