github.com/RobustRoundRobin/quorum@v20.10.0+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  	"time"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/core/state"
    26  	"github.com/ethereum/go-ethereum/core/types"
    27  	"github.com/ethereum/go-ethereum/crypto"
    28  	"github.com/ethereum/go-ethereum/log"
    29  	"github.com/ethereum/go-ethereum/params"
    30  	"github.com/ethereum/go-ethereum/trie"
    31  )
    32  
    33  // note: Quorum, States, and Value Transfer
    34  //
    35  // In Quorum there is a tricky issue in one specific case when there is call from private state to public state:
    36  // * The state db is selected based on the callee (public)
    37  // * With every call there is an associated value transfer -- in our case this is 0
    38  // * Thus, there is an implicit transfer of 0 value from the caller to callee on the public state
    39  // * However in our scenario the caller is private
    40  // * Thus, the transfer creates a ghost of the private account on the public state with no value, code, or storage
    41  //
    42  // The solution is to skip this transfer of 0 value under Quorum
    43  
    44  // emptyCodeHash is used by create to ensure deployment is disallowed to already
    45  // deployed contract addresses (relevant after the account abstraction).
    46  var emptyCodeHash = crypto.Keccak256Hash(nil)
    47  
    48  type (
    49  	// CanTransferFunc is the signature of a transfer guard function
    50  	CanTransferFunc func(StateDB, common.Address, *big.Int) bool
    51  	// TransferFunc is the signature of a transfer function
    52  	TransferFunc func(StateDB, common.Address, common.Address, *big.Int)
    53  	// GetHashFunc returns the n'th block hash in the blockchain
    54  	// and is used by the BLOCKHASH EVM op code.
    55  	GetHashFunc func(uint64) common.Hash
    56  )
    57  
    58  // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
    59  func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, error) {
    60  	if contract.CodeAddr != nil {
    61  		// Using CodeAddr is favour over contract.Address()
    62  		// During DelegateCall() CodeAddr is the address of the delegated account
    63  		address := *contract.CodeAddr
    64  		if _, ok := evm.affectedContracts[address]; !ok {
    65  			evm.affectedContracts[address] = MessageCall
    66  		}
    67  		precompiles := PrecompiledContractsHomestead
    68  		if evm.chainRules.IsByzantium {
    69  			precompiles = PrecompiledContractsByzantium
    70  		}
    71  		if evm.chainRules.IsIstanbul {
    72  			precompiles = PrecompiledContractsIstanbul
    73  		}
    74  		if p := precompiles[address]; p != nil {
    75  			return RunPrecompiledContract(p, input, contract)
    76  		}
    77  	}
    78  	for _, interpreter := range evm.interpreters {
    79  		if interpreter.CanRun(contract.Code) {
    80  			if evm.interpreter != interpreter {
    81  				// Ensure that the interpreter pointer is set back
    82  				// to its current value upon return.
    83  				defer func(i Interpreter) {
    84  					evm.interpreter = i
    85  				}(evm.interpreter)
    86  				evm.interpreter = interpreter
    87  			}
    88  			return interpreter.Run(contract, input, readOnly)
    89  		}
    90  	}
    91  	return nil, ErrNoCompatibleInterpreter
    92  }
    93  
    94  // Context provides the EVM with auxiliary information. Once provided
    95  // it shouldn't be modified.
    96  type Context struct {
    97  	// CanTransfer returns whether the account contains
    98  	// sufficient ether to transfer the value
    99  	CanTransfer CanTransferFunc
   100  	// Transfer transfers ether from one account to the other
   101  	Transfer TransferFunc
   102  	// GetHash returns the hash corresponding to n
   103  	GetHash GetHashFunc
   104  
   105  	// Message information
   106  	Origin   common.Address // Provides information for ORIGIN
   107  	GasPrice *big.Int       // Provides information for GASPRICE
   108  
   109  	// Block information
   110  	Coinbase    common.Address // Provides information for COINBASE
   111  	GasLimit    uint64         // Provides information for GASLIMIT
   112  	BlockNumber *big.Int       // Provides information for NUMBER
   113  	Time        *big.Int       // Provides information for TIME
   114  	Difficulty  *big.Int       // Provides information for DIFFICULTY
   115  }
   116  
   117  type PublicState StateDB
   118  type PrivateState StateDB
   119  
   120  // EVM is the Ethereum Virtual Machine base object and provides
   121  // the necessary tools to run a contract on the given state with
   122  // the provided context. It should be noted that any error
   123  // generated through any of the calls should be considered a
   124  // revert-state-and-consume-all-gas operation, no checks on
   125  // specific errors should ever be performed. The interpreter makes
   126  // sure that any errors generated are to be considered faulty code.
   127  //
   128  // The EVM should never be reused and is not thread safe.
   129  type EVM struct {
   130  	// Context provides auxiliary blockchain related information
   131  	Context
   132  	// StateDB gives access to the underlying state
   133  	StateDB StateDB
   134  	// Depth is the current call stack
   135  	depth int
   136  
   137  	// chainConfig contains information about the current chain
   138  	chainConfig *params.ChainConfig
   139  	// chain rules contains the chain rules for the current epoch
   140  	chainRules params.Rules
   141  	// virtual machine configuration options used to initialise the
   142  	// evm.
   143  	vmConfig Config
   144  	// global (to this context) ethereum virtual machine
   145  	// used throughout the execution of the tx.
   146  	interpreters []Interpreter
   147  	interpreter  Interpreter
   148  	// abort is used to abort the EVM calling operations
   149  	// NOTE: must be set atomically
   150  	abort int32
   151  	// callGasTemp holds the gas available for the current call. This is needed because the
   152  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   153  	// applied in opCall*.
   154  	callGasTemp uint64
   155  
   156  	// Quorum additions:
   157  	publicState       PublicState
   158  	privateState      PrivateState
   159  	states            [1027]*state.StateDB // TODO(joel) we should be able to get away with 1024 or maybe 1025
   160  	currentStateDepth uint
   161  
   162  	// This flag has different semantics from the `Interpreter:readOnly` flag (though they interact and could maybe
   163  	// be simplified). This is set by Quorum when it's inside a Private State -> Public State read.
   164  	quorumReadOnly bool
   165  	readOnlyDepth  uint
   166  
   167  	// these are for privacy enhancements
   168  	affectedContracts map[common.Address]AffectedType // affected contract account address -> type
   169  	currentTx         *types.Transaction              // transaction currently being applied on this EVM
   170  }
   171  
   172  type AffectedType byte
   173  
   174  const (
   175  	_                     = iota
   176  	Creation AffectedType = iota
   177  	MessageCall
   178  )
   179  
   180  // NewEVM returns a new EVM. The returned EVM is not thread safe and should
   181  // only ever be used *once*.
   182  func NewEVM(ctx Context, statedb, privateState StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
   183  	evm := &EVM{
   184  		Context:      ctx,
   185  		StateDB:      statedb,
   186  		vmConfig:     vmConfig,
   187  		chainConfig:  chainConfig,
   188  		chainRules:   chainConfig.Rules(ctx.BlockNumber),
   189  		interpreters: make([]Interpreter, 0, 1),
   190  
   191  		publicState:  statedb,
   192  		privateState: privateState,
   193  
   194  		affectedContracts: make(map[common.Address]AffectedType),
   195  	}
   196  
   197  	if chainConfig.IsEWASM(ctx.BlockNumber) {
   198  		// to be implemented by EVM-C and Wagon PRs.
   199  		// if vmConfig.EWASMInterpreter != "" {
   200  		//  extIntOpts := strings.Split(vmConfig.EWASMInterpreter, ":")
   201  		//  path := extIntOpts[0]
   202  		//  options := []string{}
   203  		//  if len(extIntOpts) > 1 {
   204  		//    options = extIntOpts[1..]
   205  		//  }
   206  		//  evm.interpreters = append(evm.interpreters, NewEVMVCInterpreter(evm, vmConfig, options))
   207  		// } else {
   208  		// 	evm.interpreters = append(evm.interpreters, NewEWASMInterpreter(evm, vmConfig))
   209  		// }
   210  		panic("No supported ewasm interpreter yet.")
   211  	}
   212  
   213  	evm.Push(privateState)
   214  
   215  	// vmConfig.EVMInterpreter will be used by EVM-C, it won't be checked here
   216  	// as we always want to have the built-in EVM as the failover option.
   217  	evm.interpreters = append(evm.interpreters, NewEVMInterpreter(evm, vmConfig))
   218  	evm.interpreter = evm.interpreters[0]
   219  
   220  	return evm
   221  }
   222  
   223  // Cancel cancels any running EVM operation. This may be called concurrently and
   224  // it's safe to be called multiple times.
   225  func (evm *EVM) Cancel() {
   226  	atomic.StoreInt32(&evm.abort, 1)
   227  }
   228  
   229  // Cancelled returns true if Cancel has been called
   230  func (evm *EVM) Cancelled() bool {
   231  	return atomic.LoadInt32(&evm.abort) == 1
   232  }
   233  
   234  // Interpreter returns the current interpreter
   235  func (evm *EVM) Interpreter() Interpreter {
   236  	return evm.interpreter
   237  }
   238  
   239  // Call executes the contract associated with the addr with the given input as
   240  // parameters. It also handles any necessary value transfer required and takes
   241  // the necessary steps to create accounts and reverses the state in case of an
   242  // execution error or failed value transfer.
   243  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   244  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   245  		return nil, gas, nil
   246  	}
   247  
   248  	evm.Push(getDualState(evm, addr))
   249  	defer func() { evm.Pop() }()
   250  
   251  	// Fail if we're trying to execute above the call depth limit
   252  	if evm.depth > int(params.CallCreateDepth) {
   253  		return nil, gas, ErrDepth
   254  	}
   255  	// Fail if we're trying to transfer more than the available balance
   256  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   257  		return nil, gas, ErrInsufficientBalance
   258  	}
   259  
   260  	var (
   261  		to       = AccountRef(addr)
   262  		snapshot = evm.StateDB.Snapshot()
   263  	)
   264  	if !evm.StateDB.Exist(addr) {
   265  		precompiles := PrecompiledContractsHomestead
   266  		if evm.chainRules.IsByzantium {
   267  			precompiles = PrecompiledContractsByzantium
   268  		}
   269  		if evm.chainRules.IsIstanbul {
   270  			precompiles = PrecompiledContractsIstanbul
   271  		}
   272  		if precompiles[addr] == nil && evm.chainRules.IsEIP158 && value.Sign() == 0 {
   273  			// Calling a non existing account, don't do anything, but ping the tracer
   274  			if evm.vmConfig.Debug && evm.depth == 0 {
   275  				evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   276  				evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
   277  			}
   278  			return nil, gas, nil
   279  		}
   280  		evm.StateDB.CreateAccount(addr)
   281  	}
   282  	if evm.ChainConfig().IsQuorum {
   283  		// skip transfer if value /= 0 (see note: Quorum, States, and Value Transfer)
   284  		if value.Sign() != 0 {
   285  			if evm.quorumReadOnly {
   286  				return nil, gas, ErrReadOnlyValueTransfer
   287  			}
   288  			evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   289  		}
   290  	} else {
   291  		evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   292  	}
   293  
   294  	// Initialise a new contract and set the code that is to be used by the EVM.
   295  	// The contract is a scoped environment for this execution context only.
   296  	contract := NewContract(caller, to, value, gas)
   297  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   298  
   299  	// Even if the account has no code, we need to continue because it might be a precompile
   300  	start := time.Now()
   301  
   302  	// Capture the tracer start/end events in debug mode
   303  	if evm.vmConfig.Debug && evm.depth == 0 {
   304  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   305  
   306  		defer func() { // Lazy evaluation of the parameters
   307  			evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   308  		}()
   309  	}
   310  	ret, err = run(evm, contract, input, false)
   311  
   312  	// When an error was returned by the EVM or when setting the creation code
   313  	// above we revert to the snapshot and consume any gas remaining. Additionally
   314  	// when we're in homestead this also counts for code storage gas errors.
   315  	if err != nil {
   316  		evm.StateDB.RevertToSnapshot(snapshot)
   317  		if err != errExecutionReverted {
   318  			contract.UseGas(contract.Gas)
   319  		}
   320  	}
   321  	return ret, contract.Gas, err
   322  }
   323  
   324  // CallCode executes the contract associated with the addr with the given input
   325  // as parameters. It also handles any necessary value transfer required and takes
   326  // the necessary steps to create accounts and reverses the state in case of an
   327  // execution error or failed value transfer.
   328  //
   329  // CallCode differs from Call in the sense that it executes the given address'
   330  // code with the caller as context.
   331  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   332  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   333  		return nil, gas, nil
   334  	}
   335  
   336  	evm.Push(getDualState(evm, addr))
   337  	defer func() { evm.Pop() }()
   338  
   339  	// Fail if we're trying to execute above the call depth limit
   340  	if evm.depth > int(params.CallCreateDepth) {
   341  		return nil, gas, ErrDepth
   342  	}
   343  	// Fail if we're trying to transfer more than the available balance
   344  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   345  		return nil, gas, ErrInsufficientBalance
   346  	}
   347  
   348  	var (
   349  		snapshot = evm.StateDB.Snapshot()
   350  		to       = AccountRef(caller.Address())
   351  	)
   352  	// Initialise a new contract and set the code that is to be used by the EVM.
   353  	// The contract is a scoped environment for this execution context only.
   354  	contract := NewContract(caller, to, value, gas)
   355  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   356  
   357  	ret, err = run(evm, contract, input, false)
   358  	if err != nil {
   359  		evm.StateDB.RevertToSnapshot(snapshot)
   360  		if err != errExecutionReverted {
   361  			contract.UseGas(contract.Gas)
   362  		}
   363  	}
   364  	return ret, contract.Gas, err
   365  }
   366  
   367  // DelegateCall executes the contract associated with the addr with the given input
   368  // as parameters. It reverses the state in case of an execution error.
   369  //
   370  // DelegateCall differs from CallCode in the sense that it executes the given address'
   371  // code with the caller as context and the caller is set to the caller of the caller.
   372  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   373  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   374  		return nil, gas, nil
   375  	}
   376  
   377  	evm.Push(getDualState(evm, addr))
   378  	defer func() { evm.Pop() }()
   379  
   380  	// Fail if we're trying to execute above the call depth limit
   381  	if evm.depth > int(params.CallCreateDepth) {
   382  		return nil, gas, ErrDepth
   383  	}
   384  
   385  	var (
   386  		snapshot = evm.StateDB.Snapshot()
   387  		to       = AccountRef(caller.Address())
   388  	)
   389  
   390  	// Initialise a new contract and make initialise the delegate values
   391  	contract := NewContract(caller, to, nil, gas).AsDelegate()
   392  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   393  
   394  	ret, err = run(evm, contract, input, false)
   395  	if err != nil {
   396  		evm.StateDB.RevertToSnapshot(snapshot)
   397  		if err != errExecutionReverted {
   398  			contract.UseGas(contract.Gas)
   399  		}
   400  	}
   401  	return ret, contract.Gas, err
   402  }
   403  
   404  // StaticCall executes the contract associated with the addr with the given input
   405  // as parameters while disallowing any modifications to the state during the call.
   406  // Opcodes that attempt to perform such modifications will result in exceptions
   407  // instead of performing the modifications.
   408  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   409  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   410  		return nil, gas, nil
   411  	}
   412  	// Fail if we're trying to execute above the call depth limit
   413  	if evm.depth > int(params.CallCreateDepth) {
   414  		return nil, gas, ErrDepth
   415  	}
   416  
   417  	var (
   418  		to       = AccountRef(addr)
   419  		stateDb  = getDualState(evm, addr)
   420  		snapshot = stateDb.Snapshot()
   421  	)
   422  	// Initialise a new contract and set the code that is to be used by the EVM.
   423  	// The contract is a scoped environment for this execution context only.
   424  	contract := NewContract(caller, to, new(big.Int), gas)
   425  	contract.SetCallCode(&addr, stateDb.GetCodeHash(addr), stateDb.GetCode(addr))
   426  
   427  	// We do an AddBalance of zero here, just in order to trigger a touch.
   428  	// This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium,
   429  	// but is the correct thing to do and matters on other networks, in tests, and potential
   430  	// future scenarios
   431  	stateDb.AddBalance(addr, bigZero)
   432  
   433  	// When an error was returned by the EVM or when setting the creation code
   434  	// above we revert to the snapshot and consume any gas remaining. Additionally
   435  	// when we're in Homestead this also counts for code storage gas errors.
   436  	ret, err = run(evm, contract, input, true)
   437  	if err != nil {
   438  		stateDb.RevertToSnapshot(snapshot)
   439  		if err != errExecutionReverted {
   440  			contract.UseGas(contract.Gas)
   441  		}
   442  	}
   443  	return ret, contract.Gas, err
   444  }
   445  
   446  type codeAndHash struct {
   447  	code []byte
   448  	hash common.Hash
   449  }
   450  
   451  func (c *codeAndHash) Hash() common.Hash {
   452  	if c.hash == (common.Hash{}) {
   453  		c.hash = crypto.Keccak256Hash(c.code)
   454  	}
   455  	return c.hash
   456  }
   457  
   458  // create creates a new contract using code as deployment code.
   459  func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
   460  	// Depth check execution. Fail if we're trying to execute above the
   461  	// limit.
   462  	if evm.depth > int(params.CallCreateDepth) {
   463  		return nil, common.Address{}, gas, ErrDepth
   464  	}
   465  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   466  		return nil, common.Address{}, gas, ErrInsufficientBalance
   467  	}
   468  
   469  	// Quorum
   470  	// Get the right state in case of a dual state environment. If a sender
   471  	// is a transaction (depth == 0) use the public state to derive the address
   472  	// and increment the nonce of the public state. If the sender is a contract
   473  	// (depth > 0) use the private state to derive the nonce and increment the
   474  	// nonce on the private state only.
   475  	//
   476  	// If the transaction went to a public contract the private and public state
   477  	// are the same.
   478  	var creatorStateDb StateDB
   479  	if evm.depth > 0 {
   480  		creatorStateDb = evm.privateState
   481  	} else {
   482  		creatorStateDb = evm.publicState
   483  	}
   484  
   485  	nonce := creatorStateDb.GetNonce(caller.Address())
   486  	creatorStateDb.SetNonce(caller.Address(), nonce+1)
   487  
   488  	// Ensure there's no existing contract already at the designated address
   489  	contractHash := evm.StateDB.GetCodeHash(address)
   490  	if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   491  		return nil, common.Address{}, 0, ErrContractAddressCollision
   492  	}
   493  	// Create a new account on the state
   494  	snapshot := evm.StateDB.Snapshot()
   495  	evm.StateDB.CreateAccount(address)
   496  	evm.affectedContracts[address] = Creation
   497  	if evm.chainRules.IsEIP158 {
   498  		evm.StateDB.SetNonce(address, 1)
   499  	}
   500  	if nil != evm.currentTx && evm.currentTx.IsPrivate() && evm.currentTx.PrivacyMetadata() != nil {
   501  		// for calls (reading contract state) or finding the affected contracts there is no transaction
   502  		if evm.currentTx.PrivacyMetadata().PrivacyFlag.IsNotStandardPrivate() {
   503  			pm := state.NewStatePrivacyMetadata(common.BytesToEncryptedPayloadHash(evm.currentTx.Data()), evm.currentTx.PrivacyMetadata().PrivacyFlag)
   504  			evm.StateDB.SetStatePrivacyMetadata(address, pm)
   505  			log.Trace("Set Privacy Metadata", "key", address, "privacyMetadata", pm)
   506  		}
   507  	}
   508  	if evm.ChainConfig().IsQuorum {
   509  		// skip transfer if value /= 0 (see note: Quorum, States, and Value Transfer)
   510  		if value.Sign() != 0 {
   511  			if evm.quorumReadOnly {
   512  				return nil, common.Address{}, gas, ErrReadOnlyValueTransfer
   513  			}
   514  			evm.Transfer(evm.StateDB, caller.Address(), address, value)
   515  		}
   516  	} else {
   517  		evm.Transfer(evm.StateDB, caller.Address(), address, value)
   518  	}
   519  
   520  	// Initialise a new contract and set the code that is to be used by the EVM.
   521  	// The contract is a scoped environment for this execution context only.
   522  	contract := NewContract(caller, AccountRef(address), value, gas)
   523  	contract.SetCodeOptionalHash(&address, codeAndHash)
   524  
   525  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   526  		return nil, address, gas, nil
   527  	}
   528  
   529  	if evm.vmConfig.Debug && evm.depth == 0 {
   530  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value)
   531  	}
   532  	start := time.Now()
   533  
   534  	ret, err := run(evm, contract, nil, false)
   535  
   536  	maxCodeSize := evm.ChainConfig().GetMaxCodeSize(evm.BlockNumber)
   537  	// check whether the max code size has been exceeded, check maxcode size from chain config
   538  	maxCodeSizeExceeded := evm.chainRules.IsEIP158 && len(ret) > maxCodeSize
   539  	// if the contract creation ran successfully and no errors were returned
   540  	// calculate the gas required to store the code. If the code could not
   541  	// be stored due to not enough gas set an error and let it be handled
   542  	// by the error checking condition below.
   543  	if err == nil && !maxCodeSizeExceeded {
   544  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   545  		if contract.UseGas(createDataGas) {
   546  			evm.StateDB.SetCode(address, ret)
   547  		} else {
   548  			err = ErrCodeStoreOutOfGas
   549  		}
   550  	}
   551  
   552  	// When an error was returned by the EVM or when setting the creation code
   553  	// above we revert to the snapshot and consume any gas remaining. Additionally
   554  	// when we're in homestead this also counts for code storage gas errors.
   555  	if maxCodeSizeExceeded || (err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas)) {
   556  		evm.StateDB.RevertToSnapshot(snapshot)
   557  		if err != errExecutionReverted {
   558  			contract.UseGas(contract.Gas)
   559  		}
   560  	}
   561  	// Assign err if contract code size exceeds the max while the err is still empty.
   562  	if maxCodeSizeExceeded && err == nil {
   563  		err = errMaxCodeSizeExceeded
   564  	}
   565  	if evm.vmConfig.Debug && evm.depth == 0 {
   566  		evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   567  	}
   568  	return ret, address, contract.Gas, err
   569  
   570  }
   571  
   572  // Create creates a new contract using code as deployment code.
   573  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   574  	// Quorum
   575  	// Get the right state in case of a dual state environment. If a sender
   576  	// is a transaction (depth == 0) use the public state to derive the address
   577  	// and increment the nonce of the public state. If the sender is a contract
   578  	// (depth > 0) use the private state to derive the nonce and increment the
   579  	// nonce on the private state only.
   580  	//
   581  	// If the transaction went to a public contract the private and public state
   582  	// are the same.
   583  	var creatorStateDb StateDB
   584  	if evm.depth > 0 {
   585  		creatorStateDb = evm.privateState
   586  	} else {
   587  		creatorStateDb = evm.publicState
   588  	}
   589  
   590  	// Ensure there's no existing contract already at the designated address
   591  	nonce := creatorStateDb.GetNonce(caller.Address())
   592  	contractAddr = crypto.CreateAddress(caller.Address(), nonce)
   593  	return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
   594  }
   595  
   596  // Create2 creates a new contract using code as deployment code.
   597  //
   598  // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
   599  // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
   600  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) {
   601  	codeAndHash := &codeAndHash{code: code}
   602  	contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), codeAndHash.Hash().Bytes())
   603  	return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
   604  }
   605  
   606  // ChainConfig returns the environment's chain configuration
   607  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }
   608  
   609  // Quorum functions for dual state
   610  func getDualState(env *EVM, addr common.Address) StateDB {
   611  	// priv: (a) -> (b)  (private)
   612  	// pub:   a  -> [b]  (private -> public)
   613  	// priv: (a) ->  b   (public)
   614  	state := env.StateDB
   615  
   616  	if env.PrivateState().Exist(addr) {
   617  		state = env.PrivateState()
   618  	} else if env.PublicState().Exist(addr) {
   619  		state = env.PublicState()
   620  	}
   621  
   622  	return state
   623  }
   624  
   625  func (env *EVM) PublicState() PublicState           { return env.publicState }
   626  func (env *EVM) PrivateState() PrivateState         { return env.privateState }
   627  func (env *EVM) SetCurrentTX(tx *types.Transaction) { env.currentTx = tx }
   628  func (env *EVM) SetTxPrivacyMetadata(pm *types.PrivacyMetadata) {
   629  	env.currentTx.SetTxPrivacyMetadata(pm)
   630  }
   631  func (env *EVM) Push(statedb StateDB) {
   632  	// Quorum : the read only depth to be set up only once for the entire
   633  	// op code execution. This will be set first time transition from
   634  	// private state to public state happens
   635  	// statedb will be the state of the contract being called.
   636  	// if a private contract is calling a public contract make it readonly.
   637  	if !env.quorumReadOnly && env.privateState != statedb {
   638  		env.quorumReadOnly = true
   639  		env.readOnlyDepth = env.currentStateDepth
   640  	}
   641  
   642  	if castedStateDb, ok := statedb.(*state.StateDB); ok {
   643  		env.states[env.currentStateDepth] = castedStateDb
   644  		env.currentStateDepth++
   645  	}
   646  
   647  	env.StateDB = statedb
   648  }
   649  func (env *EVM) Pop() {
   650  	env.currentStateDepth--
   651  	if env.quorumReadOnly && env.currentStateDepth == env.readOnlyDepth {
   652  		env.quorumReadOnly = false
   653  	}
   654  	env.StateDB = env.states[env.currentStateDepth-1]
   655  }
   656  
   657  func (env *EVM) Depth() int { return env.depth }
   658  
   659  // We only need to revert the current state because when we call from private
   660  // public state it's read only, there wouldn't be anything to reset.
   661  // (A)->(B)->C->(B): A failure in (B) wouldn't need to reset C, as C was flagged
   662  // read only.
   663  func (self *EVM) RevertToSnapshot(snapshot int) {
   664  	self.StateDB.RevertToSnapshot(snapshot)
   665  }
   666  
   667  // Returns all affected contracts that are NOT due to creation transaction
   668  func (evm *EVM) AffectedContracts() []common.Address {
   669  	addr := make([]common.Address, 0, len(evm.affectedContracts))
   670  	for a, t := range evm.affectedContracts {
   671  		if t == MessageCall {
   672  			addr = append(addr, a)
   673  		}
   674  	}
   675  	return addr[:]
   676  }
   677  
   678  func (evm *EVM) CreatedContracts() []common.Address {
   679  	addr := make([]common.Address, 0, len(evm.affectedContracts))
   680  	for a, t := range evm.affectedContracts {
   681  		if t == Creation {
   682  			addr = append(addr, a)
   683  		}
   684  	}
   685  	return addr[:]
   686  }
   687  
   688  // Return MerkleRoot of all affected contracts (due to both creation and message call)
   689  func (evm *EVM) CalculateMerkleRoot() (common.Hash, error) {
   690  	combined := new(trie.Trie)
   691  	for addr := range evm.affectedContracts {
   692  		data, err := getDualState(evm, addr).GetRLPEncodedStateObject(addr)
   693  		if err != nil {
   694  			return common.Hash{}, err
   695  		}
   696  		if err := combined.TryUpdate(addr.Bytes(), data); err != nil {
   697  			return common.Hash{}, err
   698  		}
   699  	}
   700  	return combined.Hash(), nil
   701  }