github.com/calmw/ethereum@v0.1.1/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 "github.com/calmw/ethereum/common" 21 "github.com/calmw/ethereum/common/math" 22 "github.com/calmw/ethereum/crypto" 23 "github.com/calmw/ethereum/log" 24 ) 25 26 // Config are the configuration options for the Interpreter 27 type Config struct { 28 Tracer EVMLogger // Opcode logger 29 NoBaseFee bool // Forces the EIP-1559 baseFee to 0 (needed for 0 price calls) 30 EnablePreimageRecording bool // Enables recording of SHA3/keccak preimages 31 ExtraEips []int // Additional EIPS that are to be enabled 32 } 33 34 // ScopeContext contains the things that are per-call, such as stack and memory, 35 // but not transients like pc and gas 36 type ScopeContext struct { 37 Memory *Memory 38 Stack *Stack 39 Contract *Contract 40 } 41 42 // EVMInterpreter represents an EVM interpreter 43 type EVMInterpreter struct { 44 evm *EVM 45 table *JumpTable 46 47 hasher crypto.KeccakState // Keccak256 hasher instance shared across opcodes 48 hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes 49 50 readOnly bool // Whether to throw on stateful modifications 51 returnData []byte // Last CALL's return data for subsequent reuse 52 } 53 54 // NewEVMInterpreter returns a new instance of the Interpreter. 55 func NewEVMInterpreter(evm *EVM) *EVMInterpreter { 56 // If jump table was not initialised we set the default one. 57 var table *JumpTable 58 switch { 59 case evm.chainRules.IsShanghai: 60 table = &shanghaiInstructionSet 61 case evm.chainRules.IsMerge: 62 table = &mergeInstructionSet 63 case evm.chainRules.IsLondon: 64 table = &londonInstructionSet 65 case evm.chainRules.IsBerlin: 66 table = &berlinInstructionSet 67 case evm.chainRules.IsIstanbul: 68 table = &istanbulInstructionSet 69 case evm.chainRules.IsConstantinople: 70 table = &constantinopleInstructionSet 71 case evm.chainRules.IsByzantium: 72 table = &byzantiumInstructionSet 73 case evm.chainRules.IsEIP158: 74 table = &spuriousDragonInstructionSet 75 case evm.chainRules.IsEIP150: 76 table = &tangerineWhistleInstructionSet 77 case evm.chainRules.IsHomestead: 78 table = &homesteadInstructionSet 79 default: 80 table = &frontierInstructionSet 81 } 82 var extraEips []int 83 if len(evm.Config.ExtraEips) > 0 { 84 // Deep-copy jumptable to prevent modification of opcodes in other tables 85 table = copyJumpTable(table) 86 } 87 for _, eip := range evm.Config.ExtraEips { 88 if err := EnableEIP(eip, table); err != nil { 89 // Disable it, so caller can check if it's activated or not 90 log.Error("EIP activation failed", "eip", eip, "error", err) 91 } else { 92 extraEips = append(extraEips, eip) 93 } 94 } 95 evm.Config.ExtraEips = extraEips 96 return &EVMInterpreter{evm: evm, table: table} 97 } 98 99 // Run loops and evaluates the contract's code with the given input data and returns 100 // the return byte-slice and an error if one occurred. 101 // 102 // It's important to note that any errors returned by the interpreter should be 103 // considered a revert-and-consume-all-gas operation except for 104 // ErrExecutionReverted which means revert-and-keep-gas-left. 105 func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) { 106 // Increment the call depth which is restricted to 1024 107 in.evm.depth++ 108 defer func() { in.evm.depth-- }() 109 110 // Make sure the readOnly is only set if we aren't in readOnly yet. 111 // This also makes sure that the readOnly flag isn't removed for child calls. 112 if readOnly && !in.readOnly { 113 in.readOnly = true 114 defer func() { in.readOnly = false }() 115 } 116 117 // Reset the previous call's return data. It's unimportant to preserve the old buffer 118 // as every returning call will return new data anyway. 119 in.returnData = nil 120 121 // Don't bother with the execution if there's no code. 122 if len(contract.Code) == 0 { 123 return nil, nil 124 } 125 126 var ( 127 op OpCode // current opcode 128 mem = NewMemory() // bound memory 129 stack = newstack() // local stack 130 callContext = &ScopeContext{ 131 Memory: mem, 132 Stack: stack, 133 Contract: contract, 134 } 135 // For optimisation reason we're using uint64 as the program counter. 136 // It's theoretically possible to go above 2^64. The YP defines the PC 137 // to be uint256. Practically much less so feasible. 138 pc = uint64(0) // program counter 139 cost uint64 140 // copies used by tracer 141 pcCopy uint64 // needed for the deferred EVMLogger 142 gasCopy uint64 // for EVMLogger to log gas remaining before execution 143 logged bool // deferred EVMLogger should ignore already logged steps 144 res []byte // result of the opcode execution function 145 debug = in.evm.Config.Tracer != nil 146 ) 147 // Don't move this deferred function, it's placed before the capturestate-deferred method, 148 // so that it get's executed _after_: the capturestate needs the stacks before 149 // they are returned to the pools 150 defer func() { 151 returnStack(stack) 152 }() 153 contract.Input = input 154 155 if debug { 156 defer func() { 157 if err != nil { 158 if !logged { 159 in.evm.Config.Tracer.CaptureState(pcCopy, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 160 } else { 161 in.evm.Config.Tracer.CaptureFault(pcCopy, op, gasCopy, cost, callContext, in.evm.depth, err) 162 } 163 } 164 }() 165 } 166 // The Interpreter main run loop (contextual). This loop runs until either an 167 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 168 // the execution of one of the operations or until the done flag is set by the 169 // parent context. 170 for { 171 if debug { 172 // Capture pre-execution values for tracing. 173 logged, pcCopy, gasCopy = false, pc, contract.Gas 174 } 175 // Get the operation from the jump table and validate the stack to ensure there are 176 // enough stack items available to perform the operation. 177 op = contract.GetOp(pc) 178 operation := in.table[op] 179 cost = operation.constantGas // For tracing 180 // Validate stack 181 if sLen := stack.len(); sLen < operation.minStack { 182 return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack} 183 } else if sLen > operation.maxStack { 184 return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack} 185 } 186 if !contract.UseGas(cost) { 187 return nil, ErrOutOfGas 188 } 189 if operation.dynamicGas != nil { 190 // All ops with a dynamic memory usage also has a dynamic gas cost. 191 var memorySize uint64 192 // calculate the new memory size and expand the memory to fit 193 // the operation 194 // Memory check needs to be done prior to evaluating the dynamic gas portion, 195 // to detect calculation overflows 196 if operation.memorySize != nil { 197 memSize, overflow := operation.memorySize(stack) 198 if overflow { 199 return nil, ErrGasUintOverflow 200 } 201 // memory is expanded in words of 32 bytes. Gas 202 // is also calculated in words. 203 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 204 return nil, ErrGasUintOverflow 205 } 206 } 207 // Consume the gas and return an error if not enough gas is available. 208 // cost is explicitly set so that the capture state defer method can get the proper cost 209 var dynamicCost uint64 210 dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize) 211 cost += dynamicCost // for tracing 212 if err != nil || !contract.UseGas(dynamicCost) { 213 return nil, ErrOutOfGas 214 } 215 // Do tracing before memory expansion 216 if debug { 217 in.evm.Config.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 218 logged = true 219 } 220 if memorySize > 0 { 221 mem.Resize(memorySize) 222 } 223 } else if debug { 224 in.evm.Config.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 225 logged = true 226 } 227 // execute the operation 228 res, err = operation.execute(&pc, in, callContext) 229 if err != nil { 230 break 231 } 232 pc++ 233 } 234 235 if err == errStopToken { 236 err = nil // clear stop token error 237 } 238 239 return res, err 240 }