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