github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/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  	"hash"
    21  	"sync/atomic"
    22  
    23  	"github.com/zhiqiangxu/go-ethereum/common"
    24  	"github.com/zhiqiangxu/go-ethereum/common/math"
    25  	"github.com/zhiqiangxu/go-ethereum/log"
    26  )
    27  
    28  // Config are the configuration options for the Interpreter
    29  type Config struct {
    30  	Debug                   bool   // Enables debugging
    31  	Tracer                  Tracer // Opcode logger
    32  	NoRecursion             bool   // Disables call, callcode, delegate call and create
    33  	EnablePreimageRecording bool   // Enables recording of SHA3/keccak preimages
    34  
    35  	JumpTable [256]operation // EVM instruction table, automatically populated if unset
    36  
    37  	EWASMInterpreter string // External EWASM interpreter options
    38  	EVMInterpreter   string // External EVM interpreter options
    39  
    40  	ExtraEips []int // Additional EIPS that are to be enabled
    41  }
    42  
    43  // Interpreter is used to run Ethereum based contracts and will utilise the
    44  // passed environment to query external sources for state information.
    45  // The Interpreter will run the byte code VM based on the passed
    46  // configuration.
    47  type Interpreter interface {
    48  	// Run loops and evaluates the contract's code with the given input data and returns
    49  	// the return byte-slice and an error if one occurred.
    50  	Run(contract *Contract, input []byte, static bool) ([]byte, error)
    51  	// CanRun tells if the contract, passed as an argument, can be
    52  	// run by the current interpreter. This is meant so that the
    53  	// caller can do something like:
    54  	//
    55  	// ```golang
    56  	// for _, interpreter := range interpreters {
    57  	//   if interpreter.CanRun(contract.code) {
    58  	//     interpreter.Run(contract.code, input)
    59  	//   }
    60  	// }
    61  	// ```
    62  	CanRun([]byte) bool
    63  }
    64  
    65  // callCtx contains the things that are per-call, such as stack and memory,
    66  // but not transients like pc and gas
    67  type callCtx struct {
    68  	memory   *Memory
    69  	stack    *Stack
    70  	rstack   *ReturnStack
    71  	contract *Contract
    72  }
    73  
    74  // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports
    75  // Read to get a variable amount of data from the hash state. Read is faster than Sum
    76  // because it doesn't copy the internal state, but also modifies the internal state.
    77  type keccakState interface {
    78  	hash.Hash
    79  	Read([]byte) (int, error)
    80  }
    81  
    82  // EVMInterpreter represents an EVM interpreter
    83  type EVMInterpreter struct {
    84  	evm *EVM
    85  	cfg Config
    86  
    87  	intPool *intPool
    88  
    89  	hasher    keccakState // Keccak256 hasher instance shared across opcodes
    90  	hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes
    91  
    92  	readOnly   bool   // Whether to throw on stateful modifications
    93  	returnData []byte // Last CALL's return data for subsequent reuse
    94  }
    95  
    96  // NewEVMInterpreter returns a new instance of the Interpreter.
    97  func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
    98  	// We use the STOP instruction whether to see
    99  	// the jump table was initialised. If it was not
   100  	// we'll set the default jump table.
   101  	if !cfg.JumpTable[STOP].valid {
   102  		var jt JumpTable
   103  		switch {
   104  		case evm.chainRules.IsYoloV1:
   105  			jt = yoloV1InstructionSet
   106  		case evm.chainRules.IsIstanbul:
   107  			jt = istanbulInstructionSet
   108  		case evm.chainRules.IsConstantinople:
   109  			jt = constantinopleInstructionSet
   110  		case evm.chainRules.IsByzantium:
   111  			jt = byzantiumInstructionSet
   112  		case evm.chainRules.IsEIP158:
   113  			jt = spuriousDragonInstructionSet
   114  		case evm.chainRules.IsEIP150:
   115  			jt = tangerineWhistleInstructionSet
   116  		case evm.chainRules.IsHomestead:
   117  			jt = homesteadInstructionSet
   118  		default:
   119  			jt = frontierInstructionSet
   120  		}
   121  		for i, eip := range cfg.ExtraEips {
   122  			if err := EnableEIP(eip, &jt); err != nil {
   123  				// Disable it, so caller can check if it's activated or not
   124  				cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...)
   125  				log.Error("EIP activation failed", "eip", eip, "error", err)
   126  			}
   127  		}
   128  		cfg.JumpTable = jt
   129  	}
   130  
   131  	return &EVMInterpreter{
   132  		evm: evm,
   133  		cfg: cfg,
   134  	}
   135  }
   136  
   137  // Run loops and evaluates the contract's code with the given input data and returns
   138  // the return byte-slice and an error if one occurred.
   139  //
   140  // It's important to note that any errors returned by the interpreter should be
   141  // considered a revert-and-consume-all-gas operation except for
   142  // ErrExecutionReverted which means revert-and-keep-gas-left.
   143  func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
   144  	if in.intPool == nil {
   145  		in.intPool = poolOfIntPools.get()
   146  		defer func() {
   147  			poolOfIntPools.put(in.intPool)
   148  			in.intPool = nil
   149  		}()
   150  	}
   151  
   152  	// Increment the call depth which is restricted to 1024
   153  	in.evm.depth++
   154  	defer func() { in.evm.depth-- }()
   155  
   156  	// Make sure the readOnly is only set if we aren't in readOnly yet.
   157  	// This makes also sure that the readOnly flag isn't removed for child calls.
   158  	if readOnly && !in.readOnly {
   159  		in.readOnly = true
   160  		defer func() { in.readOnly = false }()
   161  	}
   162  
   163  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
   164  	// as every returning call will return new data anyway.
   165  	in.returnData = nil
   166  
   167  	// Don't bother with the execution if there's no code.
   168  	if len(contract.Code) == 0 {
   169  		return nil, nil
   170  	}
   171  
   172  	var (
   173  		op          OpCode             // current opcode
   174  		mem         = NewMemory()      // bound memory
   175  		stack       = newstack()       // local stack
   176  		returns     = newReturnStack() // local returns stack
   177  		callContext = &callCtx{
   178  			memory:   mem,
   179  			stack:    stack,
   180  			rstack:   returns,
   181  			contract: contract,
   182  		}
   183  		// For optimisation reason we're using uint64 as the program counter.
   184  		// It's theoretically possible to go above 2^64. The YP defines the PC
   185  		// to be uint256. Practically much less so feasible.
   186  		pc   = uint64(0) // program counter
   187  		cost uint64
   188  		// copies used by tracer
   189  		pcCopy  uint64 // needed for the deferred Tracer
   190  		gasCopy uint64 // for Tracer to log gas remaining before execution
   191  		logged  bool   // deferred Tracer should ignore already logged steps
   192  		res     []byte // result of the opcode execution function
   193  	)
   194  	contract.Input = input
   195  
   196  	// Reclaim the stack as an int pool when the execution stops
   197  	defer func() { in.intPool.put(stack.data...) }()
   198  
   199  	if in.cfg.Debug {
   200  		defer func() {
   201  			if err != nil {
   202  				if !logged {
   203  					in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, returns, contract, in.evm.depth, err)
   204  				} else {
   205  					in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, returns, contract, in.evm.depth, err)
   206  				}
   207  			}
   208  		}()
   209  	}
   210  	// The Interpreter main run loop (contextual). This loop runs until either an
   211  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   212  	// the execution of one of the operations or until the done flag is set by the
   213  	// parent context.
   214  	steps := 0
   215  	for {
   216  		steps++
   217  		if steps%1000 == 0 && atomic.LoadInt32(&in.evm.abort) != 0 {
   218  			break
   219  		}
   220  		if in.cfg.Debug {
   221  			// Capture pre-execution values for tracing.
   222  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   223  		}
   224  
   225  		// Get the operation from the jump table and validate the stack to ensure there are
   226  		// enough stack items available to perform the operation.
   227  		op = contract.GetOp(pc)
   228  		operation := in.cfg.JumpTable[op]
   229  		if !operation.valid {
   230  			return nil, &ErrInvalidOpCode{opcode: op}
   231  		}
   232  		// Validate stack
   233  		if sLen := stack.len(); sLen < operation.minStack {
   234  			return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack}
   235  		} else if sLen > operation.maxStack {
   236  			return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack}
   237  		}
   238  		// If the operation is valid, enforce and write restrictions
   239  		if in.readOnly && in.evm.chainRules.IsByzantium {
   240  			// If the interpreter is operating in readonly mode, make sure no
   241  			// state-modifying operation is performed. The 3rd stack item
   242  			// for a call operation is the value. Transferring value from one
   243  			// account to the others means the state is modified and should also
   244  			// return with an error.
   245  			if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) {
   246  				return nil, ErrWriteProtection
   247  			}
   248  		}
   249  		// Static portion of gas
   250  		cost = operation.constantGas // For tracing
   251  		if !contract.UseGas(operation.constantGas) {
   252  			return nil, ErrOutOfGas
   253  		}
   254  
   255  		var memorySize uint64
   256  		// calculate the new memory size and expand the memory to fit
   257  		// the operation
   258  		// Memory check needs to be done prior to evaluating the dynamic gas portion,
   259  		// to detect calculation overflows
   260  		if operation.memorySize != nil {
   261  			memSize, overflow := operation.memorySize(stack)
   262  			if overflow {
   263  				return nil, ErrGasUintOverflow
   264  			}
   265  			// memory is expanded in words of 32 bytes. Gas
   266  			// is also calculated in words.
   267  			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   268  				return nil, ErrGasUintOverflow
   269  			}
   270  		}
   271  		// Dynamic portion of gas
   272  		// consume the gas and return an error if not enough gas is available.
   273  		// cost is explicitly set so that the capture state defer method can get the proper cost
   274  		if operation.dynamicGas != nil {
   275  			var dynamicCost uint64
   276  			dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize)
   277  			cost += dynamicCost // total cost, for debug tracing
   278  			if err != nil || !contract.UseGas(dynamicCost) {
   279  				return nil, ErrOutOfGas
   280  			}
   281  		}
   282  		if memorySize > 0 {
   283  			mem.Resize(memorySize)
   284  		}
   285  
   286  		if in.cfg.Debug {
   287  			in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, returns, contract, in.evm.depth, err)
   288  			logged = true
   289  		}
   290  
   291  		// execute the operation
   292  		res, err = operation.execute(&pc, in, callContext)
   293  		// verifyPool is a build flag. Pool verification makes sure the integrity
   294  		// of the integer pool by comparing values to a default value.
   295  		if verifyPool {
   296  			verifyIntegerPool(in.intPool)
   297  		}
   298  		// if the operation clears the return data (e.g. it has returning data)
   299  		// set the last return to the result of the operation.
   300  		if operation.returns {
   301  			in.returnData = res
   302  		}
   303  
   304  		switch {
   305  		case err != nil:
   306  			return nil, err
   307  		case operation.reverts:
   308  			return res, ErrExecutionReverted
   309  		case operation.halts:
   310  			return res, nil
   311  		case !operation.jumps:
   312  			pc++
   313  		}
   314  	}
   315  	return nil, nil
   316  }
   317  
   318  // CanRun tells if the contract, passed as an argument, can be
   319  // run by the current interpreter.
   320  func (in *EVMInterpreter) CanRun(code []byte) bool {
   321  	return true
   322  }