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