gitlab.com/flarenetwork/coreth@v0.1.1/core/vm/interpreter.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2014 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package vm
    28  
    29  import (
    30  	"hash"
    31  	"sync/atomic"
    32  
    33  	"github.com/ethereum/go-ethereum/common"
    34  	"github.com/ethereum/go-ethereum/common/math"
    35  	"github.com/ethereum/go-ethereum/log"
    36  )
    37  
    38  var (
    39  	BuiltinAddr = common.Address{
    40  		1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    41  		0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    42  	}
    43  )
    44  
    45  // Config are the configuration options for the Interpreter
    46  type Config struct {
    47  	Debug                   bool   // Enables debugging
    48  	Tracer                  Tracer // Opcode logger
    49  	NoRecursion             bool   // Disables call, callcode, delegate call and create
    50  	NoBaseFee               bool   // Forces the EIP-1559 baseFee to 0 (needed for 0 price calls)
    51  	EnablePreimageRecording bool   // Enables recording of SHA3/keccak preimages
    52  
    53  	JumpTable [256]*operation // EVM instruction table, automatically populated if unset
    54  
    55  	ExtraEips []int // Additional EIPS that are to be enabled
    56  
    57  	// AllowUnfinalizedQueries allow unfinalized queries
    58  	AllowUnfinalizedQueries bool
    59  }
    60  
    61  // ScopeContext contains the things that are per-call, such as stack and memory,
    62  // but not transients like pc and gas
    63  type ScopeContext struct {
    64  	Memory   *Memory
    65  	Stack    *Stack
    66  	Contract *Contract
    67  }
    68  
    69  // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports
    70  // Read to get a variable amount of data from the hash state. Read is faster than Sum
    71  // because it doesn't copy the internal state, but also modifies the internal state.
    72  type keccakState interface {
    73  	hash.Hash
    74  	Read([]byte) (int, error)
    75  }
    76  
    77  // EVMInterpreter represents an EVM interpreter
    78  type EVMInterpreter struct {
    79  	evm *EVM
    80  	cfg Config
    81  
    82  	hasher    keccakState // Keccak256 hasher instance shared across opcodes
    83  	hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes
    84  
    85  	readOnly   bool   // Whether to throw on stateful modifications
    86  	returnData []byte // Last CALL's return data for subsequent reuse
    87  }
    88  
    89  // NewEVMInterpreter returns a new instance of the Interpreter.
    90  func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
    91  	// We use the STOP instruction whether to see
    92  	// the jump table was initialised. If it was not
    93  	// we'll set the default jump table.
    94  	if cfg.JumpTable[STOP] == nil {
    95  		var jt JumpTable
    96  		switch {
    97  		case evm.chainRules.IsApricotPhase3:
    98  			jt = apricotPhase3InstructionSet
    99  		case evm.chainRules.IsApricotPhase2:
   100  			jt = apricotPhase2InstructionSet
   101  		case evm.chainRules.IsApricotPhase1:
   102  			jt = apricotPhase1InstructionSet
   103  		case evm.chainRules.IsIstanbul:
   104  			jt = istanbulInstructionSet
   105  		case evm.chainRules.IsConstantinople:
   106  			jt = constantinopleInstructionSet
   107  		case evm.chainRules.IsByzantium:
   108  			jt = byzantiumInstructionSet
   109  		case evm.chainRules.IsEIP158:
   110  			jt = spuriousDragonInstructionSet
   111  		case evm.chainRules.IsEIP150:
   112  			jt = tangerineWhistleInstructionSet
   113  		case evm.chainRules.IsHomestead:
   114  			jt = homesteadInstructionSet
   115  		default:
   116  			jt = frontierInstructionSet
   117  		}
   118  		for i, eip := range cfg.ExtraEips {
   119  			if err := EnableEIP(eip, &jt); err != nil {
   120  				// Disable it, so caller can check if it's activated or not
   121  				cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...)
   122  				log.Error("EIP activation failed", "eip", eip, "error", err)
   123  			}
   124  		}
   125  		cfg.JumpTable = jt
   126  	}
   127  
   128  	return &EVMInterpreter{
   129  		evm: evm,
   130  		cfg: cfg,
   131  	}
   132  }
   133  
   134  // Run loops and evaluates the contract's code with the given input data and returns
   135  // the return byte-slice and an error if one occurred.
   136  //
   137  // It's important to note that any errors returned by the interpreter should be
   138  // considered a revert-and-consume-all-gas operation except for
   139  // ErrExecutionReverted which means revert-and-keep-gas-left.
   140  func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
   141  	if contract.Address() == BuiltinAddr {
   142  		self := AccountRef(contract.Caller())
   143  		if _, ok := contract.caller.(*Contract); ok {
   144  			contract = contract.AsDelegate()
   145  		}
   146  		contract.self = self
   147  	}
   148  
   149  	// Increment the call depth which is restricted to 1024
   150  	in.evm.depth++
   151  	defer func() { in.evm.depth-- }()
   152  
   153  	// Make sure the readOnly is only set if we aren't in readOnly yet.
   154  	// This also makes sure that the readOnly flag isn't removed for child calls.
   155  	if readOnly && !in.readOnly {
   156  		in.readOnly = true
   157  		defer func() { in.readOnly = false }()
   158  	}
   159  
   160  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
   161  	// as every returning call will return new data anyway.
   162  	in.returnData = nil
   163  
   164  	// Don't bother with the execution if there's no code.
   165  	// Note: this avoids invoking the tracer in any way for simple value
   166  	// transfers to EOA accounts.
   167  	if len(contract.Code) == 0 {
   168  		return nil, nil
   169  	}
   170  
   171  	var (
   172  		op          OpCode        // current opcode
   173  		mem         = NewMemory() // bound memory
   174  		stack       = newstack()  // local stack
   175  		callContext = &ScopeContext{
   176  			Memory:   mem,
   177  			Stack:    stack,
   178  			Contract: contract,
   179  		}
   180  		// For optimisation reason we're using uint64 as the program counter.
   181  		// It's theoretically possible to go above 2^64. The YP defines the PC
   182  		// to be uint256. Practically much less so feasible.
   183  		pc   = uint64(0) // program counter
   184  		cost uint64
   185  		// copies used by tracer
   186  		pcCopy  uint64 // needed for the deferred Tracer
   187  		gasCopy uint64 // for Tracer to log gas remaining before execution
   188  		logged  bool   // deferred Tracer should ignore already logged steps
   189  		res     []byte // result of the opcode execution function
   190  	)
   191  
   192  	// Don't move this deferrred function, it's placed before the capturestate-deferred method,
   193  	// so that it get's executed _after_: the capturestate needs the stacks before
   194  	// they are returned to the pools
   195  	defer func() {
   196  		returnStack(stack)
   197  	}()
   198  	contract.Input = input
   199  
   200  	if in.cfg.Debug {
   201  		defer func() {
   202  			if err != nil {
   203  				if !logged {
   204  					in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
   205  				} else {
   206  					in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, callContext, in.evm.depth, err)
   207  				}
   208  			}
   209  		}()
   210  	}
   211  	// The Interpreter main run loop (contextual). This loop runs until either an
   212  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   213  	// the execution of one of the operations or until the done flag is set by the
   214  	// parent context.
   215  	steps := 0
   216  	for {
   217  		steps++
   218  		if steps%1000 == 0 && atomic.LoadInt32(&in.evm.abort) != 0 {
   219  			break
   220  		}
   221  		if in.cfg.Debug {
   222  			// Capture pre-execution values for tracing.
   223  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   224  		}
   225  
   226  		// Get the operation from the jump table and validate the stack to ensure there are
   227  		// enough stack items available to perform the operation.
   228  		op = contract.GetOp(pc)
   229  		operation := in.cfg.JumpTable[op]
   230  		if operation == nil {
   231  			return nil, &ErrInvalidOpCode{opcode: op}
   232  		}
   233  		// Validate stack
   234  		if sLen := stack.len(); sLen < operation.minStack {
   235  			return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack}
   236  		} else if sLen > operation.maxStack {
   237  			return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack}
   238  		}
   239  		// If the operation is valid, enforce write restrictions
   240  		if in.readOnly && in.evm.chainRules.IsByzantium {
   241  			// If the interpreter is operating in readonly mode, make sure no
   242  			// state-modifying operation is performed. The 3rd stack item
   243  			// for a call operation is the value. Transferring value from one
   244  			// account to the others means the state is modified and should also
   245  			// return with an error.
   246  			if operation.writes || ((op == CALL || op == CALLEX) && stack.Back(2).Sign() != 0) {
   247  				return nil, ErrWriteProtection
   248  			}
   249  		}
   250  		// Static portion of gas
   251  		cost = operation.constantGas // For tracing
   252  		if !contract.UseGas(operation.constantGas) {
   253  			return nil, ErrOutOfGas
   254  		}
   255  
   256  		var memorySize uint64
   257  		// calculate the new memory size and expand the memory to fit
   258  		// the operation
   259  		// Memory check needs to be done prior to evaluating the dynamic gas portion,
   260  		// to detect calculation overflows
   261  		if operation.memorySize != nil {
   262  			memSize, overflow := operation.memorySize(stack)
   263  			if overflow {
   264  				return nil, ErrGasUintOverflow
   265  			}
   266  			// memory is expanded in words of 32 bytes. Gas
   267  			// is also calculated in words.
   268  			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   269  				return nil, ErrGasUintOverflow
   270  			}
   271  		}
   272  		// Dynamic portion of gas
   273  		// consume the gas and return an error if not enough gas is available.
   274  		// cost is explicitly set so that the capture state defer method can get the proper cost
   275  		if operation.dynamicGas != nil {
   276  			var dynamicCost uint64
   277  			dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize)
   278  			cost += dynamicCost // total cost, for debug tracing
   279  			if err != nil || !contract.UseGas(dynamicCost) {
   280  				return nil, ErrOutOfGas
   281  			}
   282  		}
   283  		if memorySize > 0 {
   284  			mem.Resize(memorySize)
   285  		}
   286  
   287  		if in.cfg.Debug {
   288  			in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
   289  			logged = true
   290  		}
   291  
   292  		// execute the operation
   293  		res, err = operation.execute(&pc, in, callContext)
   294  		// if the operation clears the return data (e.g. it has returning data)
   295  		// set the last return to the result of the operation.
   296  		if operation.returns {
   297  			in.returnData = res
   298  		}
   299  
   300  		switch {
   301  		case err != nil:
   302  			return nil, err
   303  		case operation.reverts:
   304  			return res, ErrExecutionReverted
   305  		case operation.halts:
   306  			return res, nil
   307  		case !operation.jumps:
   308  			pc++
   309  		}
   310  	}
   311  	return nil, nil
   312  }