github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/core/vm/interpreter.go (about) 1 // Copyright 2014 The go-simplechain Authors 2 // This file is part of the go-simplechain library. 3 // 4 // The go-simplechain 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-simplechain 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-simplechain 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/bigzoro/my_simplechain/common" 25 "github.com/bigzoro/my_simplechain/common/math" 26 "github.com/bigzoro/my_simplechain/log" 27 ) 28 29 // Config are the configuration options for the Interpreter 30 type Config struct { 31 Debug bool // Enables debugging 32 Tracer Tracer // Opcode logger 33 NoRecursion bool // Disables call, callcode, delegate call and create 34 EnablePreimageRecording bool // Enables recording of SHA3/keccak preimages 35 36 JumpTable [256]operation // EVM instruction table, automatically populated if unset 37 38 EWASMInterpreter string // External EWASM interpreter options 39 EVMInterpreter string // External EVM interpreter options 40 41 ExtraEips []int // Additional EIPS that are to be enabled 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, static bool) ([]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 } 65 66 // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports 67 // Read to get a variable amount of data from the hash state. Read is faster than Sum 68 // because it doesn't copy the internal state, but also modifies the internal state. 69 type keccakState interface { 70 hash.Hash 71 Read([]byte) (int, error) 72 } 73 74 // EVMInterpreter represents an EVM interpreter 75 type EVMInterpreter struct { 76 evm *EVM 77 cfg Config 78 79 intPool *intPool 80 81 hasher keccakState // Keccak256 hasher instance shared across opcodes 82 hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes 83 84 readOnly bool // Whether to throw on stateful modifications 85 returnData []byte // Last CALL's return data for subsequent reuse 86 } 87 88 // NewEVMInterpreter returns a new instance of the Interpreter. 89 func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter { 90 // We use the STOP instruction whether to see 91 // the jump table was initialised. If it was not 92 // we'll set the default jump table. 93 if !cfg.JumpTable[STOP].valid { 94 var jt JumpTable 95 switch { 96 case evm.chainRules.IsSingularity: 97 jt = singularityInstructionSet 98 default: 99 jt = constantinopleInstructionSet 100 } 101 for i, eip := range cfg.ExtraEips { 102 if err := EnableEIP(eip, &jt); err != nil { 103 // Disable it, so caller can check if it's activated or not 104 cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...) 105 log.Error("EIP activation failed", "eip", eip, "error", err) 106 } 107 } 108 enableNonce(&jt) // enable nonce for cross transaction 109 cfg.JumpTable = jt 110 } 111 112 return &EVMInterpreter{ 113 evm: evm, 114 cfg: cfg, 115 } 116 } 117 118 // Run loops and evaluates the contract's code with the given input data and returns 119 // the return byte-slice and an error if one occurred. 120 // 121 // It's important to note that any errors returned by the interpreter should be 122 // considered a revert-and-consume-all-gas operation except for 123 // errExecutionReverted which means revert-and-keep-gas-left. 124 func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) { 125 if in.intPool == nil { 126 in.intPool = poolOfIntPools.get() 127 defer func() { 128 poolOfIntPools.put(in.intPool) 129 in.intPool = nil 130 }() 131 } 132 133 // Increment the call depth which is restricted to 1024 134 in.evm.depth++ 135 defer func() { in.evm.depth-- }() 136 137 // Make sure the readOnly is only set if we aren't in readOnly yet. 138 // This makes also sure that the readOnly flag isn't removed for child calls. 139 if readOnly && !in.readOnly { 140 in.readOnly = true 141 defer func() { in.readOnly = false }() 142 } 143 144 // Reset the previous call's return data. It's unimportant to preserve the old buffer 145 // as every returning call will return new data anyway. 146 in.returnData = nil 147 148 // Don't bother with the execution if there's no code. 149 if len(contract.Code) == 0 { 150 return nil, nil 151 } 152 153 var ( 154 op OpCode // current opcode 155 mem = NewMemory() // bound memory 156 stack = newstack() // local stack 157 // For optimisation reason we're using uint64 as the program counter. 158 // It's theoretically possible to go above 2^64. The YP defines the PC 159 // to be uint256. Practically much less so feasible. 160 pc = uint64(0) // program counter 161 cost uint64 162 // copies used by tracer 163 pcCopy uint64 // needed for the deferred Tracer 164 gasCopy uint64 // for Tracer to log gas remaining before execution 165 logged bool // deferred Tracer should ignore already logged steps 166 res []byte // result of the opcode execution function 167 ) 168 contract.Input = input 169 170 // Reclaim the stack as an int pool when the execution stops 171 defer func() { in.intPool.put(stack.data...) }() 172 173 if in.cfg.Debug { 174 defer func() { 175 if err != nil { 176 if !logged { 177 in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 178 } else { 179 in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 180 } 181 } 182 }() 183 } 184 // The Interpreter main run loop (contextual). This loop runs until either an 185 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 186 // the execution of one of the operations or until the done flag is set by the 187 // parent context. 188 for atomic.LoadInt32(&in.evm.abort) == 0 { 189 if in.cfg.Debug { 190 // Capture pre-execution values for tracing. 191 logged, pcCopy, gasCopy = false, pc, contract.Gas 192 } 193 194 // Get the operation from the jump table and validate the stack to ensure there are 195 // enough stack items available to perform the operation. 196 op = contract.GetOp(pc) 197 operation := in.cfg.JumpTable[op] 198 if !operation.valid { 199 return nil, fmt.Errorf("invalid opcode 0x%x", int(op)) 200 } 201 // Validate stack 202 if sLen := stack.len(); sLen < operation.minStack { 203 return nil, fmt.Errorf("stack underflow (%d <=> %d)", sLen, operation.minStack) 204 } else if sLen > operation.maxStack { 205 return nil, fmt.Errorf("stack limit reached %d (%d)", sLen, operation.maxStack) 206 } 207 // If the operation is valid, enforce and write restrictions 208 if in.readOnly { 209 // If the interpreter is operating in readonly mode, make sure no 210 // state-modifying operation is performed. The 3rd stack item 211 // for a call operation is the value. Transferring value from one 212 // account to the others means the state is modified and should also 213 // return with an error. 214 if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) { 215 return nil, errWriteProtection 216 } 217 } 218 // Static portion of gas 219 cost = operation.constantGas // For tracing 220 if !contract.UseGas(operation.constantGas) { 221 return nil, ErrOutOfGas 222 } 223 224 var memorySize uint64 225 // calculate the new memory size and expand the memory to fit 226 // the operation 227 // Memory check needs to be done prior to evaluating the dynamic gas portion, 228 // to detect calculation overflows 229 if operation.memorySize != nil { 230 memSize, overflow := operation.memorySize(stack) 231 if overflow { 232 return nil, errGasUintOverflow 233 } 234 // memory is expanded in words of 32 bytes. Gas 235 // is also calculated in words. 236 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 237 return nil, errGasUintOverflow 238 } 239 } 240 // Dynamic portion of gas 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 if operation.dynamicGas != nil { 244 var dynamicCost uint64 245 dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize) 246 cost += dynamicCost // total cost, for debug tracing 247 if err != nil || !contract.UseGas(dynamicCost) { 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 }