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