github.com/ethereum/go-ethereum@v1.14.4-0.20240516095835-473ee8fc07a3/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 22 "github.com/ethereum/go-ethereum/common" 23 "github.com/ethereum/go-ethereum/common/math" 24 "github.com/ethereum/go-ethereum/core/tracing" 25 "github.com/ethereum/go-ethereum/crypto" 26 "github.com/ethereum/go-ethereum/log" 27 "github.com/holiman/uint256" 28 ) 29 30 // Config are the configuration options for the Interpreter 31 type Config struct { 32 Tracer *tracing.Hooks 33 NoBaseFee bool // Forces the EIP-1559 baseFee to 0 (needed for 0 price calls) 34 EnablePreimageRecording bool // Enables recording of SHA3/keccak preimages 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 // MemoryData returns the underlying memory slice. Callers must not modify the contents 47 // of the returned data. 48 func (ctx *ScopeContext) MemoryData() []byte { 49 if ctx.Memory == nil { 50 return nil 51 } 52 return ctx.Memory.Data() 53 } 54 55 // StackData returns the stack data. Callers must not modify the contents 56 // of the returned data. 57 func (ctx *ScopeContext) StackData() []uint256.Int { 58 if ctx.Stack == nil { 59 return nil 60 } 61 return ctx.Stack.Data() 62 } 63 64 // Caller returns the current caller. 65 func (ctx *ScopeContext) Caller() common.Address { 66 return ctx.Contract.Caller() 67 } 68 69 // Address returns the address where this scope of execution is taking place. 70 func (ctx *ScopeContext) Address() common.Address { 71 return ctx.Contract.Address() 72 } 73 74 // CallValue returns the value supplied with this call. 75 func (ctx *ScopeContext) CallValue() *uint256.Int { 76 return ctx.Contract.Value() 77 } 78 79 // CallInput returns the input/calldata with this call. Callers must not modify 80 // the contents of the returned data. 81 func (ctx *ScopeContext) CallInput() []byte { 82 return ctx.Contract.Input 83 } 84 85 // EVMInterpreter represents an EVM interpreter 86 type EVMInterpreter struct { 87 evm *EVM 88 table *JumpTable 89 90 hasher crypto.KeccakState // Keccak256 hasher instance shared across opcodes 91 hasherBuf common.Hash // Keccak256 hasher result array shared across opcodes 92 93 readOnly bool // Whether to throw on stateful modifications 94 returnData []byte // Last CALL's return data for subsequent reuse 95 } 96 97 // NewEVMInterpreter returns a new instance of the Interpreter. 98 func NewEVMInterpreter(evm *EVM) *EVMInterpreter { 99 // If jump table was not initialised we set the default one. 100 var table *JumpTable 101 switch { 102 case evm.chainRules.IsVerkle: 103 // TODO replace with proper instruction set when fork is specified 104 table = &verkleInstructionSet 105 case evm.chainRules.IsCancun: 106 table = &cancunInstructionSet 107 case evm.chainRules.IsShanghai: 108 table = &shanghaiInstructionSet 109 case evm.chainRules.IsMerge: 110 table = &mergeInstructionSet 111 case evm.chainRules.IsLondon: 112 table = &londonInstructionSet 113 case evm.chainRules.IsBerlin: 114 table = &berlinInstructionSet 115 case evm.chainRules.IsIstanbul: 116 table = &istanbulInstructionSet 117 case evm.chainRules.IsConstantinople: 118 table = &constantinopleInstructionSet 119 case evm.chainRules.IsByzantium: 120 table = &byzantiumInstructionSet 121 case evm.chainRules.IsEIP158: 122 table = &spuriousDragonInstructionSet 123 case evm.chainRules.IsEIP150: 124 table = &tangerineWhistleInstructionSet 125 case evm.chainRules.IsHomestead: 126 table = &homesteadInstructionSet 127 default: 128 table = &frontierInstructionSet 129 } 130 var extraEips []int 131 if len(evm.Config.ExtraEips) > 0 { 132 // Deep-copy jumptable to prevent modification of opcodes in other tables 133 table = copyJumpTable(table) 134 } 135 for _, eip := range evm.Config.ExtraEips { 136 if err := EnableEIP(eip, table); err != nil { 137 // Disable it, so caller can check if it's activated or not 138 log.Error("EIP activation failed", "eip", eip, "error", err) 139 } else { 140 extraEips = append(extraEips, eip) 141 } 142 } 143 evm.Config.ExtraEips = extraEips 144 return &EVMInterpreter{evm: evm, table: table} 145 } 146 147 // Run loops and evaluates the contract's code with the given input data and returns 148 // the return byte-slice and an error if one occurred. 149 // 150 // It's important to note that any errors returned by the interpreter should be 151 // considered a revert-and-consume-all-gas operation except for 152 // ErrExecutionReverted which means revert-and-keep-gas-left. 153 func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) { 154 // Increment the call depth which is restricted to 1024 155 in.evm.depth++ 156 defer func() { in.evm.depth-- }() 157 158 // Make sure the readOnly is only set if we aren't in readOnly yet. 159 // This also makes sure that the readOnly flag isn't removed for child calls. 160 if readOnly && !in.readOnly { 161 in.readOnly = true 162 defer func() { in.readOnly = false }() 163 } 164 165 // Reset the previous call's return data. It's unimportant to preserve the old buffer 166 // as every returning call will return new data anyway. 167 in.returnData = nil 168 169 // Don't bother with the execution if there's no code. 170 if len(contract.Code) == 0 { 171 return nil, nil 172 } 173 174 var ( 175 op OpCode // current opcode 176 mem = NewMemory() // bound memory 177 stack = newstack() // local stack 178 callContext = &ScopeContext{ 179 Memory: mem, 180 Stack: stack, 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 EVMLogger 190 gasCopy uint64 // for EVMLogger to log gas remaining before execution 191 logged bool // deferred EVMLogger should ignore already logged steps 192 res []byte // result of the opcode execution function 193 debug = in.evm.Config.Tracer != nil 194 ) 195 // Don't move this deferred function, it's placed before the OnOpcode-deferred method, 196 // so that it gets executed _after_: the OnOpcode needs the stacks before 197 // they are returned to the pools 198 defer func() { 199 returnStack(stack) 200 }() 201 contract.Input = input 202 203 if debug { 204 defer func() { // this deferred method handles exit-with-error 205 if err == nil { 206 return 207 } 208 if !logged && in.evm.Config.Tracer.OnOpcode != nil { 209 in.evm.Config.Tracer.OnOpcode(pcCopy, byte(op), gasCopy, cost, callContext, in.returnData, in.evm.depth, VMErrorFromErr(err)) 210 } 211 if logged && in.evm.Config.Tracer.OnFault != nil { 212 in.evm.Config.Tracer.OnFault(pcCopy, byte(op), gasCopy, cost, callContext, in.evm.depth, VMErrorFromErr(err)) 213 } 214 }() 215 } 216 // The Interpreter main run loop (contextual). This loop runs until either an 217 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 218 // the execution of one of the operations or until the done flag is set by the 219 // parent context. 220 for { 221 if debug { 222 // Capture pre-execution values for tracing. 223 logged, pcCopy, gasCopy = false, pc, contract.Gas 224 } 225 226 if in.evm.chainRules.IsEIP4762 && !contract.IsDeployment { 227 // if the PC ends up in a new "chunk" of verkleized code, charge the 228 // associated costs. 229 contractAddr := contract.Address() 230 contract.Gas -= in.evm.TxContext.AccessEvents.CodeChunksRangeGas(contractAddr, pc, 1, uint64(len(contract.Code)), false) 231 } 232 233 // Get the operation from the jump table and validate the stack to ensure there are 234 // enough stack items available to perform the operation. 235 op = contract.GetOp(pc) 236 operation := in.table[op] 237 cost = operation.constantGas // For tracing 238 // Validate stack 239 if sLen := stack.len(); sLen < operation.minStack { 240 return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack} 241 } else if sLen > operation.maxStack { 242 return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack} 243 } 244 if !contract.UseGas(cost, in.evm.Config.Tracer, tracing.GasChangeIgnored) { 245 return nil, ErrOutOfGas 246 } 247 248 if operation.dynamicGas != nil { 249 // All ops with a dynamic memory usage also has a dynamic gas cost. 250 var memorySize uint64 251 // calculate the new memory size and expand the memory to fit 252 // the operation 253 // Memory check needs to be done prior to evaluating the dynamic gas portion, 254 // to detect calculation overflows 255 if operation.memorySize != nil { 256 memSize, overflow := operation.memorySize(stack) 257 if overflow { 258 return nil, ErrGasUintOverflow 259 } 260 // memory is expanded in words of 32 bytes. Gas 261 // is also calculated in words. 262 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 263 return nil, ErrGasUintOverflow 264 } 265 } 266 // Consume the gas and return an error if not enough gas is available. 267 // cost is explicitly set so that the capture state defer method can get the proper cost 268 var dynamicCost uint64 269 dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize) 270 cost += dynamicCost // for tracing 271 if err != nil { 272 return nil, fmt.Errorf("%w: %v", ErrOutOfGas, err) 273 } 274 if !contract.UseGas(dynamicCost, in.evm.Config.Tracer, tracing.GasChangeIgnored) { 275 return nil, ErrOutOfGas 276 } 277 278 // Do tracing before memory expansion 279 if debug { 280 if in.evm.Config.Tracer.OnGasChange != nil { 281 in.evm.Config.Tracer.OnGasChange(gasCopy, gasCopy-cost, tracing.GasChangeCallOpCode) 282 } 283 if in.evm.Config.Tracer.OnOpcode != nil { 284 in.evm.Config.Tracer.OnOpcode(pc, byte(op), gasCopy, cost, callContext, in.returnData, in.evm.depth, VMErrorFromErr(err)) 285 logged = true 286 } 287 } 288 if memorySize > 0 { 289 mem.Resize(memorySize) 290 } 291 } else if debug { 292 if in.evm.Config.Tracer.OnGasChange != nil { 293 in.evm.Config.Tracer.OnGasChange(gasCopy, gasCopy-cost, tracing.GasChangeCallOpCode) 294 } 295 if in.evm.Config.Tracer.OnOpcode != nil { 296 in.evm.Config.Tracer.OnOpcode(pc, byte(op), gasCopy, cost, callContext, in.returnData, in.evm.depth, VMErrorFromErr(err)) 297 logged = true 298 } 299 } 300 301 // execute the operation 302 res, err = operation.execute(&pc, in, callContext) 303 if err != nil { 304 break 305 } 306 pc++ 307 } 308 309 if err == errStopToken { 310 err = nil // clear stop token error 311 } 312 313 return res, err 314 }