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