github.com/authcall/reference-optimistic-geth@v0.0.0-20220816224302-06313bfeb8d2/core/vm/interpreter.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  	"hash"
    21  
    22  	"github.com/ethereum/go-ethereum/common"
    23  	"github.com/ethereum/go-ethereum/common/math"
    24  	"github.com/ethereum/go-ethereum/log"
    25  )
    26  
    27  // Config are the configuration options for the Interpreter
    28  type Config struct {
    29  	Debug                   bool      // Enables debugging
    30  	Tracer                  EVMLogger // Opcode logger
    31  	NoBaseFee               bool      // Forces the EIP-1559 baseFee to 0 (needed for 0 price calls)
    32  	EnablePreimageRecording bool      // Enables recording of SHA3/keccak preimages
    33  
    34  	JumpTable *JumpTable // EVM instruction table, automatically populated if unset
    35  
    36  	ExtraEips []int // Additional EIPS that are to be enabled
    37  }
    38  
    39  // ScopeContext contains the things that are per-call, such as stack and memory,
    40  // but not transients like pc and gas
    41  type ScopeContext struct {
    42  	Memory   *Memory
    43  	Stack    *Stack
    44  	Contract *Contract
    45  }
    46  
    47  // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports
    48  // Read to get a variable amount of data from the hash state. Read is faster than Sum
    49  // because it doesn't copy the internal state, but also modifies the internal state.
    50  type keccakState interface {
    51  	hash.Hash
    52  	Read([]byte) (int, error)
    53  }
    54  
    55  // EVMInterpreter represents an EVM interpreter
    56  type EVMInterpreter struct {
    57  	evm *EVM
    58  	cfg Config
    59  
    60  	hasher    keccakState // Keccak256 hasher instance shared across opcodes
    61  	hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes
    62  
    63  	readOnly   bool   // Whether to throw on stateful modifications
    64  	returnData []byte // Last CALL's return data for subsequent reuse
    65  }
    66  
    67  // NewEVMInterpreter returns a new instance of the Interpreter.
    68  func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
    69  	// If jump table was not initialised we set the default one.
    70  	if cfg.JumpTable == nil {
    71  		switch {
    72  		case evm.chainRules.IsMerge:
    73  			cfg.JumpTable = &mergeInstructionSet
    74  		case evm.chainRules.IsLondon:
    75  			cfg.JumpTable = &londonInstructionSet
    76  		case evm.chainRules.IsBerlin:
    77  			cfg.JumpTable = &berlinInstructionSet
    78  		case evm.chainRules.IsIstanbul:
    79  			cfg.JumpTable = &istanbulInstructionSet
    80  		case evm.chainRules.IsConstantinople:
    81  			cfg.JumpTable = &constantinopleInstructionSet
    82  		case evm.chainRules.IsByzantium:
    83  			cfg.JumpTable = &byzantiumInstructionSet
    84  		case evm.chainRules.IsEIP158:
    85  			cfg.JumpTable = &spuriousDragonInstructionSet
    86  		case evm.chainRules.IsEIP150:
    87  			cfg.JumpTable = &tangerineWhistleInstructionSet
    88  		case evm.chainRules.IsHomestead:
    89  			cfg.JumpTable = &homesteadInstructionSet
    90  		default:
    91  			cfg.JumpTable = &frontierInstructionSet
    92  		}
    93  		for i, eip := range cfg.ExtraEips {
    94  			copy := *cfg.JumpTable
    95  			if err := EnableEIP(eip, &copy); err != nil {
    96  				// Disable it, so caller can check if it's activated or not
    97  				cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...)
    98  				log.Error("EIP activation failed", "eip", eip, "error", err)
    99  			}
   100  			cfg.JumpTable = &copy
   101  		}
   102  	}
   103  
   104  	return &EVMInterpreter{
   105  		evm: evm,
   106  		cfg: cfg,
   107  	}
   108  }
   109  
   110  // Run loops and evaluates the contract's code with the given input data and returns
   111  // the return byte-slice and an error if one occurred.
   112  //
   113  // It's important to note that any errors returned by the interpreter should be
   114  // considered a revert-and-consume-all-gas operation except for
   115  // ErrExecutionReverted which means revert-and-keep-gas-left.
   116  func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
   117  	// Increment the call depth which is restricted to 1024
   118  	in.evm.depth++
   119  	defer func() { in.evm.depth-- }()
   120  
   121  	// Make sure the readOnly is only set if we aren't in readOnly yet.
   122  	// This also makes sure that the readOnly flag isn't removed for child calls.
   123  	if readOnly && !in.readOnly {
   124  		in.readOnly = true
   125  		defer func() { in.readOnly = false }()
   126  	}
   127  
   128  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
   129  	// as every returning call will return new data anyway.
   130  	in.returnData = nil
   131  
   132  	// Don't bother with the execution if there's no code.
   133  	if len(contract.Code) == 0 {
   134  		return nil, nil
   135  	}
   136  
   137  	var (
   138  		op          OpCode        // current opcode
   139  		mem         = NewMemory() // bound memory
   140  		stack       = newstack()  // local stack
   141  		callContext = &ScopeContext{
   142  			Memory:   mem,
   143  			Stack:    stack,
   144  			Contract: contract,
   145  		}
   146  		// For optimisation reason we're using uint64 as the program counter.
   147  		// It's theoretically possible to go above 2^64. The YP defines the PC
   148  		// to be uint256. Practically much less so feasible.
   149  		pc   = uint64(0) // program counter
   150  		cost uint64
   151  		// copies used by tracer
   152  		pcCopy  uint64 // needed for the deferred EVMLogger
   153  		gasCopy uint64 // for EVMLogger to log gas remaining before execution
   154  		logged  bool   // deferred EVMLogger should ignore already logged steps
   155  		res     []byte // result of the opcode execution function
   156  	)
   157  	// Don't move this deferred function, it's placed before the capturestate-deferred method,
   158  	// so that it get's executed _after_: the capturestate needs the stacks before
   159  	// they are returned to the pools
   160  	defer func() {
   161  		returnStack(stack)
   162  	}()
   163  	contract.Input = input
   164  
   165  	if in.cfg.Debug {
   166  		defer func() {
   167  			if err != nil {
   168  				if !logged {
   169  					in.cfg.Tracer.CaptureState(pcCopy, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
   170  				} else {
   171  					in.cfg.Tracer.CaptureFault(pcCopy, op, gasCopy, cost, callContext, in.evm.depth, err)
   172  				}
   173  			}
   174  		}()
   175  	}
   176  	// The Interpreter main run loop (contextual). This loop runs until either an
   177  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   178  	// the execution of one of the operations or until the done flag is set by the
   179  	// parent context.
   180  	for {
   181  		if in.cfg.Debug {
   182  			// Capture pre-execution values for tracing.
   183  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   184  		}
   185  		// Get the operation from the jump table and validate the stack to ensure there are
   186  		// enough stack items available to perform the operation.
   187  		op = contract.GetOp(pc)
   188  		operation := in.cfg.JumpTable[op]
   189  		cost = operation.constantGas // For tracing
   190  		// Validate stack
   191  		if sLen := stack.len(); sLen < operation.minStack {
   192  			return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack}
   193  		} else if sLen > operation.maxStack {
   194  			return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack}
   195  		}
   196  		if !contract.UseGas(cost) {
   197  			return nil, ErrOutOfGas
   198  		}
   199  		if operation.dynamicGas != nil {
   200  			// All ops with a dynamic memory usage also has a dynamic gas cost.
   201  			var memorySize uint64
   202  			// calculate the new memory size and expand the memory to fit
   203  			// the operation
   204  			// Memory check needs to be done prior to evaluating the dynamic gas portion,
   205  			// to detect calculation overflows
   206  			if operation.memorySize != nil {
   207  				memSize, overflow := operation.memorySize(stack)
   208  				if overflow {
   209  					return nil, ErrGasUintOverflow
   210  				}
   211  				// memory is expanded in words of 32 bytes. Gas
   212  				// is also calculated in words.
   213  				if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   214  					return nil, ErrGasUintOverflow
   215  				}
   216  			}
   217  			// Consume the gas and return an error if not enough gas is available.
   218  			// cost is explicitly set so that the capture state defer method can get the proper cost
   219  			var dynamicCost uint64
   220  			dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize)
   221  			cost += dynamicCost // for tracing
   222  			if err != nil || !contract.UseGas(dynamicCost) {
   223  				return nil, ErrOutOfGas
   224  			}
   225  			// Do tracing before memory expansion
   226  			if in.cfg.Debug {
   227  				in.cfg.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
   228  				logged = true
   229  			}
   230  			if memorySize > 0 {
   231  				mem.Resize(memorySize)
   232  			}
   233  		} else if in.cfg.Debug {
   234  			in.cfg.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
   235  			logged = true
   236  		}
   237  		// execute the operation
   238  		res, err = operation.execute(&pc, in, callContext)
   239  		if err != nil {
   240  			break
   241  		}
   242  		pc++
   243  	}
   244  
   245  	if err == errStopToken {
   246  		err = nil // clear stop token error
   247  	}
   248  
   249  	return res, err
   250  }