github.com/luckypickle/go-ethereum-vet@v1.14.2/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 "sync/atomic" 22 23 "github.com/luckypickle/go-ethereum-vet/common/math" 24 "github.com/luckypickle/go-ethereum-vet/params" 25 ) 26 27 // Config are the configuration options for the Interpreter 28 type Config struct { 29 // Debug enabled debugging Interpreter options 30 Debug bool 31 // Tracer is the op code logger 32 Tracer Tracer 33 // NoRecursion disabled Interpreter call, callcode, 34 // delegate call and create. 35 NoRecursion bool 36 // Enable recording of SHA3/keccak preimages 37 EnablePreimageRecording bool 38 // JumpTable contains the EVM instruction table. This 39 // may be left uninitialised and will be set to the default 40 // table. 41 JumpTable [256]operation 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) ([]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 // IsReadOnly reports if the interpreter is in read only mode. 65 IsReadOnly() bool 66 // SetReadOnly sets (or unsets) read only mode in the interpreter. 67 SetReadOnly(bool) 68 } 69 70 // EVMInterpreter represents an EVM interpreter 71 type EVMInterpreter struct { 72 evm *EVM 73 cfg Config 74 gasTable params.GasTable 75 intPool *intPool 76 77 readOnly bool // Whether to throw on stateful modifications 78 returnData []byte // Last CALL's return data for subsequent reuse 79 } 80 81 // NewEVMInterpreter returns a new instance of the Interpreter. 82 func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter { 83 // We use the STOP instruction whether to see 84 // the jump table was initialised. If it was not 85 // we'll set the default jump table. 86 if !cfg.JumpTable[STOP].valid { 87 switch { 88 case evm.ChainConfig().IsConstantinople(evm.BlockNumber): 89 cfg.JumpTable = constantinopleInstructionSet 90 case evm.ChainConfig().IsByzantium(evm.BlockNumber): 91 cfg.JumpTable = byzantiumInstructionSet 92 case evm.ChainConfig().IsHomestead(evm.BlockNumber): 93 cfg.JumpTable = homesteadInstructionSet 94 default: 95 cfg.JumpTable = frontierInstructionSet 96 } 97 } 98 99 return &EVMInterpreter{ 100 evm: evm, 101 cfg: cfg, 102 gasTable: evm.ChainConfig().GasTable(evm.BlockNumber), 103 } 104 } 105 106 func (in *EVMInterpreter) enforceRestrictions(op OpCode, operation operation, stack *Stack) error { 107 if in.evm.chainRules.IsByzantium { 108 if in.readOnly { 109 // If the interpreter is operating in readonly mode, make sure no 110 // state-modifying operation is performed. The 3rd stack item 111 // for a call operation is the value. Transferring value from one 112 // account to the others means the state is modified and should also 113 // return with an error. 114 if operation.writes || (op == CALL && stack.Back(2).BitLen() > 0) { 115 return errWriteProtection 116 } 117 } 118 } 119 return nil 120 } 121 122 // Run loops and evaluates the contract's code with the given input data and returns 123 // the return byte-slice and an error if one occurred. 124 // 125 // It's important to note that any errors returned by the interpreter should be 126 // considered a revert-and-consume-all-gas operation except for 127 // errExecutionReverted which means revert-and-keep-gas-left. 128 func (in *EVMInterpreter) Run(contract *Contract, input []byte) (ret []byte, err error) { 129 if in.intPool == nil { 130 in.intPool = poolOfIntPools.get() 131 defer func() { 132 poolOfIntPools.put(in.intPool) 133 in.intPool = nil 134 }() 135 } 136 137 // Increment the call depth which is restricted to 1024 138 in.evm.depth++ 139 defer func() { in.evm.depth-- }() 140 141 // Reset the previous call's return data. It's unimportant to preserve the old buffer 142 // as every returning call will return new data anyway. 143 in.returnData = nil 144 145 // Don't bother with the execution if there's no code. 146 if len(contract.Code) == 0 { 147 return nil, nil 148 } 149 150 var ( 151 op OpCode // current opcode 152 mem = NewMemory() // bound memory 153 stack = newstack() // local stack 154 // For optimisation reason we're using uint64 as the program counter. 155 // It's theoretically possible to go above 2^64. The YP defines the PC 156 // to be uint256. Practically much less so feasible. 157 pc = uint64(0) // program counter 158 cost uint64 159 // copies used by tracer 160 pcCopy uint64 // needed for the deferred Tracer 161 gasCopy uint64 // for Tracer to log gas remaining before execution 162 logged bool // deferred Tracer should ignore already logged steps 163 ) 164 contract.Input = input 165 166 // Reclaim the stack as an int pool when the execution stops 167 defer func() { in.intPool.put(stack.data...) }() 168 169 if in.cfg.Debug { 170 defer func() { 171 if err != nil { 172 if !logged { 173 in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 174 } else { 175 in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 176 } 177 } 178 }() 179 } 180 // The Interpreter main run loop (contextual). This loop runs until either an 181 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 182 // the execution of one of the operations or until the done flag is set by the 183 // parent context. 184 for atomic.LoadInt32(&in.evm.abort) == 0 { 185 if in.cfg.Debug { 186 // Capture pre-execution values for tracing. 187 logged, pcCopy, gasCopy = false, pc, contract.Gas 188 } 189 190 // Get the operation from the jump table and validate the stack to ensure there are 191 // enough stack items available to perform the operation. 192 op = contract.GetOp(pc) 193 operation := in.cfg.JumpTable[op] 194 if !operation.valid { 195 return nil, fmt.Errorf("invalid opcode 0x%x", int(op)) 196 } 197 if err := operation.validateStack(stack); err != nil { 198 return nil, err 199 } 200 // If the operation is valid, enforce and write restrictions 201 if err := in.enforceRestrictions(op, operation, stack); err != nil { 202 return nil, err 203 } 204 205 var memorySize uint64 206 // calculate the new memory size and expand the memory to fit 207 // the operation 208 if operation.memorySize != nil { 209 memSize, overflow := bigUint64(operation.memorySize(stack)) 210 if overflow { 211 return nil, errGasUintOverflow 212 } 213 // memory is expanded in words of 32 bytes. Gas 214 // is also calculated in words. 215 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 216 return nil, errGasUintOverflow 217 } 218 } 219 // consume the gas and return an error if not enough gas is available. 220 // cost is explicitly set so that the capture state defer method can get the proper cost 221 cost, err = operation.gasCost(in.gasTable, in.evm, contract, stack, mem, memorySize) 222 if err != nil || !contract.UseGas(cost) { 223 return nil, ErrOutOfGas 224 } 225 if memorySize > 0 { 226 mem.Resize(memorySize) 227 } 228 229 if in.cfg.Debug { 230 in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 231 logged = true 232 } 233 234 // execute the operation 235 res, err := operation.execute(&pc, in, contract, mem, stack) 236 // verifyPool is a build flag. Pool verification makes sure the integrity 237 // of the integer pool by comparing values to a default value. 238 if verifyPool { 239 verifyIntegerPool(in.intPool) 240 } 241 // if the operation clears the return data (e.g. it has returning data) 242 // set the last return to the result of the operation. 243 if operation.returns { 244 in.returnData = res 245 } 246 247 switch { 248 case err != nil: 249 return nil, err 250 case operation.reverts: 251 return res, errExecutionReverted 252 case operation.halts: 253 return res, nil 254 case !operation.jumps: 255 pc++ 256 } 257 } 258 return nil, nil 259 } 260 261 // CanRun tells if the contract, passed as an argument, can be 262 // run by the current interpreter. 263 func (in *EVMInterpreter) CanRun(code []byte) bool { 264 return true 265 } 266 267 // IsReadOnly reports if the interpreter is in read only mode. 268 func (in *EVMInterpreter) IsReadOnly() bool { 269 return in.readOnly 270 } 271 272 // SetReadOnly sets (or unsets) read only mode in the interpreter. 273 func (in *EVMInterpreter) SetReadOnly(ro bool) { 274 in.readOnly = ro 275 }