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