github.com/reapchain/go-reapchain@v0.2.15-0.20210609012950-9735c110c705/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 "sync/atomic" 22 "time" 23 24 "github.com/ethereum/go-ethereum/common" 25 "github.com/ethereum/go-ethereum/common/math" 26 "github.com/ethereum/go-ethereum/crypto" 27 "github.com/ethereum/go-ethereum/log" 28 "github.com/ethereum/go-ethereum/params" 29 ) 30 31 // Config are the configuration options for the Interpreter 32 type Config struct { 33 // Debug enabled debugging Interpreter options 34 Debug bool 35 // EnableJit enabled the JIT VM 36 EnableJit bool 37 // ForceJit forces the JIT VM 38 ForceJit bool 39 // Tracer is the op code logger 40 Tracer Tracer 41 // NoRecursion disabled Interpreter call, callcode, 42 // delegate call and create. 43 NoRecursion bool 44 // Disable gas metering 45 DisableGasMetering bool 46 // Enable recording of SHA3/keccak preimages 47 EnablePreimageRecording bool 48 // JumpTable contains the EVM instruction table. This 49 // may me left uninitialised and will be set the default 50 // table. 51 JumpTable [256]operation 52 // Estimate gas metering 53 EstimateGasMetering bool 54 } 55 56 // Interpreter is used to run Ethereum based contracts and will utilise the 57 // passed evmironment to query external sources for state information. 58 // The Interpreter will run the byte code VM or JIT VM based on the passed 59 // configuration. 60 type Interpreter struct { 61 evm *EVM 62 cfg Config 63 gasTable params.GasTable 64 intPool *intPool 65 66 readonly bool 67 } 68 69 // NewInterpreter returns a new instance of the Interpreter. 70 func NewInterpreter(evm *EVM, cfg Config) *Interpreter { 71 // We use the STOP instruction whether to see 72 // the jump table was initialised. If it was not 73 // we'll set the default jump table. 74 if !cfg.JumpTable[STOP].valid { 75 switch { 76 case evm.ChainConfig().IsHomestead(evm.BlockNumber): 77 cfg.JumpTable = homesteadInstructionSet 78 default: 79 cfg.JumpTable = frontierInstructionSet 80 } 81 } 82 83 return &Interpreter{ 84 evm: evm, 85 cfg: cfg, 86 gasTable: evm.ChainConfig().GasTable(evm.BlockNumber), 87 intPool: newIntPool(), 88 } 89 } 90 91 func (in *Interpreter) enforceRestrictions(op OpCode, operation operation, stack *Stack) error { 92 return nil 93 } 94 95 // Run loops and evaluates the contract's code with the given input data and returns 96 // the return byte-slice and an error if one occurred. 97 // 98 // It's important to note that any errors returned by the interpreter should be 99 // considered a revert-and-consume-all-gas operation. No error specific checks 100 // should be handled to reduce complexity and errors further down the in. 101 func (in *Interpreter) Run(snapshot int, contract *Contract, input []byte) (ret []byte, err error) { 102 in.evm.depth++ 103 defer func() { in.evm.depth-- }() 104 105 // Don't bother with the execution if there's no code. 106 if len(contract.Code) == 0 { 107 return nil, nil 108 } 109 110 codehash := contract.CodeHash // codehash is used when doing jump dest caching 111 if codehash == (common.Hash{}) { 112 codehash = crypto.Keccak256Hash(contract.Code) 113 } 114 115 var ( 116 op OpCode // current opcode 117 mem = NewMemory() // bound memory 118 stack = newstack() // local stack 119 // For optimisation reason we're using uint64 as the program counter. 120 // It's theoretically possible to go above 2^64. The YP defines the PC 121 // to be uint256. Practically much less so feasible. 122 pc = uint64(0) // program counter 123 cost uint64 124 //fee uint64 125 ) 126 contract.Input = input 127 128 // User defer pattern to check for an error and, based on the error being nil or not, use all gas and return. 129 defer func() { 130 if err != nil && in.cfg.Debug { 131 // XXX For debugging 132 //fmt.Printf("%04d: %8v cost = %-8d stack = %-8d ERR = %v\n", pc, op, cost, stack.len(), err) 133 in.cfg.Tracer.CaptureState(in.evm, pc, op, contract.Gas, cost, mem, stack, contract, in.evm.depth, err) 134 } 135 }() 136 137 log.Debug("interpreter running contract", "hash", codehash[:]) 138 tstart := time.Now() 139 defer log.Debug("interpreter finished running contract", "hash", codehash[:], "elapsed", time.Since(tstart)) 140 141 // The Interpreter main run loop (contextual). This loop runs until either an 142 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 143 // the execution of one of the operations or until the done flag is set by the 144 // parent context. 145 for atomic.LoadInt32(&in.evm.abort) == 0 { 146 // Get the memory location of pc 147 op = contract.GetOp(pc) 148 149 //log.Info("Interpreter atomic.LoadInt32", "OP Code", int(op)) 150 151 // get the operation from the jump table matching the opcode 152 operation := in.cfg.JumpTable[op] 153 if err := in.enforceRestrictions(op, operation, stack); err != nil { 154 return nil, err 155 } 156 157 // if the op is invalid abort the process and return an error 158 if !operation.valid { 159 return nil, fmt.Errorf("invalid opcode 0x%x", int(op)) 160 } 161 162 // validate the stack and make sure there enough stack items available 163 // to perform the operation 164 if err := operation.validateStack(stack); err != nil { 165 return nil, err 166 } 167 168 var memorySize uint64 169 // calculate the new memory size and expand the memory to fit 170 // the operation 171 if operation.memorySize != nil { 172 memSize, overflow := bigUint64(operation.memorySize(stack)) 173 if overflow { 174 return nil, errGasUintOverflow 175 } 176 // memory is expanded in words of 32 bytes. Gas 177 // is also calculated in words. 178 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 179 return nil, errGasUintOverflow 180 } 181 } 182 183 if !in.cfg.DisableGasMetering { 184 // consume the gas and return an error if not enough gas is available. 185 // cost is explicitly set so that the capture state defer method cas get the proper cost 186 cost, err = operation.gasCost(in.gasTable, in.evm, contract, stack, mem, memorySize) 187 if err != nil || !contract.UseGas(cost) { 188 return nil, ErrOutOfGas 189 } 190 191 } 192 if memorySize > 0 { 193 mem.Resize(memorySize) 194 } 195 196 //log.Info("Interpreter Run","Cost Value", cost, "Memory Size", memorySize, "OP Code", int(op)) 197 198 if in.cfg.Debug { 199 in.cfg.Tracer.CaptureState(in.evm, pc, op, contract.Gas, cost, mem, stack, contract, in.evm.depth, err) 200 } 201 // XXX For debugging 202 //fmt.Printf("%04d: %8v cost = %-8d stack = %-8d\n", pc, op, cost, stack.len()) 203 204 // execute the operation 205 res, err := operation.execute(&pc, in.evm, contract, mem, stack) 206 // verifyPool is a build flag. Pool verification makes sure the integrity 207 // of the integer pool by comparing values to a default value. 208 if verifyPool { 209 verifyIntegerPool(in.intPool) 210 } 211 212 switch { 213 case err != nil: 214 return nil, err 215 case operation.halts: 216 return res, nil 217 case !operation.jumps: 218 pc++ 219 } 220 // if the operation returned a value make sure that is also set 221 // the last return data. 222 if res != nil { 223 mem.lastReturn = ret 224 } 225 } 226 return nil, nil 227 }