github.com/pfcoder/quorum@v2.0.3-0.20180501191142-d4a1b0958135+incompatible/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  
    23  	"github.com/ethereum/go-ethereum/common"
    24  	"github.com/ethereum/go-ethereum/core/state"
    25  	"github.com/ethereum/go-ethereum/crypto"
    26  	"github.com/ethereum/go-ethereum/params"
    27  )
    28  
    29  // note: Quorum, States, and Value Transfer
    30  //
    31  // In Quorum there is a tricky issue in one specific case when there is call from private state to public state:
    32  // * The state db is selected based on the callee (public)
    33  // * With every call there is an associated value transfer -- in our case this is 0
    34  // * Thus, there is an implicit transfer of 0 value from the caller to callee on the public state
    35  // * However in our scenario the caller is private
    36  // * Thus, the transfer creates a ghost of the private account on the public state with no value, code, or storage
    37  //
    38  // The solution is to skip this transfer of 0 value under Quorum
    39  
    40  // emptyCodeHash is used by create to ensure deployment is disallowed to already
    41  // deployed contract addresses (relevant after the account abstraction).
    42  var emptyCodeHash = crypto.Keccak256Hash(nil)
    43  
    44  type (
    45  	CanTransferFunc func(StateDB, common.Address, *big.Int) bool
    46  	TransferFunc    func(StateDB, common.Address, common.Address, *big.Int)
    47  	// GetHashFunc returns the nth block hash in the blockchain
    48  	// and is used by the BLOCKHASH EVM op code.
    49  	GetHashFunc func(uint64) common.Hash
    50  )
    51  
    52  // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
    53  func run(evm *EVM, snapshot int, contract *Contract, input []byte) ([]byte, error) {
    54  	if contract.CodeAddr != nil {
    55  		precompiles := PrecompiledContractsHomestead
    56  		if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
    57  			precompiles = PrecompiledContractsByzantium
    58  		}
    59  		if p := precompiles[*contract.CodeAddr]; p != nil {
    60  			return RunPrecompiledContract(p, input, contract)
    61  		}
    62  	}
    63  	return evm.interpreter.Run(snapshot, contract, input)
    64  }
    65  
    66  // Context provides the EVM with auxiliary information. Once provided
    67  // it shouldn't be modified.
    68  type Context struct {
    69  	// CanTransfer returns whether the account contains
    70  	// sufficient ether to transfer the value
    71  	CanTransfer CanTransferFunc
    72  	// Transfer transfers ether from one account to the other
    73  	Transfer TransferFunc
    74  	// GetHash returns the hash corresponding to n
    75  	GetHash GetHashFunc
    76  
    77  	// Message information
    78  	Origin   common.Address // Provides information for ORIGIN
    79  	GasPrice *big.Int       // Provides information for GASPRICE
    80  
    81  	// Block information
    82  	Coinbase    common.Address // Provides information for COINBASE
    83  	GasLimit    *big.Int       // Provides information for GASLIMIT
    84  	BlockNumber *big.Int       // Provides information for NUMBER
    85  	Time        *big.Int       // Provides information for TIME
    86  	Difficulty  *big.Int       // Provides information for DIFFICULTY
    87  }
    88  
    89  type PublicState StateDB
    90  type PrivateState StateDB
    91  
    92  // EVM is the Ethereum Virtual Machine base object and provides
    93  // the necessary tools to run a contract on the given state with
    94  // the provided context. It should be noted that any error
    95  // generated through any of the calls should be considered a
    96  // revert-state-and-consume-all-gas operation, no checks on
    97  // specific errors should ever be performed. The interpreter makes
    98  // sure that any errors generated are to be considered faulty code.
    99  //
   100  // The EVM should never be reused and is not thread safe.
   101  type EVM struct {
   102  	// Context provides auxiliary blockchain related information
   103  	Context
   104  	// StateDB gives access to the underlying state
   105  	StateDB StateDB
   106  	// Depth is the current call stack
   107  	depth int
   108  
   109  	// chainConfig contains information about the current chain
   110  	chainConfig *params.ChainConfig
   111  	// chain rules contains the chain rules for the current epoch
   112  	chainRules params.Rules
   113  	// virtual machine configuration options used to initialise the
   114  	// evm.
   115  	vmConfig Config
   116  	// global (to this context) ethereum virtual machine
   117  	// used throughout the execution of the tx.
   118  	interpreter *Interpreter
   119  	// abort is used to abort the EVM calling operations
   120  	// NOTE: must be set atomically
   121  	abort int32
   122  
   123  	// Quorum additions:
   124  	publicState       PublicState
   125  	privateState      PrivateState
   126  	states            [1027]*state.StateDB // TODO(joel) we should be able to get away with 1024 or maybe 1025
   127  	currentStateDepth uint
   128  	// This flag has different semantics from the `Interpreter:readOnly` flag (though they interact and could maybe
   129  	// be simplified). This is set by Quorum when it's inside a Private State -> Public State read.
   130  	quorumReadOnly bool
   131  	readOnlyDepth  uint
   132  }
   133  
   134  // NewEVM retutrns a new EVM . The returned EVM is not thread safe and should
   135  // only ever be used *once*.
   136  func NewEVM(ctx Context, statedb, privateState StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
   137  	evm := &EVM{
   138  		Context:     ctx,
   139  		StateDB:     statedb,
   140  		vmConfig:    vmConfig,
   141  		chainConfig: chainConfig,
   142  		chainRules:  chainConfig.Rules(ctx.BlockNumber),
   143  
   144  		publicState:  statedb,
   145  		privateState: privateState,
   146  	}
   147  
   148  	evm.Push(privateState)
   149  
   150  	evm.interpreter = NewInterpreter(evm, vmConfig)
   151  	return evm
   152  }
   153  
   154  // Cancel cancels any running EVM operation. This may be called concurrently and
   155  // it's safe to be called multiple times.
   156  func (evm *EVM) Cancel() {
   157  	atomic.StoreInt32(&evm.abort, 1)
   158  }
   159  
   160  // Call executes the contract associated with the addr with the given input as
   161  // parameters. It also handles any necessary value transfer required and takes
   162  // the necessary steps to create accounts and reverses the state in case of an
   163  // execution error or failed value transfer.
   164  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   165  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   166  		return nil, gas, nil
   167  	}
   168  
   169  	evm.Push(getDualState(evm, addr))
   170  	defer func() { evm.Pop() }()
   171  
   172  	// Fail if we're trying to execute above the call depth limit
   173  	if evm.depth > int(params.CallCreateDepth) {
   174  		return nil, gas, ErrDepth
   175  	}
   176  	// Fail if we're trying to transfer more than the available balance
   177  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   178  		return nil, gas, ErrInsufficientBalance
   179  	}
   180  
   181  	var (
   182  		to       = AccountRef(addr)
   183  		snapshot = evm.StateDB.Snapshot()
   184  	)
   185  	if !evm.StateDB.Exist(addr) {
   186  		precompiles := PrecompiledContractsHomestead
   187  		if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
   188  			precompiles = PrecompiledContractsByzantium
   189  		}
   190  		if precompiles[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 {
   191  			return nil, gas, nil
   192  		}
   193  
   194  		evm.StateDB.CreateAccount(addr)
   195  	}
   196  	if evm.ChainConfig().IsQuorum {
   197  		// skip transfer if value /= 0 (see note: Quorum, States, and Value Transfer)
   198  		if value.Sign() != 0 {
   199  			if evm.quorumReadOnly {
   200  				return nil, gas, ErrReadOnlyValueTransfer
   201  			}
   202  			evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   203  		}
   204  	} else {
   205  		evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   206  	}
   207  
   208  	// initialise a new contract and set the code that is to be used by the
   209  	// E The contract is a scoped environment for this execution context
   210  	// only.
   211  	contract := NewContract(caller, to, value, gas)
   212  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   213  
   214  	ret, err = run(evm, snapshot, contract, input)
   215  	// When an error was returned by the EVM or when setting the creation code
   216  	// above we revert to the snapshot and consume any gas remaining. Additionally
   217  	// when we're in homestead this also counts for code storage gas errors.
   218  	if err != nil {
   219  		evm.StateDB.RevertToSnapshot(snapshot)
   220  		if err != errExecutionReverted {
   221  			contract.UseGas(contract.Gas)
   222  		}
   223  	}
   224  	return ret, contract.Gas, err
   225  }
   226  
   227  // CallCode executes the contract associated with the addr with the given input
   228  // as parameters. It also handles any necessary value transfer required and takes
   229  // the necessary steps to create accounts and reverses the state in case of an
   230  // execution error or failed value transfer.
   231  //
   232  // CallCode differs from Call in the sense that it executes the given address'
   233  // code with the caller as context.
   234  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   235  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   236  		return nil, gas, nil
   237  	}
   238  
   239  	evm.Push(getDualState(evm, addr))
   240  	defer func() { evm.Pop() }()
   241  
   242  	// Fail if we're trying to execute above the call depth limit
   243  	if evm.depth > int(params.CallCreateDepth) {
   244  		return nil, gas, ErrDepth
   245  	}
   246  	// Fail if we're trying to transfer more than the available balance
   247  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   248  		return nil, gas, ErrInsufficientBalance
   249  	}
   250  
   251  	var (
   252  		snapshot = evm.StateDB.Snapshot()
   253  		to       = AccountRef(caller.Address())
   254  	)
   255  	// initialise a new contract and set the code that is to be used by the
   256  	// E The contract is a scoped evmironment for this execution context
   257  	// only.
   258  	contract := NewContract(caller, to, value, gas)
   259  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   260  
   261  	ret, err = run(evm, snapshot, contract, input)
   262  	if err != nil {
   263  		evm.StateDB.RevertToSnapshot(snapshot)
   264  		if err != errExecutionReverted {
   265  			contract.UseGas(contract.Gas)
   266  		}
   267  	}
   268  	return ret, contract.Gas, err
   269  }
   270  
   271  // DelegateCall executes the contract associated with the addr with the given input
   272  // as parameters. It reverses the state in case of an execution error.
   273  //
   274  // DelegateCall differs from CallCode in the sense that it executes the given address'
   275  // code with the caller as context and the caller is set to the caller of the caller.
   276  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   277  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   278  		return nil, gas, nil
   279  	}
   280  
   281  	evm.Push(getDualState(evm, addr))
   282  	defer func() { evm.Pop() }()
   283  
   284  	// Fail if we're trying to execute above the call depth limit
   285  	if evm.depth > int(params.CallCreateDepth) {
   286  		return nil, gas, ErrDepth
   287  	}
   288  
   289  	var (
   290  		snapshot = evm.StateDB.Snapshot()
   291  		to       = AccountRef(caller.Address())
   292  	)
   293  
   294  	// Initialise a new contract and make initialise the delegate values
   295  	contract := NewContract(caller, to, nil, gas).AsDelegate()
   296  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   297  
   298  	ret, err = run(evm, snapshot, contract, input)
   299  	if err != nil {
   300  		evm.StateDB.RevertToSnapshot(snapshot)
   301  		if err != errExecutionReverted {
   302  			contract.UseGas(contract.Gas)
   303  		}
   304  	}
   305  	return ret, contract.Gas, err
   306  }
   307  
   308  // StaticCall executes the contract associated with the addr with the given input
   309  // as parameters while disallowing any modifications to the state during the call.
   310  // Opcodes that attempt to perform such modifications will result in exceptions
   311  // instead of performing the modifications.
   312  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   313  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   314  		return nil, gas, nil
   315  	}
   316  	// Fail if we're trying to execute above the call depth limit
   317  	if evm.depth > int(params.CallCreateDepth) {
   318  		return nil, gas, ErrDepth
   319  	}
   320  	// Make sure the readonly is only set if we aren't in readonly yet
   321  	// this makes also sure that the readonly flag isn't removed for
   322  	// child calls.
   323  	if !evm.interpreter.readOnly {
   324  		evm.interpreter.readOnly = true
   325  		defer func() { evm.interpreter.readOnly = false }()
   326  	}
   327  
   328  	var (
   329  		to       = AccountRef(addr)
   330  		snapshot = evm.StateDB.Snapshot()
   331  	)
   332  	// Initialise a new contract and set the code that is to be used by the
   333  	// EVM. The contract is a scoped environment for this execution context
   334  	// only.
   335  	contract := NewContract(caller, to, new(big.Int), gas)
   336  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   337  
   338  	// When an error was returned by the EVM or when setting the creation code
   339  	// above we revert to the snapshot and consume any gas remaining. Additionally
   340  	// when we're in Homestead this also counts for code storage gas errors.
   341  	ret, err = run(evm, snapshot, contract, input)
   342  	if err != nil {
   343  		evm.StateDB.RevertToSnapshot(snapshot)
   344  		if err != errExecutionReverted {
   345  			contract.UseGas(contract.Gas)
   346  		}
   347  	}
   348  	return ret, contract.Gas, err
   349  }
   350  
   351  // Create creates a new contract using code as deployment code.
   352  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   353  
   354  	// Depth check execution. Fail if we're trying to execute above the
   355  	// limit.
   356  	if evm.depth > int(params.CallCreateDepth) {
   357  		return nil, common.Address{}, gas, ErrDepth
   358  	}
   359  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   360  		return nil, common.Address{}, gas, ErrInsufficientBalance
   361  	}
   362  
   363  	// Get the right state in case of a dual state environment. If a sender
   364  	// is a transaction (depth == 0) use the public state to derive the address
   365  	// and increment the nonce of the public state. If the sender is a contract
   366  	// (depth > 0) use the private state to derive the nonce and increment the
   367  	// nonce on the private state only.
   368  	//
   369  	// If the transaction went to a public contract the private and public state
   370  	// are the same.
   371  	var creatorStateDb StateDB
   372  	if evm.Depth() > 0 {
   373  		creatorStateDb = evm.privateState
   374  	} else {
   375  		creatorStateDb = evm.publicState
   376  	}
   377  
   378  	// Ensure there's no existing contract already at the designated address
   379  	nonce := creatorStateDb.GetNonce(caller.Address())
   380  	creatorStateDb.SetNonce(caller.Address(), nonce+1)
   381  
   382  	contractAddr = crypto.CreateAddress(caller.Address(), nonce)
   383  	contractHash := evm.StateDB.GetCodeHash(contractAddr)
   384  	if evm.StateDB.GetNonce(contractAddr) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   385  		return nil, common.Address{}, 0, ErrContractAddressCollision
   386  	}
   387  	// Create a new account on the state
   388  	snapshot := evm.StateDB.Snapshot()
   389  	evm.StateDB.CreateAccount(contractAddr)
   390  	if evm.ChainConfig().IsEIP158(evm.BlockNumber) {
   391  		evm.StateDB.SetNonce(contractAddr, 1)
   392  	}
   393  	if evm.ChainConfig().IsQuorum {
   394  		// skip transfer if value /= 0 (see note: Quorum, States, and Value Transfer)
   395  		if value.Sign() != 0 {
   396  			if evm.quorumReadOnly {
   397  				return nil, common.Address{}, gas, ErrReadOnlyValueTransfer
   398  			}
   399  			evm.Transfer(evm.StateDB, caller.Address(), contractAddr, value)
   400  		}
   401  	} else {
   402  		evm.Transfer(evm.StateDB, caller.Address(), contractAddr, value)
   403  	}
   404  
   405  	// initialise a new contract and set the code that is to be used by the
   406  	// E The contract is a scoped evmironment for this execution context
   407  	// only.
   408  	contract := NewContract(caller, AccountRef(contractAddr), value, gas)
   409  	contract.SetCallCode(&contractAddr, crypto.Keccak256Hash(code), code)
   410  
   411  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   412  		return nil, contractAddr, gas, nil
   413  	}
   414  	ret, err = run(evm, snapshot, contract, nil)
   415  	// check whether the max code size has been exceeded
   416  	maxCodeSizeExceeded := evm.ChainConfig().IsEIP158(evm.BlockNumber) && len(ret) > params.MaxCodeSize
   417  	// if the contract creation ran successfully and no errors were returned
   418  	// calculate the gas required to store the code. If the code could not
   419  	// be stored due to not enough gas set an error and let it be handled
   420  	// by the error checking condition below.
   421  	if err == nil && !maxCodeSizeExceeded {
   422  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   423  		if contract.UseGas(createDataGas) {
   424  			evm.StateDB.SetCode(contractAddr, ret)
   425  		} else {
   426  			err = ErrCodeStoreOutOfGas
   427  		}
   428  	}
   429  
   430  	// When an error was returned by the EVM or when setting the creation code
   431  	// above we revert to the snapshot and consume any gas remaining. Additionally
   432  	// when we're in homestead this also counts for code storage gas errors.
   433  	if maxCodeSizeExceeded || (err != nil && (evm.ChainConfig().IsHomestead(evm.BlockNumber) || err != ErrCodeStoreOutOfGas)) {
   434  		evm.StateDB.RevertToSnapshot(snapshot)
   435  		if err != errExecutionReverted {
   436  			contract.UseGas(contract.Gas)
   437  		}
   438  	}
   439  	// Assign err if contract code size exceeds the max while the err is still empty.
   440  	if maxCodeSizeExceeded && err == nil {
   441  		err = errMaxCodeSizeExceeded
   442  	}
   443  	return ret, contractAddr, contract.Gas, err
   444  }
   445  
   446  // ChainConfig returns the evmironment's chain configuration
   447  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }
   448  
   449  // Interpreter returns the EVM interpreter
   450  func (evm *EVM) Interpreter() *Interpreter { return evm.interpreter }
   451  
   452  func getDualState(env *EVM, addr common.Address) StateDB {
   453  	// priv: (a) -> (b)  (private)
   454  	// pub:   a  -> [b]  (private -> public)
   455  	// priv: (a) ->  b   (public)
   456  	state := env.StateDB
   457  
   458  	if env.PrivateState().Exist(addr) {
   459  		state = env.PrivateState()
   460  	} else if env.PublicState().Exist(addr) {
   461  		state = env.PublicState()
   462  	}
   463  
   464  	return state
   465  }
   466  
   467  func (env *EVM) PublicState() PublicState   { return env.publicState }
   468  func (env *EVM) PrivateState() PrivateState { return env.privateState }
   469  func (env *EVM) Push(statedb StateDB) {
   470  	if env.privateState != statedb {
   471  		env.quorumReadOnly = true
   472  		env.readOnlyDepth = env.currentStateDepth
   473  	}
   474  
   475  	if castedStateDb, ok := statedb.(*state.StateDB); ok {
   476  		env.states[env.currentStateDepth] = castedStateDb
   477  		env.currentStateDepth++
   478  	}
   479  
   480  	env.StateDB = statedb
   481  }
   482  func (env *EVM) Pop() {
   483  	env.currentStateDepth--
   484  	if env.quorumReadOnly && env.currentStateDepth == env.readOnlyDepth {
   485  		env.quorumReadOnly = false
   486  	}
   487  	env.StateDB = env.states[env.currentStateDepth-1]
   488  }
   489  
   490  func (env *EVM) Depth() int { return env.depth }
   491  
   492  // We only need to revert the current state because when we call from private
   493  // public state it's read only, there wouldn't be anything to reset.
   494  // (A)->(B)->C->(B): A failure in (B) wouldn't need to reset C, as C was flagged
   495  // read only.
   496  func (self *EVM) RevertToSnapshot(snapshot int) {
   497  	self.StateDB.RevertToSnapshot(snapshot)
   498  }