github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/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  	"fmt"
    21  
    22  	"github.com/ethereum/go-ethereum/common"
    23  	"github.com/ethereum/go-ethereum/common/math"
    24  	"github.com/ethereum/go-ethereum/core/tracing"
    25  	"github.com/ethereum/go-ethereum/crypto"
    26  	"github.com/ethereum/go-ethereum/log"
    27  	"github.com/holiman/uint256"
    28  )
    29  
    30  // Config are the configuration options for the Interpreter
    31  type Config struct {
    32  	Tracer                  *tracing.Hooks
    33  	NoBaseFee               bool  // Forces the EIP-1559 baseFee to 0 (needed for 0 price calls)
    34  	EnablePreimageRecording bool  // Enables recording of SHA3/keccak preimages
    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  // MemoryData returns the underlying memory slice. Callers must not modify the contents
    47  // of the returned data.
    48  func (ctx *ScopeContext) MemoryData() []byte {
    49  	if ctx.Memory == nil {
    50  		return nil
    51  	}
    52  	return ctx.Memory.Data()
    53  }
    54  
    55  // StackData returns the stack data. Callers must not modify the contents
    56  // of the returned data.
    57  func (ctx *ScopeContext) StackData() []uint256.Int {
    58  	if ctx.Stack == nil {
    59  		return nil
    60  	}
    61  	return ctx.Stack.Data()
    62  }
    63  
    64  // Caller returns the current caller.
    65  func (ctx *ScopeContext) Caller() common.Address {
    66  	return ctx.Contract.Caller()
    67  }
    68  
    69  // Address returns the address where this scope of execution is taking place.
    70  func (ctx *ScopeContext) Address() common.Address {
    71  	return ctx.Contract.Address()
    72  }
    73  
    74  // CallValue returns the value supplied with this call.
    75  func (ctx *ScopeContext) CallValue() *uint256.Int {
    76  	return ctx.Contract.Value()
    77  }
    78  
    79  // CallInput returns the input/calldata with this call. Callers must not modify
    80  // the contents of the returned data.
    81  func (ctx *ScopeContext) CallInput() []byte {
    82  	return ctx.Contract.Input
    83  }
    84  
    85  // EVMInterpreter represents an EVM interpreter
    86  type EVMInterpreter struct {
    87  	evm   *EVM
    88  	table *JumpTable
    89  
    90  	hasher    crypto.KeccakState // Keccak256 hasher instance shared across opcodes
    91  	hasherBuf common.Hash        // Keccak256 hasher result array shared across opcodes
    92  
    93  	readOnly   bool   // Whether to throw on stateful modifications
    94  	returnData []byte // Last CALL's return data for subsequent reuse
    95  }
    96  
    97  // NewEVMInterpreter returns a new instance of the Interpreter.
    98  func NewEVMInterpreter(evm *EVM) *EVMInterpreter {
    99  	// If jump table was not initialised we set the default one.
   100  	var table *JumpTable
   101  	switch {
   102  	case evm.chainRules.IsCancun:
   103  		table = &cancunInstructionSet
   104  	case evm.chainRules.IsShanghai:
   105  		table = &shanghaiInstructionSet
   106  	case evm.chainRules.IsMerge:
   107  		table = &mergeInstructionSet
   108  	case evm.chainRules.IsLondon:
   109  		table = &londonInstructionSet
   110  	case evm.chainRules.IsBerlin:
   111  		table = &berlinInstructionSet
   112  	case evm.chainRules.IsIstanbul:
   113  		table = &istanbulInstructionSet
   114  	case evm.chainRules.IsConstantinople:
   115  		table = &constantinopleInstructionSet
   116  	case evm.chainRules.IsByzantium:
   117  		table = &byzantiumInstructionSet
   118  	case evm.chainRules.IsEIP158:
   119  		table = &spuriousDragonInstructionSet
   120  	case evm.chainRules.IsEIP150:
   121  		table = &tangerineWhistleInstructionSet
   122  	case evm.chainRules.IsHomestead:
   123  		table = &homesteadInstructionSet
   124  	default:
   125  		table = &frontierInstructionSet
   126  	}
   127  	var extraEips []int
   128  	if len(evm.Config.ExtraEips) > 0 {
   129  		// Deep-copy jumptable to prevent modification of opcodes in other tables
   130  		table = copyJumpTable(table)
   131  	}
   132  	for _, eip := range evm.Config.ExtraEips {
   133  		if err := EnableEIP(eip, table); err != nil {
   134  			// Disable it, so caller can check if it's activated or not
   135  			log.Error("EIP activation failed", "eip", eip, "error", err)
   136  		} else {
   137  			extraEips = append(extraEips, eip)
   138  		}
   139  	}
   140  	evm.Config.ExtraEips = extraEips
   141  	return &EVMInterpreter{evm: evm, table: table}
   142  }
   143  
   144  // Run loops and evaluates the contract's code with the given input data and returns
   145  // the return byte-slice and an error if one occurred.
   146  //
   147  // It's important to note that any errors returned by the interpreter should be
   148  // considered a revert-and-consume-all-gas operation except for
   149  // ErrExecutionReverted which means revert-and-keep-gas-left.
   150  func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
   151  	// Increment the call depth which is restricted to 1024
   152  	in.evm.depth++
   153  	defer func() { in.evm.depth-- }()
   154  
   155  	// Make sure the readOnly is only set if we aren't in readOnly yet.
   156  	// This also makes sure that the readOnly flag isn't removed for child calls.
   157  	if readOnly && !in.readOnly {
   158  		in.readOnly = true
   159  		defer func() { in.readOnly = false }()
   160  	}
   161  
   162  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
   163  	// as every returning call will return new data anyway.
   164  	in.returnData = nil
   165  
   166  	// Don't bother with the execution if there's no code.
   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 EVMLogger
   187  		gasCopy uint64 // for EVMLogger to log gas remaining before execution
   188  		logged  bool   // deferred EVMLogger should ignore already logged steps
   189  		res     []byte // result of the opcode execution function
   190  		debug   = in.evm.Config.Tracer != nil
   191  	)
   192  	// Don't move this deferred function, it's placed before the OnOpcode-deferred method,
   193  	// so that it gets executed _after_: the OnOpcode 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 debug {
   201  		defer func() { // this deferred method handles exit-with-error
   202  			if err == nil {
   203  				return
   204  			}
   205  			if !logged && in.evm.Config.Tracer.OnOpcode != nil {
   206  				in.evm.Config.Tracer.OnOpcode(pcCopy, byte(op), gasCopy, cost, callContext, in.returnData, in.evm.depth, VMErrorFromErr(err))
   207  			}
   208  			if logged && in.evm.Config.Tracer.OnFault != nil {
   209  				in.evm.Config.Tracer.OnFault(pcCopy, byte(op), gasCopy, cost, callContext, in.evm.depth, VMErrorFromErr(err))
   210  			}
   211  		}()
   212  	}
   213  	// The Interpreter main run loop (contextual). This loop runs until either an
   214  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   215  	// the execution of one of the operations or until the done flag is set by the
   216  	// parent context.
   217  	for {
   218  		if debug {
   219  			// Capture pre-execution values for tracing.
   220  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   221  		}
   222  		// Get the operation from the jump table and validate the stack to ensure there are
   223  		// enough stack items available to perform the operation.
   224  		op = contract.GetOp(pc)
   225  		operation := in.table[op]
   226  		cost = operation.constantGas // For tracing
   227  		// Validate stack
   228  		if sLen := stack.len(); sLen < operation.minStack {
   229  			return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack}
   230  		} else if sLen > operation.maxStack {
   231  			return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack}
   232  		}
   233  		if !contract.UseGas(cost, in.evm.Config.Tracer, tracing.GasChangeIgnored) {
   234  			return nil, ErrOutOfGas
   235  		}
   236  
   237  		if operation.dynamicGas != nil {
   238  			// All ops with a dynamic memory usage also has a dynamic gas cost.
   239  			var memorySize uint64
   240  			// calculate the new memory size and expand the memory to fit
   241  			// the operation
   242  			// Memory check needs to be done prior to evaluating the dynamic gas portion,
   243  			// to detect calculation overflows
   244  			if operation.memorySize != nil {
   245  				memSize, overflow := operation.memorySize(stack)
   246  				if overflow {
   247  					return nil, ErrGasUintOverflow
   248  				}
   249  				// memory is expanded in words of 32 bytes. Gas
   250  				// is also calculated in words.
   251  				if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   252  					return nil, ErrGasUintOverflow
   253  				}
   254  			}
   255  			// Consume the gas and return an error if not enough gas is available.
   256  			// cost is explicitly set so that the capture state defer method can get the proper cost
   257  			var dynamicCost uint64
   258  			dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize)
   259  			cost += dynamicCost // for tracing
   260  			if err != nil {
   261  				return nil, fmt.Errorf("%w: %v", ErrOutOfGas, err)
   262  			}
   263  			if !contract.UseGas(dynamicCost, in.evm.Config.Tracer, tracing.GasChangeIgnored) {
   264  				return nil, ErrOutOfGas
   265  			}
   266  
   267  			// Do tracing before memory expansion
   268  			if debug {
   269  				if in.evm.Config.Tracer.OnGasChange != nil {
   270  					in.evm.Config.Tracer.OnGasChange(gasCopy, gasCopy-cost, tracing.GasChangeCallOpCode)
   271  				}
   272  				if in.evm.Config.Tracer.OnOpcode != nil {
   273  					in.evm.Config.Tracer.OnOpcode(pc, byte(op), gasCopy, cost, callContext, in.returnData, in.evm.depth, VMErrorFromErr(err))
   274  					logged = true
   275  				}
   276  			}
   277  			if memorySize > 0 {
   278  				mem.Resize(memorySize)
   279  			}
   280  		} else if debug {
   281  			if in.evm.Config.Tracer.OnGasChange != nil {
   282  				in.evm.Config.Tracer.OnGasChange(gasCopy, gasCopy-cost, tracing.GasChangeCallOpCode)
   283  			}
   284  			if in.evm.Config.Tracer.OnOpcode != nil {
   285  				in.evm.Config.Tracer.OnOpcode(pc, byte(op), gasCopy, cost, callContext, in.returnData, in.evm.depth, VMErrorFromErr(err))
   286  				logged = true
   287  			}
   288  		}
   289  
   290  		// execute the operation
   291  		res, err = operation.execute(&pc, in, callContext)
   292  		if err != nil {
   293  			break
   294  		}
   295  		pc++
   296  	}
   297  
   298  	if err == errStopToken {
   299  		err = nil // clear stop token error
   300  	}
   301  
   302  	return res, err
   303  }