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