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