github.com/intfoundation/intchain@v0.0.0-20220727031208-4316ad31ca73/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/intfoundation/intchain/common"
    25  	"github.com/intfoundation/intchain/crypto"
    26  	"github.com/intfoundation/intchain/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 n'th 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.chainRules.IsByzantium {
    48  			precompiles = PrecompiledContractsByzantium
    49  		}
    50  		if evm.chainRules.IsIstanbul {
    51  			precompiles = PrecompiledContractsIstanbul
    52  		}
    53  		if p := precompiles[*contract.CodeAddr]; p != nil {
    54  			return RunPrecompiledContract(p, input, contract)
    55  		}
    56  	}
    57  	for _, interpreter := range evm.interpreters {
    58  		if interpreter.CanRun(contract.Code) {
    59  			if evm.interpreter != interpreter {
    60  				// Ensure that the interpreter pointer is set back
    61  				// to its current value upon return.
    62  				defer func(i Interpreter) {
    63  					evm.interpreter = i
    64  				}(evm.interpreter)
    65  				evm.interpreter = interpreter
    66  			}
    67  			return interpreter.Run(contract, input, readOnly)
    68  		}
    69  	}
    70  	return nil, ErrNoCompatibleInterpreter
    71  }
    72  
    73  // Context provides the EVM with auxiliary information. Once provided
    74  // it shouldn't be modified.
    75  type Context struct {
    76  	// CanTransfer returns whether the account contains
    77  	// sufficient ether to transfer the value
    78  	CanTransfer CanTransferFunc
    79  	// Transfer transfers ether from one account to the other
    80  	Transfer TransferFunc
    81  	// GetHash returns the hash corresponding to n
    82  	GetHash GetHashFunc
    83  
    84  	// Message information
    85  	Origin   common.Address // Provides information for ORIGIN
    86  	GasPrice *big.Int       // Provides information for GASPRICE
    87  
    88  	// Block information
    89  	Coinbase    common.Address // Provides information for COINBASE
    90  	GasLimit    uint64         // Provides information for GASLIMIT
    91  	BlockNumber *big.Int       // Provides information for NUMBER
    92  	Time        *big.Int       // Provides information for TIME
    93  	Difficulty  *big.Int       // Provides information for DIFFICULTY
    94  }
    95  
    96  // EVM is the Ethereum Virtual Machine base object and provides
    97  // the necessary tools to run a contract on the given state with
    98  // the provided context. It should be noted that any error
    99  // generated through any of the calls should be considered a
   100  // revert-state-and-consume-all-gas operation, no checks on
   101  // specific errors should ever be performed. The interpreter makes
   102  // sure that any errors generated are to be considered faulty code.
   103  //
   104  // The EVM should never be reused and is not thread safe.
   105  type EVM struct {
   106  	// Context provides auxiliary blockchain related information
   107  	Context
   108  	// StateDB gives access to the underlying state
   109  	StateDB StateDB
   110  	// Depth is the current call stack
   111  	depth int
   112  
   113  	// chainConfig contains information about the current chain
   114  	chainConfig *params.ChainConfig
   115  	// chain rules contains the chain rules for the current epoch
   116  	chainRules params.Rules
   117  	// virtual machine configuration options used to initialise the
   118  	// evm.
   119  	vmConfig Config
   120  	// global (to this context) ethereum virtual machine
   121  	// used throughout the execution of the tx.
   122  	interpreters []Interpreter
   123  	interpreter  Interpreter
   124  	// abort is used to abort the EVM calling operations
   125  	// NOTE: must be set atomically
   126  	abort int32
   127  	// callGasTemp holds the gas available for the current call. This is needed because the
   128  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   129  	// applied in opCall*.
   130  	callGasTemp uint64
   131  }
   132  
   133  // NewEVM returns a new EVM. The returned EVM is not thread safe and should
   134  // only ever be used *once*.
   135  func NewEVM(ctx Context, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
   136  	evm := &EVM{
   137  		Context:      ctx,
   138  		StateDB:      statedb,
   139  		vmConfig:     vmConfig,
   140  		chainConfig:  chainConfig,
   141  		chainRules:   chainConfig.Rules(ctx.BlockNumber),
   142  		interpreters: make([]Interpreter, 0, 1),
   143  	}
   144  
   145  	if chainConfig.IsEWASM(ctx.BlockNumber) {
   146  		// to be implemented by EVM-C and Wagon PRs.
   147  		// if vmConfig.EWASMInterpreter != "" {
   148  		//  extIntOpts := strings.Split(vmConfig.EWASMInterpreter, ":")
   149  		//  path := extIntOpts[0]
   150  		//  options := []string{}
   151  		//  if len(extIntOpts) > 1 {
   152  		//    options = extIntOpts[1..]
   153  		//  }
   154  		//  evm.interpreters = append(evm.interpreters, NewEVMVCInterpreter(evm, vmConfig, options))
   155  		// } else {
   156  		// 	evm.interpreters = append(evm.interpreters, NewEWASMInterpreter(evm, vmConfig))
   157  		// }
   158  		panic("No supported ewasm interpreter yet.")
   159  	}
   160  
   161  	// vmConfig.EVMInterpreter will be used by EVM-C, it won't be checked here
   162  	// as we always want to have the built-in EVM as the failover option.
   163  	evm.interpreters = append(evm.interpreters, NewEVMInterpreter(evm, vmConfig))
   164  	evm.interpreter = evm.interpreters[0]
   165  
   166  	return evm
   167  }
   168  
   169  // Cancel cancels any running EVM operation. This may be called concurrently and
   170  // it's safe to be called multiple times.
   171  func (evm *EVM) Cancel() {
   172  	atomic.StoreInt32(&evm.abort, 1)
   173  }
   174  
   175  // Cancelled returns true if Cancel has been called
   176  func (evm *EVM) Cancelled() bool {
   177  	return atomic.LoadInt32(&evm.abort) == 1
   178  }
   179  
   180  // Interpreter returns the current interpreter
   181  func (evm *EVM) Interpreter() Interpreter {
   182  	return evm.interpreter
   183  }
   184  
   185  // Call executes the contract associated with the addr with the given input as
   186  // parameters. It also handles any necessary value transfer required and takes
   187  // the necessary steps to create accounts and reverses the state in case of an
   188  // execution error or failed value transfer.
   189  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   190  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   191  		return nil, gas, nil
   192  	}
   193  
   194  	// Fail if we're trying to execute above the call depth limit
   195  	if evm.depth > int(params.CallCreateDepth) {
   196  		return nil, gas, ErrDepth
   197  	}
   198  	// Fail if we're trying to transfer more than the available balance
   199  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   200  		return nil, gas, ErrInsufficientBalance
   201  	}
   202  
   203  	var (
   204  		to       = AccountRef(addr)
   205  		snapshot = evm.StateDB.Snapshot()
   206  	)
   207  	if !evm.StateDB.Exist(addr) {
   208  		precompiles := PrecompiledContractsHomestead
   209  		if evm.chainRules.IsByzantium {
   210  			precompiles = PrecompiledContractsByzantium
   211  		}
   212  		if evm.chainRules.IsIstanbul {
   213  			precompiles = PrecompiledContractsIstanbul
   214  		}
   215  		if precompiles[addr] == nil && evm.chainRules.IsEIP158 && value.Sign() == 0 {
   216  			// Calling a non existing account, don't do anything, but ping the tracer
   217  			if evm.vmConfig.Debug && evm.depth == 0 {
   218  				evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   219  				evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
   220  			}
   221  			return nil, gas, nil
   222  		}
   223  		evm.StateDB.CreateAccount(addr)
   224  	}
   225  	evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   226  
   227  	// Initialise a new contract and set the code that is to be used by the EVM.
   228  	// The contract is a scoped environment for this execution context only.
   229  	contract := NewContract(caller, to, value, gas)
   230  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   231  
   232  	// Even if the account has no code, we need to continue because it might be a precompile
   233  	start := time.Now()
   234  
   235  	// Capture the tracer start/end events in debug mode
   236  	if evm.vmConfig.Debug && evm.depth == 0 {
   237  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   238  
   239  		defer func() { // Lazy evaluation of the parameters
   240  			evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   241  		}()
   242  	}
   243  	ret, err = run(evm, contract, input, false)
   244  
   245  	// When an error was returned by the EVM or when setting the creation code
   246  	// above we revert to the snapshot and consume any gas remaining. Additionally
   247  	// when we're in homestead this also counts for code storage gas errors.
   248  	if err != nil {
   249  		evm.StateDB.RevertToSnapshot(snapshot)
   250  		if err != ErrExecutionReverted {
   251  			contract.UseGas(contract.Gas)
   252  		}
   253  	}
   254  	return ret, contract.Gas, err
   255  }
   256  
   257  // CallCode executes the contract associated with the addr with the given input
   258  // as parameters. It also handles any necessary value transfer required and takes
   259  // the necessary steps to create accounts and reverses the state in case of an
   260  // execution error or failed value transfer.
   261  //
   262  // CallCode differs from Call in the sense that it executes the given address'
   263  // code with the caller as context.
   264  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   265  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   266  		return nil, gas, nil
   267  	}
   268  
   269  	// Fail if we're trying to execute above the call depth limit
   270  	if evm.depth > int(params.CallCreateDepth) {
   271  		return nil, gas, ErrDepth
   272  	}
   273  	// Fail if we're trying to transfer more than the available balance
   274  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   275  		return nil, gas, ErrInsufficientBalance
   276  	}
   277  
   278  	var (
   279  		snapshot = evm.StateDB.Snapshot()
   280  		to       = AccountRef(caller.Address())
   281  	)
   282  	// Initialise a new contract and set the code that is to be used by the EVM.
   283  	// The contract is a scoped environment for this execution context only.
   284  	contract := NewContract(caller, to, value, gas)
   285  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   286  
   287  	ret, err = run(evm, contract, input, false)
   288  	if err != nil {
   289  		evm.StateDB.RevertToSnapshot(snapshot)
   290  		if err != ErrExecutionReverted {
   291  			contract.UseGas(contract.Gas)
   292  		}
   293  	}
   294  	return ret, contract.Gas, err
   295  }
   296  
   297  // DelegateCall executes the contract associated with the addr with the given input
   298  // as parameters. It reverses the state in case of an execution error.
   299  //
   300  // DelegateCall differs from CallCode in the sense that it executes the given address'
   301  // code with the caller as context and the caller is set to the caller of the caller.
   302  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   303  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   304  		return nil, gas, nil
   305  	}
   306  	// Fail if we're trying to execute above the call depth limit
   307  	if evm.depth > int(params.CallCreateDepth) {
   308  		return nil, gas, ErrDepth
   309  	}
   310  
   311  	var (
   312  		snapshot = evm.StateDB.Snapshot()
   313  		to       = AccountRef(caller.Address())
   314  	)
   315  
   316  	// Initialise a new contract and make initialise the delegate values
   317  	contract := NewContract(caller, to, nil, gas).AsDelegate()
   318  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   319  
   320  	ret, err = run(evm, contract, input, false)
   321  	if err != nil {
   322  		evm.StateDB.RevertToSnapshot(snapshot)
   323  		if err != ErrExecutionReverted {
   324  			contract.UseGas(contract.Gas)
   325  		}
   326  	}
   327  	return ret, contract.Gas, err
   328  }
   329  
   330  // StaticCall executes the contract associated with the addr with the given input
   331  // as parameters while disallowing any modifications to the state during the call.
   332  // Opcodes that attempt to perform such modifications will result in exceptions
   333  // instead of performing the modifications.
   334  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   335  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   336  		return nil, gas, nil
   337  	}
   338  	// Fail if we're trying to execute above the call depth limit
   339  	if evm.depth > int(params.CallCreateDepth) {
   340  		return nil, gas, ErrDepth
   341  	}
   342  
   343  	var (
   344  		to       = AccountRef(addr)
   345  		snapshot = evm.StateDB.Snapshot()
   346  	)
   347  	// Initialise a new contract and set the code that is to be used by the EVM.
   348  	// The contract is a scoped environment for this execution context only.
   349  	contract := NewContract(caller, to, new(big.Int), gas)
   350  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   351  
   352  	// We do an AddBalance of zero here, just in order to trigger a touch.
   353  	// This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium,
   354  	// but is the correct thing to do and matters on other networks, in tests, and potential
   355  	// future scenarios
   356  	evm.StateDB.AddBalance(addr, bigZero)
   357  
   358  	// When an error was returned by the EVM or when setting the creation code
   359  	// above we revert to the snapshot and consume any gas remaining. Additionally
   360  	// when we're in Homestead this also counts for code storage gas errors.
   361  	ret, err = run(evm, contract, input, true)
   362  	if err != nil {
   363  		evm.StateDB.RevertToSnapshot(snapshot)
   364  		if err != ErrExecutionReverted {
   365  			contract.UseGas(contract.Gas)
   366  		}
   367  	}
   368  	return ret, contract.Gas, err
   369  }
   370  
   371  type codeAndHash struct {
   372  	code []byte
   373  	hash common.Hash
   374  }
   375  
   376  func (c *codeAndHash) Hash() common.Hash {
   377  	if c.hash == (common.Hash{}) {
   378  		c.hash = crypto.Keccak256Hash(c.code)
   379  	}
   380  	return c.hash
   381  }
   382  
   383  // create creates a new contract using code as deployment code.
   384  func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
   385  	// Depth check execution. Fail if we're trying to execute above the
   386  	// limit.
   387  	if evm.depth > int(params.CallCreateDepth) {
   388  		return nil, common.Address{}, gas, ErrDepth
   389  	}
   390  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   391  		return nil, common.Address{}, gas, ErrInsufficientBalance
   392  	}
   393  	nonce := evm.StateDB.GetNonce(caller.Address())
   394  	evm.StateDB.SetNonce(caller.Address(), nonce+1)
   395  
   396  	// Ensure there's no existing contract already at the designated address
   397  	contractHash := evm.StateDB.GetCodeHash(address)
   398  	if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   399  		return nil, common.Address{}, 0, ErrContractAddressCollision
   400  	}
   401  	// Create a new account on the state
   402  	snapshot := evm.StateDB.Snapshot()
   403  	evm.StateDB.CreateAccount(address)
   404  	if evm.chainRules.IsEIP158 {
   405  		evm.StateDB.SetNonce(address, 1)
   406  	}
   407  	evm.Transfer(evm.StateDB, caller.Address(), address, value)
   408  
   409  	// Initialise a new contract and set the code that is to be used by the EVM.
   410  	// The contract is a scoped environment for this execution context only.
   411  	contract := NewContract(caller, AccountRef(address), value, gas)
   412  	contract.SetCodeOptionalHash(&address, codeAndHash)
   413  
   414  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   415  		return nil, address, gas, nil
   416  	}
   417  
   418  	if evm.vmConfig.Debug && evm.depth == 0 {
   419  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value)
   420  	}
   421  	start := time.Now()
   422  
   423  	ret, err := run(evm, contract, nil, false)
   424  
   425  	// check whether the max code size has been exceeded
   426  	maxCodeSizeExceeded := evm.chainRules.IsEIP158 && len(ret) > params.MaxCodeSize
   427  	// if the contract creation ran successfully and no errors were returned
   428  	// calculate the gas required to store the code. If the code could not
   429  	// be stored due to not enough gas set an error and let it be handled
   430  	// by the error checking condition below.
   431  	if err == nil && !maxCodeSizeExceeded {
   432  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   433  		if contract.UseGas(createDataGas) {
   434  			evm.StateDB.SetCode(address, ret)
   435  		} else {
   436  			err = ErrCodeStoreOutOfGas
   437  		}
   438  	}
   439  
   440  	// When an error was returned by the EVM or when setting the creation code
   441  	// above we revert to the snapshot and consume any gas remaining. Additionally
   442  	// when we're in homestead this also counts for code storage gas errors.
   443  	if maxCodeSizeExceeded || (err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas)) {
   444  		evm.StateDB.RevertToSnapshot(snapshot)
   445  		if err != ErrExecutionReverted {
   446  			contract.UseGas(contract.Gas)
   447  		}
   448  	}
   449  	// Assign err if contract code size exceeds the max while the err is still empty.
   450  	if maxCodeSizeExceeded && err == nil {
   451  		err = ErrMaxCodeSizeExceeded
   452  	}
   453  	if evm.vmConfig.Debug && evm.depth == 0 {
   454  		evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   455  	}
   456  	return ret, address, contract.Gas, err
   457  
   458  }
   459  
   460  // Create creates a new contract using code as deployment code.
   461  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   462  	contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
   463  	return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
   464  }
   465  
   466  // Create2 creates a new contract using code as deployment code.
   467  //
   468  // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
   469  // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
   470  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) {
   471  	codeAndHash := &codeAndHash{code: code}
   472  	contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), codeAndHash.Hash().Bytes())
   473  	return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
   474  }
   475  
   476  // ChainConfig returns the environment's chain configuration
   477  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }