github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/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  
   118  	// Increment the call depth which is restricted to 1024
   119  	in.evm.depth++
   120  	defer func() { in.evm.depth-- }()
   121  
   122  	// Make sure the readOnly is only set if we aren't in readOnly yet.
   123  	// This also makes sure that the readOnly flag isn't removed for child calls.
   124  	if readOnly && !in.readOnly {
   125  		in.readOnly = true
   126  		defer func() { in.readOnly = false }()
   127  	}
   128  
   129  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
   130  	// as every returning call will return new data anyway.
   131  	in.returnData = nil
   132  
   133  	// Don't bother with the execution if there's no code.
   134  	if len(contract.Code) == 0 {
   135  		return nil, nil
   136  	}
   137  
   138  	var (
   139  		op          OpCode        // current opcode
   140  		mem         = NewMemory() // bound memory
   141  		stack       = newstack()  // local stack
   142  		callContext = &ScopeContext{
   143  			Memory:   mem,
   144  			Stack:    stack,
   145  			Contract: contract,
   146  		}
   147  		// For optimisation reason we're using uint64 as the program counter.
   148  		// It's theoretically possible to go above 2^64. The YP defines the PC
   149  		// to be uint256. Practically much less so feasible.
   150  		pc   = uint64(0) // program counter
   151  		cost uint64
   152  		// copies used by tracer
   153  		pcCopy  uint64 // needed for the deferred EVMLogger
   154  		gasCopy uint64 // for EVMLogger to log gas remaining before execution
   155  		logged  bool   // deferred EVMLogger should ignore already logged steps
   156  		res     []byte // result of the opcode execution function
   157  	)
   158  	// Don't move this deferrred function, it's placed before the capturestate-deferred method,
   159  	// so that it get's executed _after_: the capturestate needs the stacks before
   160  	// they are returned to the pools
   161  	defer func() {
   162  		returnStack(stack)
   163  	}()
   164  	contract.Input = input
   165  
   166  	if in.cfg.Debug {
   167  		defer func() {
   168  			if err != nil {
   169  				if !logged {
   170  					in.cfg.Tracer.CaptureState(pcCopy, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
   171  				} else {
   172  					in.cfg.Tracer.CaptureFault(pcCopy, op, gasCopy, cost, callContext, in.evm.depth, err)
   173  				}
   174  			}
   175  		}()
   176  	}
   177  	// The Interpreter main run loop (contextual). This loop runs until either an
   178  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   179  	// the execution of one of the operations or until the done flag is set by the
   180  	// parent context.
   181  	for {
   182  		if in.cfg.Debug {
   183  			// Capture pre-execution values for tracing.
   184  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   185  		}
   186  		// Get the operation from the jump table and validate the stack to ensure there are
   187  		// enough stack items available to perform the operation.
   188  		op = contract.GetOp(pc)
   189  		operation := in.cfg.JumpTable[op]
   190  		cost = operation.constantGas // For tracing
   191  		// Validate stack
   192  		if sLen := stack.len(); sLen < operation.minStack {
   193  			return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack}
   194  		} else if sLen > operation.maxStack {
   195  			return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack}
   196  		}
   197  		if !contract.UseGas(cost) {
   198  			return nil, ErrOutOfGas
   199  		}
   200  		if operation.dynamicGas != nil {
   201  			// All ops with a dynamic memory usage also has a dynamic gas cost.
   202  			var memorySize uint64
   203  			// calculate the new memory size and expand the memory to fit
   204  			// the operation
   205  			// Memory check needs to be done prior to evaluating the dynamic gas portion,
   206  			// to detect calculation overflows
   207  			if operation.memorySize != nil {
   208  				memSize, overflow := operation.memorySize(stack)
   209  				if overflow {
   210  					return nil, ErrGasUintOverflow
   211  				}
   212  				// memory is expanded in words of 32 bytes. Gas
   213  				// is also calculated in words.
   214  				if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   215  					return nil, ErrGasUintOverflow
   216  				}
   217  			}
   218  			// Consume the gas and return an error if not enough gas is available.
   219  			// cost is explicitly set so that the capture state defer method can get the proper cost
   220  			var dynamicCost uint64
   221  			dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize)
   222  			cost += dynamicCost // for tracing
   223  			if err != nil || !contract.UseGas(dynamicCost) {
   224  				return nil, ErrOutOfGas
   225  			}
   226  			if memorySize > 0 {
   227  				mem.Resize(memorySize)
   228  			}
   229  		}
   230  		if in.cfg.Debug {
   231  			in.cfg.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
   232  			logged = true
   233  		}
   234  		// execute the operation
   235  		res, err = operation.execute(&pc, in, callContext)
   236  		if err != nil {
   237  			break
   238  		}
   239  		pc++
   240  	}
   241  
   242  	if err == errStopToken {
   243  		err = nil // clear stop token error
   244  	}
   245  
   246  	return res, err
   247  }