github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/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  	"bytes"
    21  	"fmt"
    22  	"math/big"
    23  	"sync/atomic"
    24  	"time"
    25  
    26  	"github.com/ethereum-optimism/optimism/l2geth/statedumper"
    27  
    28  	"github.com/ethereum-optimism/optimism/l2geth/common"
    29  	"github.com/ethereum-optimism/optimism/l2geth/crypto"
    30  	"github.com/ethereum-optimism/optimism/l2geth/params"
    31  	"github.com/ethereum-optimism/optimism/l2geth/rollup/dump"
    32  	"github.com/ethereum-optimism/optimism/l2geth/rollup/rcfg"
    33  	"github.com/ethereum-optimism/optimism/l2geth/rollup/util"
    34  	"golang.org/x/crypto/sha3"
    35  )
    36  
    37  // emptyCodeHash is used by create to ensure deployment is disallowed to already
    38  // deployed contract addresses (relevant after the account abstraction).
    39  var emptyCodeHash = crypto.Keccak256Hash(nil)
    40  
    41  // mintSigHash is the function signature of mint(address,uint256)
    42  var mintSigHash = common.FromHex("0x40c10f19")
    43  
    44  type (
    45  	// CanTransferFunc is the signature of a transfer guard function
    46  	CanTransferFunc func(StateDB, common.Address, *big.Int) bool
    47  	// TransferFunc is the signature of a transfer function
    48  	TransferFunc func(StateDB, common.Address, common.Address, *big.Int)
    49  	// GetHashFunc returns the n'th block hash in the blockchain
    50  	// and is used by the BLOCKHASH EVM op code.
    51  	GetHashFunc func(uint64) common.Hash
    52  )
    53  
    54  // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
    55  func run(evm *EVM, contract *Contract, input []byte, readOnly bool) ([]byte, error) {
    56  	if contract.CodeAddr != nil {
    57  		precompiles := PrecompiledContractsHomestead
    58  		if evm.chainRules.IsByzantium {
    59  			precompiles = PrecompiledContractsByzantium
    60  		}
    61  		if evm.chainRules.IsIstanbul {
    62  			precompiles = PrecompiledContractsIstanbul
    63  		}
    64  		if evm.chainRules.IsBerlin {
    65  			precompiles = PrecompiledContractsBerlin
    66  		}
    67  		if p := precompiles[*contract.CodeAddr]; p != nil {
    68  			return RunPrecompiledContract(p, input, contract)
    69  		}
    70  	}
    71  	for _, interpreter := range evm.interpreters {
    72  		if interpreter.CanRun(contract.Code) {
    73  			if evm.interpreter != interpreter {
    74  				// Ensure that the interpreter pointer is set back
    75  				// to its current value upon return.
    76  				defer func(i Interpreter) {
    77  					evm.interpreter = i
    78  				}(evm.interpreter)
    79  				evm.interpreter = interpreter
    80  			}
    81  			return interpreter.Run(contract, input, readOnly)
    82  		}
    83  	}
    84  	return nil, ErrNoCompatibleInterpreter
    85  }
    86  
    87  // Context provides the EVM with auxiliary information. Once provided
    88  // it shouldn't be modified.
    89  type Context struct {
    90  	// CanTransfer returns whether the account contains
    91  	// sufficient ether to transfer the value
    92  	CanTransfer CanTransferFunc
    93  	// Transfer transfers ether from one account to the other
    94  	Transfer TransferFunc
    95  	// GetHash returns the hash corresponding to n
    96  	GetHash GetHashFunc
    97  
    98  	// Message information
    99  	Origin   common.Address // Provides information for ORIGIN
   100  	GasPrice *big.Int       // Provides information for GASPRICE
   101  
   102  	// Block information
   103  	Coinbase    common.Address // Provides information for COINBASE
   104  	GasLimit    uint64         // Provides information for GASLIMIT
   105  	BlockNumber *big.Int       // Provides information for NUMBER
   106  	Time        *big.Int       // Provides information for TIME
   107  	Difficulty  *big.Int       // Provides information for DIFFICULTY
   108  
   109  	// OVM information
   110  	L1BlockNumber *big.Int // Provides information for L1BLOCKNUMBER
   111  }
   112  
   113  // EVM is the Ethereum Virtual Machine base object and provides
   114  // the necessary tools to run a contract on the given state with
   115  // the provided context. It should be noted that any error
   116  // generated through any of the calls should be considered a
   117  // revert-state-and-consume-all-gas operation, no checks on
   118  // specific errors should ever be performed. The interpreter makes
   119  // sure that any errors generated are to be considered faulty code.
   120  //
   121  // The EVM should never be reused and is not thread safe.
   122  type EVM struct {
   123  	// Context provides auxiliary blockchain related information
   124  	Context
   125  	// StateDB gives access to the underlying state
   126  	StateDB StateDB
   127  	// Depth is the current call stack
   128  	depth int
   129  
   130  	// chainConfig contains information about the current chain
   131  	chainConfig *params.ChainConfig
   132  	// chain rules contains the chain rules for the current epoch
   133  	chainRules params.Rules
   134  	// virtual machine configuration options used to initialise the
   135  	// evm.
   136  	vmConfig Config
   137  	// global (to this context) ethereum virtual machine
   138  	// used throughout the execution of the tx.
   139  	interpreters []Interpreter
   140  	interpreter  Interpreter
   141  	// abort is used to abort the EVM calling operations
   142  	// NOTE: must be set atomically
   143  	abort int32
   144  	// callGasTemp holds the gas available for the current call. This is needed because the
   145  	// available gas is calculated in gasCall* according to the 63/64 rule and later
   146  	// applied in opCall*.
   147  	callGasTemp uint64
   148  }
   149  
   150  // NewEVM returns a new EVM. The returned EVM is not thread safe and should
   151  // only ever be used *once*.
   152  func NewEVM(ctx Context, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
   153  	evm := &EVM{
   154  		Context:      ctx,
   155  		StateDB:      statedb,
   156  		vmConfig:     vmConfig,
   157  		chainConfig:  chainConfig,
   158  		chainRules:   chainConfig.Rules(ctx.BlockNumber),
   159  		interpreters: make([]Interpreter, 0, 1),
   160  	}
   161  
   162  	if chainConfig.IsEWASM(ctx.BlockNumber) {
   163  		// to be implemented by EVM-C and Wagon PRs.
   164  		// if vmConfig.EWASMInterpreter != "" {
   165  		//  extIntOpts := strings.Split(vmConfig.EWASMInterpreter, ":")
   166  		//  path := extIntOpts[0]
   167  		//  options := []string{}
   168  		//  if len(extIntOpts) > 1 {
   169  		//    options = extIntOpts[1..]
   170  		//  }
   171  		//  evm.interpreters = append(evm.interpreters, NewEVMVCInterpreter(evm, vmConfig, options))
   172  		// } else {
   173  		// 	evm.interpreters = append(evm.interpreters, NewEWASMInterpreter(evm, vmConfig))
   174  		// }
   175  		panic("No supported ewasm interpreter yet.")
   176  	}
   177  
   178  	// vmConfig.EVMInterpreter will be used by EVM-C, it won't be checked here
   179  	// as we always want to have the built-in EVM as the failover option.
   180  	evm.interpreters = append(evm.interpreters, NewEVMInterpreter(evm, vmConfig))
   181  	evm.interpreter = evm.interpreters[0]
   182  
   183  	return evm
   184  }
   185  
   186  // Cancel cancels any running EVM operation. This may be called concurrently and
   187  // it's safe to be called multiple times.
   188  func (evm *EVM) Cancel() {
   189  	atomic.StoreInt32(&evm.abort, 1)
   190  }
   191  
   192  // Cancelled returns true if Cancel has been called
   193  func (evm *EVM) Cancelled() bool {
   194  	return atomic.LoadInt32(&evm.abort) == 1
   195  }
   196  
   197  // Interpreter returns the current interpreter
   198  func (evm *EVM) Interpreter() Interpreter {
   199  	return evm.interpreter
   200  }
   201  
   202  // Call executes the contract associated with the addr with the given input as
   203  // parameters. It also handles any necessary value transfer required and takes
   204  // the necessary steps to create accounts and reverses the state in case of an
   205  // execution error or failed value transfer.
   206  func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   207  	if addr == dump.MessagePasserAddress {
   208  		statedumper.WriteMessage(caller.Address(), input)
   209  	}
   210  
   211  	if addr == dump.OvmEthAddress {
   212  		// We need at least 4 bytes + 32 bytes for the recipient address, then
   213  		// address will be found at bytes 16-36. 0x40c10f19 is the function
   214  		// selector for mint(address,uint256).
   215  		if len(input) >= 36 && bytes.Equal(input[:4], mintSigHash) {
   216  			recipient := common.BytesToAddress(input[16:36])
   217  			statedumper.WriteETH(recipient)
   218  		}
   219  	}
   220  
   221  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   222  		return nil, gas, nil
   223  	}
   224  
   225  	// Fail if we're trying to execute above the call depth limit
   226  	if evm.depth > int(params.CallCreateDepth) {
   227  		return nil, gas, ErrDepth
   228  	}
   229  	// Fail if we're trying to transfer more than the available balance
   230  	if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
   231  		return nil, gas, ErrInsufficientBalance
   232  	}
   233  
   234  	var (
   235  		to       = AccountRef(addr)
   236  		snapshot = evm.StateDB.Snapshot()
   237  	)
   238  	if !evm.StateDB.Exist(addr) {
   239  		precompiles := PrecompiledContractsHomestead
   240  		if evm.chainRules.IsByzantium {
   241  			precompiles = PrecompiledContractsByzantium
   242  		}
   243  		if evm.chainRules.IsIstanbul {
   244  			precompiles = PrecompiledContractsIstanbul
   245  		}
   246  		if evm.chainRules.IsBerlin {
   247  			precompiles = PrecompiledContractsBerlin
   248  		}
   249  		if precompiles[addr] == nil && evm.chainRules.IsEIP158 && value.Sign() == 0 {
   250  			// Calling a non existing account, don't do anything, but ping the tracer
   251  			if evm.vmConfig.Debug && evm.depth == 0 {
   252  				evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   253  				evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
   254  			}
   255  			return nil, gas, nil
   256  		}
   257  		evm.StateDB.CreateAccount(addr)
   258  	}
   259  	evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
   260  	// Initialise a new contract and set the code that is to be used by the EVM.
   261  	// The contract is a scoped environment for this execution context only.
   262  	contract := NewContract(caller, to, value, gas)
   263  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   264  
   265  	// Even if the account has no code, we need to continue because it might be a precompile
   266  	start := time.Now()
   267  
   268  	// Capture the tracer start/end events in debug mode
   269  	if evm.vmConfig.Debug && evm.depth == 0 {
   270  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
   271  
   272  		defer func() { // Lazy evaluation of the parameters
   273  			evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   274  		}()
   275  	}
   276  	ret, err = run(evm, contract, input, false)
   277  
   278  	// When an error was returned by the EVM or when setting the creation code
   279  	// above we revert to the snapshot and consume any gas remaining. Additionally
   280  	// when we're in homestead this also counts for code storage gas errors.
   281  	if err != nil {
   282  		evm.StateDB.RevertToSnapshot(snapshot)
   283  		if err != errExecutionReverted {
   284  			contract.UseGas(contract.Gas)
   285  		}
   286  	}
   287  	return ret, contract.Gas, err
   288  }
   289  
   290  // CallCode executes the contract associated with the addr with the given input
   291  // as parameters. It also handles any necessary value transfer required and takes
   292  // the necessary steps to create accounts and reverses the state in case of an
   293  // execution error or failed value transfer.
   294  //
   295  // CallCode differs from Call in the sense that it executes the given address'
   296  // code with the caller as context.
   297  func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
   298  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   299  		return nil, gas, nil
   300  	}
   301  
   302  	// Fail if we're trying to execute above the call depth limit
   303  	if evm.depth > int(params.CallCreateDepth) {
   304  		return nil, gas, ErrDepth
   305  	}
   306  	// Fail if we're trying to transfer more than the available balance
   307  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   308  		return nil, gas, ErrInsufficientBalance
   309  	}
   310  
   311  	var (
   312  		snapshot = evm.StateDB.Snapshot()
   313  		to       = AccountRef(caller.Address())
   314  	)
   315  	// Initialise a new contract and set the code that is to be used by the EVM.
   316  	// The contract is a scoped environment for this execution context only.
   317  	contract := NewContract(caller, to, value, gas)
   318  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   319  
   320  	ret, err = run(evm, contract, input, false)
   321  	if err != nil {
   322  		evm.StateDB.RevertToSnapshot(snapshot)
   323  		if err != errExecutionReverted {
   324  			contract.UseGas(contract.Gas)
   325  		}
   326  	}
   327  	return ret, contract.Gas, err
   328  }
   329  
   330  // DelegateCall executes the contract associated with the addr with the given input
   331  // as parameters. It reverses the state in case of an execution error.
   332  //
   333  // DelegateCall differs from CallCode in the sense that it executes the given address'
   334  // code with the caller as context and the caller is set to the caller of the caller.
   335  func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   336  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   337  		return nil, gas, nil
   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  
   344  	var (
   345  		snapshot = evm.StateDB.Snapshot()
   346  		to       = AccountRef(caller.Address())
   347  	)
   348  
   349  	// Initialise a new contract and make initialise the delegate values
   350  	contract := NewContract(caller, to, nil, gas).AsDelegate()
   351  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   352  
   353  	ret, err = run(evm, contract, input, false)
   354  	if err != nil {
   355  		evm.StateDB.RevertToSnapshot(snapshot)
   356  		if err != errExecutionReverted {
   357  			contract.UseGas(contract.Gas)
   358  		}
   359  	}
   360  	return ret, contract.Gas, err
   361  }
   362  
   363  // StaticCall executes the contract associated with the addr with the given input
   364  // as parameters while disallowing any modifications to the state during the call.
   365  // Opcodes that attempt to perform such modifications will result in exceptions
   366  // instead of performing the modifications.
   367  func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
   368  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   369  		return nil, gas, nil
   370  	}
   371  	// Fail if we're trying to execute above the call depth limit
   372  	if evm.depth > int(params.CallCreateDepth) {
   373  		return nil, gas, ErrDepth
   374  	}
   375  
   376  	var (
   377  		to       = AccountRef(addr)
   378  		snapshot = evm.StateDB.Snapshot()
   379  	)
   380  	// Initialise a new contract and set the code that is to be used by the EVM.
   381  	// The contract is a scoped environment for this execution context only.
   382  	contract := NewContract(caller, to, new(big.Int), gas)
   383  	contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
   384  
   385  	// We do an AddBalance of zero here, just in order to trigger a touch.
   386  	// This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium,
   387  	// but is the correct thing to do and matters on other networks, in tests, and potential
   388  	// future scenarios
   389  	evm.StateDB.AddBalance(addr, bigZero)
   390  
   391  	// When an error was returned by the EVM or when setting the creation code
   392  	// above we revert to the snapshot and consume any gas remaining. Additionally
   393  	// when we're in Homestead this also counts for code storage gas errors.
   394  	ret, err = run(evm, contract, input, true)
   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  type codeAndHash struct {
   405  	code []byte
   406  	hash common.Hash
   407  }
   408  
   409  func (c *codeAndHash) Hash() common.Hash {
   410  	if c.hash == (common.Hash{}) {
   411  		c.hash = crypto.Keccak256Hash(c.code)
   412  	}
   413  	return c.hash
   414  }
   415  
   416  // create creates a new contract using code as deployment code.
   417  func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
   418  	// Depth check execution. Fail if we're trying to execute above the
   419  	// limit.
   420  	if evm.depth > int(params.CallCreateDepth) {
   421  		return nil, common.Address{}, gas, ErrDepth
   422  	}
   423  	if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
   424  		return nil, common.Address{}, gas, ErrInsufficientBalance
   425  	}
   426  	if rcfg.UsingOVM {
   427  		// Make sure the creator address should be able to deploy.
   428  		if !evm.AddressWhitelisted(caller.Address()) {
   429  			// Try to encode this error as a Solidity error message so it's more clear to end-users
   430  			// what's going on when a contract creation fails.
   431  			solerr := fmt.Errorf("deployer address not whitelisted: %s", caller.Address().Hex())
   432  			ret, err := util.EncodeSolidityError(solerr)
   433  			if err != nil {
   434  				// If we're unable to properly encode the error then just return the original message.
   435  				return nil, common.Address{}, gas, solerr
   436  			}
   437  			return ret, common.Address{}, gas, errExecutionReverted
   438  		}
   439  
   440  		// Get the system address for this caller.
   441  		sysAddr := rcfg.SystemAddressFor(evm.ChainConfig().ChainID, caller.Address())
   442  
   443  		// If there is a configured system address for this caller, and the caller's nonce is zero,
   444  		// and there is no contract already deployed at this system address, then set the created
   445  		// address to the system address.
   446  		if sysAddr != rcfg.ZeroSystemAddress && evm.StateDB.GetNonce(caller.Address()) == 0 {
   447  			address = sysAddr
   448  		}
   449  	}
   450  	nonce := evm.StateDB.GetNonce(caller.Address())
   451  	evm.StateDB.SetNonce(caller.Address(), nonce+1)
   452  	// We add this to the access list _before_ taking a snapshot. Even if the creation fails,
   453  	// the access-list change should not be rolled back
   454  	if evm.chainRules.IsBerlin {
   455  		evm.StateDB.AddAddressToAccessList(address)
   456  	}
   457  	// Ensure there's no existing contract already at the designated address
   458  	contractHash := evm.StateDB.GetCodeHash(address)
   459  	if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
   460  		return nil, common.Address{}, 0, ErrContractAddressCollision
   461  	}
   462  	// Create a new account on the state
   463  	snapshot := evm.StateDB.Snapshot()
   464  	evm.StateDB.CreateAccount(address)
   465  	if evm.chainRules.IsEIP158 {
   466  		evm.StateDB.SetNonce(address, 1)
   467  	}
   468  	evm.Transfer(evm.StateDB, caller.Address(), address, value)
   469  
   470  	// Initialise a new contract and set the code that is to be used by the EVM.
   471  	// The contract is a scoped environment for this execution context only.
   472  	contract := NewContract(caller, AccountRef(address), value, gas)
   473  	contract.SetCodeOptionalHash(&address, codeAndHash)
   474  
   475  	if evm.vmConfig.NoRecursion && evm.depth > 0 {
   476  		return nil, address, gas, nil
   477  	}
   478  
   479  	if evm.vmConfig.Debug && evm.depth == 0 {
   480  		evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value)
   481  	}
   482  	start := time.Now()
   483  
   484  	ret, err := run(evm, contract, nil, false)
   485  
   486  	// check whether the max code size has been exceeded
   487  	maxCodeSizeExceeded := evm.chainRules.IsEIP158 && len(ret) > params.MaxCodeSize
   488  	// if the contract creation ran successfully and no errors were returned
   489  	// calculate the gas required to store the code. If the code could not
   490  	// be stored due to not enough gas set an error and let it be handled
   491  	// by the error checking condition below.
   492  	if err == nil && !maxCodeSizeExceeded {
   493  		createDataGas := uint64(len(ret)) * params.CreateDataGas
   494  		if contract.UseGas(createDataGas) {
   495  			evm.StateDB.SetCode(address, ret)
   496  		} else {
   497  			err = ErrCodeStoreOutOfGas
   498  		}
   499  	}
   500  
   501  	// When an error was returned by the EVM or when setting the creation code
   502  	// above we revert to the snapshot and consume any gas remaining. Additionally
   503  	// when we're in homestead this also counts for code storage gas errors.
   504  	if maxCodeSizeExceeded || (err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas)) {
   505  		evm.StateDB.RevertToSnapshot(snapshot)
   506  		if err != errExecutionReverted {
   507  			contract.UseGas(contract.Gas)
   508  		}
   509  	}
   510  	// Assign err if contract code size exceeds the max while the err is still empty.
   511  	if maxCodeSizeExceeded && err == nil {
   512  		err = errMaxCodeSizeExceeded
   513  	}
   514  	if evm.vmConfig.Debug && evm.depth == 0 {
   515  		evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
   516  	}
   517  	return ret, address, contract.Gas, err
   518  
   519  }
   520  
   521  // Create creates a new contract using code as deployment code.
   522  func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
   523  	contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
   524  	return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
   525  }
   526  
   527  // Create2 creates a new contract using code as deployment code.
   528  //
   529  // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
   530  // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
   531  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) {
   532  	codeAndHash := &codeAndHash{code: code}
   533  	contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), codeAndHash.Hash().Bytes())
   534  	return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
   535  }
   536  
   537  // ChainConfig returns the environment's chain configuration
   538  func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }
   539  
   540  func (evm *EVM) AddressWhitelisted(addr common.Address) bool {
   541  	// First check if the owner is address(0), which implicitly disables the whitelist.
   542  	ownerKey := common.Hash{}
   543  	owner := evm.StateDB.GetState(dump.OvmWhitelistAddress, ownerKey)
   544  	if (owner == common.Hash{}) {
   545  		return true
   546  	}
   547  
   548  	// Next check if the user is whitelisted by resolving the position where the
   549  	// true/false value would be.
   550  	position := common.Big1
   551  	hasher := sha3.NewLegacyKeccak256()
   552  	hasher.Write(common.LeftPadBytes(addr.Bytes(), 32))
   553  	hasher.Write(common.LeftPadBytes(position.Bytes(), 32))
   554  	digest := hasher.Sum(nil)
   555  	key := common.BytesToHash(digest)
   556  	isWhitelisted := evm.StateDB.GetState(dump.OvmWhitelistAddress, key)
   557  	return isWhitelisted != common.Hash{}
   558  }