github.com/ethereum/go-ethereum@v1.16.1/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  	StatelessSelfValidation bool // Generate execution witnesses and self-check against them (testing purpose)
    38  }
    39  
    40  // ScopeContext contains the things that are per-call, such as stack and memory,
    41  // but not transients like pc and gas
    42  type ScopeContext struct {
    43  	Memory   *Memory
    44  	Stack    *Stack
    45  	Contract *Contract
    46  }
    47  
    48  // MemoryData returns the underlying memory slice. Callers must not modify the contents
    49  // of the returned data.
    50  func (ctx *ScopeContext) MemoryData() []byte {
    51  	if ctx.Memory == nil {
    52  		return nil
    53  	}
    54  	return ctx.Memory.Data()
    55  }
    56  
    57  // StackData returns the stack data. Callers must not modify the contents
    58  // of the returned data.
    59  func (ctx *ScopeContext) StackData() []uint256.Int {
    60  	if ctx.Stack == nil {
    61  		return nil
    62  	}
    63  	return ctx.Stack.Data()
    64  }
    65  
    66  // Caller returns the current caller.
    67  func (ctx *ScopeContext) Caller() common.Address {
    68  	return ctx.Contract.Caller()
    69  }
    70  
    71  // Address returns the address where this scope of execution is taking place.
    72  func (ctx *ScopeContext) Address() common.Address {
    73  	return ctx.Contract.Address()
    74  }
    75  
    76  // CallValue returns the value supplied with this call.
    77  func (ctx *ScopeContext) CallValue() *uint256.Int {
    78  	return ctx.Contract.Value()
    79  }
    80  
    81  // CallInput returns the input/calldata with this call. Callers must not modify
    82  // the contents of the returned data.
    83  func (ctx *ScopeContext) CallInput() []byte {
    84  	return ctx.Contract.Input
    85  }
    86  
    87  // ContractCode returns the code of the contract being executed.
    88  func (ctx *ScopeContext) ContractCode() []byte {
    89  	return ctx.Contract.Code
    90  }
    91  
    92  // EVMInterpreter represents an EVM interpreter
    93  type EVMInterpreter struct {
    94  	evm   *EVM
    95  	table *JumpTable
    96  
    97  	hasher    crypto.KeccakState // Keccak256 hasher instance shared across opcodes
    98  	hasherBuf common.Hash        // Keccak256 hasher result array shared across opcodes
    99  
   100  	readOnly   bool   // Whether to throw on stateful modifications
   101  	returnData []byte // Last CALL's return data for subsequent reuse
   102  }
   103  
   104  // NewEVMInterpreter returns a new instance of the Interpreter.
   105  func NewEVMInterpreter(evm *EVM) *EVMInterpreter {
   106  	// If jump table was not initialised we set the default one.
   107  	var table *JumpTable
   108  	switch {
   109  	case evm.chainRules.IsVerkle:
   110  		// TODO replace with proper instruction set when fork is specified
   111  		table = &verkleInstructionSet
   112  	case evm.chainRules.IsPrague:
   113  		table = &pragueInstructionSet
   114  	case evm.chainRules.IsCancun:
   115  		table = &cancunInstructionSet
   116  	case evm.chainRules.IsShanghai:
   117  		table = &shanghaiInstructionSet
   118  	case evm.chainRules.IsMerge:
   119  		table = &mergeInstructionSet
   120  	case evm.chainRules.IsLondon:
   121  		table = &londonInstructionSet
   122  	case evm.chainRules.IsBerlin:
   123  		table = &berlinInstructionSet
   124  	case evm.chainRules.IsIstanbul:
   125  		table = &istanbulInstructionSet
   126  	case evm.chainRules.IsConstantinople:
   127  		table = &constantinopleInstructionSet
   128  	case evm.chainRules.IsByzantium:
   129  		table = &byzantiumInstructionSet
   130  	case evm.chainRules.IsEIP158:
   131  		table = &spuriousDragonInstructionSet
   132  	case evm.chainRules.IsEIP150:
   133  		table = &tangerineWhistleInstructionSet
   134  	case evm.chainRules.IsHomestead:
   135  		table = &homesteadInstructionSet
   136  	default:
   137  		table = &frontierInstructionSet
   138  	}
   139  	var extraEips []int
   140  	if len(evm.Config.ExtraEips) > 0 {
   141  		// Deep-copy jumptable to prevent modification of opcodes in other tables
   142  		table = copyJumpTable(table)
   143  	}
   144  	for _, eip := range evm.Config.ExtraEips {
   145  		if err := EnableEIP(eip, table); err != nil {
   146  			// Disable it, so caller can check if it's activated or not
   147  			log.Error("EIP activation failed", "eip", eip, "error", err)
   148  		} else {
   149  			extraEips = append(extraEips, eip)
   150  		}
   151  	}
   152  	evm.Config.ExtraEips = extraEips
   153  	return &EVMInterpreter{evm: evm, table: table, hasher: crypto.NewKeccakState()}
   154  }
   155  
   156  // Run loops and evaluates the contract's code with the given input data and returns
   157  // the return byte-slice and an error if one occurred.
   158  //
   159  // It's important to note that any errors returned by the interpreter should be
   160  // considered a revert-and-consume-all-gas operation except for
   161  // ErrExecutionReverted which means revert-and-keep-gas-left.
   162  func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
   163  	// Increment the call depth which is restricted to 1024
   164  	in.evm.depth++
   165  	defer func() { in.evm.depth-- }()
   166  
   167  	// Make sure the readOnly is only set if we aren't in readOnly yet.
   168  	// This also makes sure that the readOnly flag isn't removed for child calls.
   169  	if readOnly && !in.readOnly {
   170  		in.readOnly = true
   171  		defer func() { in.readOnly = false }()
   172  	}
   173  
   174  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
   175  	// as every returning call will return new data anyway.
   176  	in.returnData = nil
   177  
   178  	// Don't bother with the execution if there's no code.
   179  	if len(contract.Code) == 0 {
   180  		return nil, nil
   181  	}
   182  
   183  	var (
   184  		op          OpCode        // current opcode
   185  		mem         = NewMemory() // bound memory
   186  		stack       = newstack()  // local stack
   187  		callContext = &ScopeContext{
   188  			Memory:   mem,
   189  			Stack:    stack,
   190  			Contract: contract,
   191  		}
   192  		// For optimisation reason we're using uint64 as the program counter.
   193  		// It's theoretically possible to go above 2^64. The YP defines the PC
   194  		// to be uint256. Practically much less so feasible.
   195  		pc   = uint64(0) // program counter
   196  		cost uint64
   197  		// copies used by tracer
   198  		pcCopy  uint64 // needed for the deferred EVMLogger
   199  		gasCopy uint64 // for EVMLogger to log gas remaining before execution
   200  		logged  bool   // deferred EVMLogger should ignore already logged steps
   201  		res     []byte // result of the opcode execution function
   202  		debug   = in.evm.Config.Tracer != nil
   203  	)
   204  	// Don't move this deferred function, it's placed before the OnOpcode-deferred method,
   205  	// so that it gets executed _after_: the OnOpcode needs the stacks before
   206  	// they are returned to the pools
   207  	defer func() {
   208  		returnStack(stack)
   209  		mem.Free()
   210  	}()
   211  	contract.Input = input
   212  
   213  	if debug {
   214  		defer func() { // this deferred method handles exit-with-error
   215  			if err == nil {
   216  				return
   217  			}
   218  			if !logged && in.evm.Config.Tracer.OnOpcode != nil {
   219  				in.evm.Config.Tracer.OnOpcode(pcCopy, byte(op), gasCopy, cost, callContext, in.returnData, in.evm.depth, VMErrorFromErr(err))
   220  			}
   221  			if logged && in.evm.Config.Tracer.OnFault != nil {
   222  				in.evm.Config.Tracer.OnFault(pcCopy, byte(op), gasCopy, cost, callContext, in.evm.depth, VMErrorFromErr(err))
   223  			}
   224  		}()
   225  	}
   226  	// The Interpreter main run loop (contextual). This loop runs until either an
   227  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   228  	// the execution of one of the operations or until the done flag is set by the
   229  	// parent context.
   230  	for {
   231  		if debug {
   232  			// Capture pre-execution values for tracing.
   233  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   234  		}
   235  
   236  		if in.evm.chainRules.IsEIP4762 && !contract.IsDeployment && !contract.IsSystemCall {
   237  			// if the PC ends up in a new "chunk" of verkleized code, charge the
   238  			// associated costs.
   239  			contractAddr := contract.Address()
   240  			consumed, wanted := in.evm.TxContext.AccessEvents.CodeChunksRangeGas(contractAddr, pc, 1, uint64(len(contract.Code)), false, contract.Gas)
   241  			contract.UseGas(consumed, in.evm.Config.Tracer, tracing.GasChangeWitnessCodeChunk)
   242  			if consumed < wanted {
   243  				return nil, ErrOutOfGas
   244  			}
   245  		}
   246  
   247  		// Get the operation from the jump table and validate the stack to ensure there are
   248  		// enough stack items available to perform the operation.
   249  		op = contract.GetOp(pc)
   250  		operation := in.table[op]
   251  		cost = operation.constantGas // For tracing
   252  		// Validate stack
   253  		if sLen := stack.len(); sLen < operation.minStack {
   254  			return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack}
   255  		} else if sLen > operation.maxStack {
   256  			return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack}
   257  		}
   258  		// for tracing: this gas consumption event is emitted below in the debug section.
   259  		if contract.Gas < cost {
   260  			return nil, ErrOutOfGas
   261  		} else {
   262  			contract.Gas -= cost
   263  		}
   264  
   265  		// All ops with a dynamic memory usage also has a dynamic gas cost.
   266  		var memorySize uint64
   267  		if operation.dynamicGas != nil {
   268  			// calculate the new memory size and expand the memory to fit
   269  			// the operation
   270  			// Memory check needs to be done prior to evaluating the dynamic gas portion,
   271  			// to detect calculation overflows
   272  			if operation.memorySize != nil {
   273  				memSize, overflow := operation.memorySize(stack)
   274  				if overflow {
   275  					return nil, ErrGasUintOverflow
   276  				}
   277  				// memory is expanded in words of 32 bytes. Gas
   278  				// is also calculated in words.
   279  				if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   280  					return nil, ErrGasUintOverflow
   281  				}
   282  			}
   283  			// Consume the gas and return an error if not enough gas is available.
   284  			// cost is explicitly set so that the capture state defer method can get the proper cost
   285  			var dynamicCost uint64
   286  			dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize)
   287  			cost += dynamicCost // for tracing
   288  			if err != nil {
   289  				return nil, fmt.Errorf("%w: %v", ErrOutOfGas, err)
   290  			}
   291  			// for tracing: this gas consumption event is emitted below in the debug section.
   292  			if contract.Gas < dynamicCost {
   293  				return nil, ErrOutOfGas
   294  			} else {
   295  				contract.Gas -= dynamicCost
   296  			}
   297  		}
   298  
   299  		// Do tracing before potential memory expansion
   300  		if debug {
   301  			if in.evm.Config.Tracer.OnGasChange != nil {
   302  				in.evm.Config.Tracer.OnGasChange(gasCopy, gasCopy-cost, tracing.GasChangeCallOpCode)
   303  			}
   304  			if in.evm.Config.Tracer.OnOpcode != nil {
   305  				in.evm.Config.Tracer.OnOpcode(pc, byte(op), gasCopy, cost, callContext, in.returnData, in.evm.depth, VMErrorFromErr(err))
   306  				logged = true
   307  			}
   308  		}
   309  		if memorySize > 0 {
   310  			mem.Resize(memorySize)
   311  		}
   312  
   313  		// execute the operation
   314  		res, err = operation.execute(&pc, in, callContext)
   315  		if err != nil {
   316  			break
   317  		}
   318  		pc++
   319  	}
   320  
   321  	if err == errStopToken {
   322  		err = nil // clear stop token error
   323  	}
   324  
   325  	return res, err
   326  }