github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/core/vm/evm.go (about)

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