github.com/gobitfly/go-ethereum@v1.8.12/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/ethereum/go-ethereum/common/math" 24 "github.com/ethereum/go-ethereum/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 struct { 49 evm *EVM 50 cfg Config 51 gasTable params.GasTable 52 intPool *intPool 53 54 readOnly bool // Whether to throw on stateful modifications 55 returnData []byte // Last CALL's return data for subsequent reuse 56 } 57 58 // NewInterpreter returns a new instance of the Interpreter. 59 func NewInterpreter(evm *EVM, cfg Config) *Interpreter { 60 // We use the STOP instruction whether to see 61 // the jump table was initialised. If it was not 62 // we'll set the default jump table. 63 if !cfg.JumpTable[STOP].valid { 64 switch { 65 case evm.ChainConfig().IsConstantinople(evm.BlockNumber): 66 cfg.JumpTable = constantinopleInstructionSet 67 case evm.ChainConfig().IsByzantium(evm.BlockNumber): 68 cfg.JumpTable = byzantiumInstructionSet 69 case evm.ChainConfig().IsHomestead(evm.BlockNumber): 70 cfg.JumpTable = homesteadInstructionSet 71 default: 72 cfg.JumpTable = frontierInstructionSet 73 } 74 } 75 76 return &Interpreter{ 77 evm: evm, 78 cfg: cfg, 79 gasTable: evm.ChainConfig().GasTable(evm.BlockNumber), 80 } 81 } 82 83 func (in *Interpreter) enforceRestrictions(op OpCode, operation operation, stack *Stack) error { 84 if in.evm.chainRules.IsByzantium { 85 if in.readOnly { 86 // If the interpreter is operating in readonly mode, make sure no 87 // state-modifying operation is performed. The 3rd stack item 88 // for a call operation is the value. Transferring value from one 89 // account to the others means the state is modified and should also 90 // return with an error. 91 if operation.writes || (op == CALL && stack.Back(2).BitLen() > 0) { 92 return errWriteProtection 93 } 94 } 95 } 96 return nil 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 *Interpreter) Run(contract *Contract, input []byte) (ret []byte, err error) { 106 if in.intPool == nil { 107 in.intPool = poolOfIntPools.get() 108 defer func() { 109 poolOfIntPools.put(in.intPool) 110 in.intPool = nil 111 }() 112 } 113 114 // Increment the call depth which is restricted to 1024 115 in.evm.depth++ 116 defer func() { in.evm.depth-- }() 117 118 // Reset the previous call's return data. It's unimportant to preserve the old buffer 119 // as every returning call will return new data anyway. 120 in.returnData = nil 121 122 // Don't bother with the execution if there's no code. 123 if len(contract.Code) == 0 { 124 return nil, nil 125 } 126 127 var ( 128 op OpCode // current opcode 129 mem = NewMemory() // bound memory 130 stack = newstack() // local stack 131 // For optimisation reason we're using uint64 as the program counter. 132 // It's theoretically possible to go above 2^64. The YP defines the PC 133 // to be uint256. Practically much less so feasible. 134 pc = uint64(0) // program counter 135 cost uint64 136 // copies used by tracer 137 pcCopy uint64 // needed for the deferred Tracer 138 gasCopy uint64 // for Tracer to log gas remaining before execution 139 logged bool // deferred Tracer should ignore already logged steps 140 ) 141 contract.Input = input 142 143 // Reclaim the stack as an int pool when the execution stops 144 defer func() { in.intPool.put(stack.data...) }() 145 146 if in.cfg.Debug { 147 defer func() { 148 if err != nil { 149 if !logged { 150 in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 151 } else { 152 in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 153 } 154 } 155 }() 156 } 157 // The Interpreter main run loop (contextual). This loop runs until either an 158 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 159 // the execution of one of the operations or until the done flag is set by the 160 // parent context. 161 for atomic.LoadInt32(&in.evm.abort) == 0 { 162 if in.cfg.Debug { 163 // Capture pre-execution values for tracing. 164 logged, pcCopy, gasCopy = false, pc, contract.Gas 165 } 166 167 // Get the operation from the jump table and validate the stack to ensure there are 168 // enough stack items available to perform the operation. 169 op = contract.GetOp(pc) 170 operation := in.cfg.JumpTable[op] 171 if !operation.valid { 172 return nil, fmt.Errorf("invalid opcode 0x%x", int(op)) 173 } 174 if err := operation.validateStack(stack); err != nil { 175 return nil, err 176 } 177 // If the operation is valid, enforce and write restrictions 178 if err := in.enforceRestrictions(op, operation, stack); err != nil { 179 return nil, err 180 } 181 182 var memorySize uint64 183 // calculate the new memory size and expand the memory to fit 184 // the operation 185 if operation.memorySize != nil { 186 memSize, overflow := bigUint64(operation.memorySize(stack)) 187 if overflow { 188 return nil, errGasUintOverflow 189 } 190 // memory is expanded in words of 32 bytes. Gas 191 // is also calculated in words. 192 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 193 return nil, errGasUintOverflow 194 } 195 } 196 // consume the gas and return an error if not enough gas is available. 197 // cost is explicitly set so that the capture state defer method can get the proper cost 198 cost, err = operation.gasCost(in.gasTable, in.evm, contract, stack, mem, memorySize) 199 if err != nil || !contract.UseGas(cost) { 200 return nil, ErrOutOfGas 201 } 202 if memorySize > 0 { 203 mem.Resize(memorySize) 204 } 205 206 if in.cfg.Debug { 207 in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 208 logged = true 209 } 210 211 // execute the operation 212 res, err := operation.execute(&pc, in.evm, contract, mem, stack) 213 // verifyPool is a build flag. Pool verification makes sure the integrity 214 // of the integer pool by comparing values to a default value. 215 if verifyPool { 216 verifyIntegerPool(in.intPool) 217 } 218 // if the operation clears the return data (e.g. it has returning data) 219 // set the last return to the result of the operation. 220 if operation.returns { 221 in.returnData = res 222 } 223 224 switch { 225 case err != nil: 226 return nil, err 227 case operation.reverts: 228 return res, errExecutionReverted 229 case operation.halts: 230 return res, nil 231 case !operation.jumps: 232 pc++ 233 } 234 } 235 return nil, nil 236 }