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