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