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