github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/core/vm/evm.go (about)

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