github.com/theQRL/go-zond@v0.1.1/core/vm/evm.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 "math/big" 21 "sync/atomic" 22 23 "github.com/holiman/uint256" 24 "github.com/theQRL/go-zond/common" 25 "github.com/theQRL/go-zond/core/types" 26 "github.com/theQRL/go-zond/crypto" 27 "github.com/theQRL/go-zond/params" 28 ) 29 30 type ( 31 // CanTransferFunc is the signature of a transfer guard function 32 CanTransferFunc func(StateDB, common.Address, *big.Int) bool 33 // TransferFunc is the signature of a transfer function 34 TransferFunc func(StateDB, common.Address, common.Address, *big.Int) 35 // GetHashFunc returns the n'th block hash in the blockchain 36 // and is used by the BLOCKHASH EVM op code. 37 GetHashFunc func(uint64) common.Hash 38 ) 39 40 func (evm *EVM) precompile(addr common.Address) (PrecompiledContract, bool) { 41 var precompiles map[common.Address]PrecompiledContract 42 switch { 43 case evm.chainRules.IsCancun: 44 precompiles = PrecompiledContractsCancun 45 case evm.chainRules.IsBerlin: 46 precompiles = PrecompiledContractsBerlin 47 case evm.chainRules.IsIstanbul: 48 precompiles = PrecompiledContractsIstanbul 49 case evm.chainRules.IsByzantium: 50 precompiles = PrecompiledContractsByzantium 51 default: 52 precompiles = PrecompiledContractsHomestead 53 } 54 p, ok := precompiles[addr] 55 return p, ok 56 } 57 58 // BlockContext provides the EVM with auxiliary information. Once provided 59 // it shouldn't be modified. 60 type BlockContext struct { 61 // CanTransfer returns whether the account contains 62 // sufficient ether to transfer the value 63 CanTransfer CanTransferFunc 64 // Transfer transfers ether from one account to the other 65 Transfer TransferFunc 66 // GetHash returns the hash corresponding to n 67 GetHash GetHashFunc 68 69 // Block information 70 Coinbase common.Address // Provides information for COINBASE 71 GasLimit uint64 // Provides information for GASLIMIT 72 BlockNumber *big.Int // Provides information for NUMBER 73 Time uint64 // Provides information for TIME 74 Difficulty *big.Int // Provides information for DIFFICULTY 75 BaseFee *big.Int // Provides information for BASEFEE 76 Random *common.Hash // Provides information for PREVRANDAO 77 ExcessBlobGas *uint64 // ExcessBlobGas field in the header, needed to compute the data 78 } 79 80 // TxContext provides the EVM with information about a transaction. 81 // All fields can change between transactions. 82 type TxContext struct { 83 // Message information 84 Origin common.Address // Provides information for ORIGIN 85 GasPrice *big.Int // Provides information for GASPRICE 86 BlobHashes []common.Hash // Provides information for BLOBHASH 87 } 88 89 // EVM is the Ethereum Virtual Machine base object and provides 90 // the necessary tools to run a contract on the given state with 91 // the provided context. It should be noted that any error 92 // generated through any of the calls should be considered a 93 // revert-state-and-consume-all-gas operation, no checks on 94 // specific errors should ever be performed. The interpreter makes 95 // sure that any errors generated are to be considered faulty code. 96 // 97 // The EVM should never be reused and is not thread safe. 98 type EVM struct { 99 // Context provides auxiliary blockchain related information 100 Context BlockContext 101 TxContext 102 // StateDB gives access to the underlying state 103 StateDB StateDB 104 // Depth is the current call stack 105 depth int 106 107 // chainConfig contains information about the current chain 108 chainConfig *params.ChainConfig 109 // chain rules contains the chain rules for the current epoch 110 chainRules params.Rules 111 // virtual machine configuration options used to initialise the 112 // evm. 113 Config Config 114 // global (to this context) ethereum virtual machine 115 // used throughout the execution of the tx. 116 interpreter *EVMInterpreter 117 // abort is used to abort the EVM calling operations 118 abort atomic.Bool 119 // callGasTemp holds the gas available for the current call. This is needed because the 120 // available gas is calculated in gasCall* according to the 63/64 rule and later 121 // applied in opCall*. 122 callGasTemp uint64 123 } 124 125 // NewEVM returns a new EVM. The returned EVM is not thread safe and should 126 // only ever be used *once*. 127 func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb StateDB, chainConfig *params.ChainConfig, config Config) *EVM { 128 evm := &EVM{ 129 Context: blockCtx, 130 TxContext: txCtx, 131 StateDB: statedb, 132 Config: config, 133 chainConfig: chainConfig, 134 chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time), 135 } 136 evm.interpreter = NewEVMInterpreter(evm) 137 return evm 138 } 139 140 // Reset resets the EVM with a new transaction context.Reset 141 // This is not threadsafe and should only be done very cautiously. 142 func (evm *EVM) Reset(txCtx TxContext, statedb StateDB) { 143 evm.TxContext = txCtx 144 evm.StateDB = statedb 145 } 146 147 // Cancel cancels any running EVM operation. This may be called concurrently and 148 // it's safe to be called multiple times. 149 func (evm *EVM) Cancel() { 150 evm.abort.Store(true) 151 } 152 153 // Cancelled returns true if Cancel has been called 154 func (evm *EVM) Cancelled() bool { 155 return evm.abort.Load() 156 } 157 158 // Interpreter returns the current interpreter 159 func (evm *EVM) Interpreter() *EVMInterpreter { 160 return evm.interpreter 161 } 162 163 // SetBlockContext updates the block context of the EVM. 164 func (evm *EVM) SetBlockContext(blockCtx BlockContext) { 165 evm.Context = blockCtx 166 num := blockCtx.BlockNumber 167 timestamp := blockCtx.Time 168 evm.chainRules = evm.chainConfig.Rules(num, blockCtx.Random != nil, timestamp) 169 } 170 171 // Call executes the contract associated with the addr with the given input as 172 // parameters. It also handles any necessary value transfer required and takes 173 // the necessary steps to create accounts and reverses the state in case of an 174 // execution error or failed value transfer. 175 func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { 176 // Fail if we're trying to execute above the call depth limit 177 if evm.depth > int(params.CallCreateDepth) { 178 return nil, gas, ErrDepth 179 } 180 // Fail if we're trying to transfer more than the available balance 181 if value.Sign() != 0 && !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 182 return nil, gas, ErrInsufficientBalance 183 } 184 snapshot := evm.StateDB.Snapshot() 185 p, isPrecompile := evm.precompile(addr) 186 debug := evm.Config.Tracer != nil 187 188 if !evm.StateDB.Exist(addr) { 189 if !isPrecompile && evm.chainRules.IsEIP158 && value.Sign() == 0 { 190 // Calling a non existing account, don't do anything, but ping the tracer 191 if debug { 192 if evm.depth == 0 { 193 evm.Config.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value) 194 evm.Config.Tracer.CaptureEnd(ret, 0, nil) 195 } else { 196 evm.Config.Tracer.CaptureEnter(CALL, caller.Address(), addr, input, gas, value) 197 evm.Config.Tracer.CaptureExit(ret, 0, nil) 198 } 199 } 200 return nil, gas, nil 201 } 202 evm.StateDB.CreateAccount(addr) 203 } 204 evm.Context.Transfer(evm.StateDB, caller.Address(), addr, value) 205 206 // Capture the tracer start/end events in debug mode 207 if debug { 208 if evm.depth == 0 { 209 evm.Config.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value) 210 defer func(startGas uint64) { // Lazy evaluation of the parameters 211 evm.Config.Tracer.CaptureEnd(ret, startGas-gas, err) 212 }(gas) 213 } else { 214 // Handle tracer events for entering and exiting a call frame 215 evm.Config.Tracer.CaptureEnter(CALL, caller.Address(), addr, input, gas, value) 216 defer func(startGas uint64) { 217 evm.Config.Tracer.CaptureExit(ret, startGas-gas, err) 218 }(gas) 219 } 220 } 221 222 if isPrecompile { 223 ret, gas, err = RunPrecompiledContract(p, input, gas) 224 } else { 225 // Initialise a new contract and set the code that is to be used by the EVM. 226 // The contract is a scoped environment for this execution context only. 227 code := evm.StateDB.GetCode(addr) 228 if len(code) == 0 { 229 ret, err = nil, nil // gas is unchanged 230 } else { 231 addrCopy := addr 232 // If the account has no code, we can abort here 233 // The depth-check is already done, and precompiles handled above 234 contract := NewContract(caller, AccountRef(addrCopy), value, gas) 235 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), code) 236 ret, err = evm.interpreter.Run(contract, input, false) 237 gas = contract.Gas 238 } 239 } 240 // When an error was returned by the EVM or when setting the creation code 241 // above we revert to the snapshot and consume any gas remaining. Additionally 242 // when we're in homestead this also counts for code storage gas errors. 243 if err != nil { 244 evm.StateDB.RevertToSnapshot(snapshot) 245 if err != ErrExecutionReverted { 246 gas = 0 247 } 248 // TODO: consider clearing up unused snapshots: 249 //} else { 250 // evm.StateDB.DiscardSnapshot(snapshot) 251 } 252 return ret, gas, err 253 } 254 255 // CallCode executes the contract associated with the addr with the given input 256 // as parameters. It also handles any necessary value transfer required and takes 257 // the necessary steps to create accounts and reverses the state in case of an 258 // execution error or failed value transfer. 259 // 260 // CallCode differs from Call in the sense that it executes the given address' 261 // code with the caller as context. 262 func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { 263 // Fail if we're trying to execute above the call depth limit 264 if evm.depth > int(params.CallCreateDepth) { 265 return nil, gas, ErrDepth 266 } 267 // Fail if we're trying to transfer more than the available balance 268 // Note although it's noop to transfer X ether to caller itself. But 269 // if caller doesn't have enough balance, it would be an error to allow 270 // over-charging itself. So the check here is necessary. 271 if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 272 return nil, gas, ErrInsufficientBalance 273 } 274 var snapshot = evm.StateDB.Snapshot() 275 276 // Invoke tracer hooks that signal entering/exiting a call frame 277 if evm.Config.Tracer != nil { 278 evm.Config.Tracer.CaptureEnter(CALLCODE, caller.Address(), addr, input, gas, value) 279 defer func(startGas uint64) { 280 evm.Config.Tracer.CaptureExit(ret, startGas-gas, err) 281 }(gas) 282 } 283 284 // It is allowed to call precompiles, even via delegatecall 285 if p, isPrecompile := evm.precompile(addr); isPrecompile { 286 ret, gas, err = RunPrecompiledContract(p, input, gas) 287 } else { 288 addrCopy := addr 289 // Initialise a new contract and set the code that is to be used by the EVM. 290 // The contract is a scoped environment for this execution context only. 291 contract := NewContract(caller, AccountRef(caller.Address()), value, gas) 292 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) 293 ret, err = evm.interpreter.Run(contract, input, false) 294 gas = contract.Gas 295 } 296 if err != nil { 297 evm.StateDB.RevertToSnapshot(snapshot) 298 if err != ErrExecutionReverted { 299 gas = 0 300 } 301 } 302 return ret, gas, err 303 } 304 305 // DelegateCall executes the contract associated with the addr with the given input 306 // as parameters. It reverses the state in case of an execution error. 307 // 308 // DelegateCall differs from CallCode in the sense that it executes the given address' 309 // code with the caller as context and the caller is set to the caller of the caller. 310 func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) { 311 // Fail if we're trying to execute above the call depth limit 312 if evm.depth > int(params.CallCreateDepth) { 313 return nil, gas, ErrDepth 314 } 315 var snapshot = evm.StateDB.Snapshot() 316 317 // Invoke tracer hooks that signal entering/exiting a call frame 318 if evm.Config.Tracer != nil { 319 // NOTE: caller must, at all times be a contract. It should never happen 320 // that caller is something other than a Contract. 321 parent := caller.(*Contract) 322 // DELEGATECALL inherits value from parent call 323 evm.Config.Tracer.CaptureEnter(DELEGATECALL, caller.Address(), addr, input, gas, parent.value) 324 defer func(startGas uint64) { 325 evm.Config.Tracer.CaptureExit(ret, startGas-gas, err) 326 }(gas) 327 } 328 329 // It is allowed to call precompiles, even via delegatecall 330 if p, isPrecompile := evm.precompile(addr); isPrecompile { 331 ret, gas, err = RunPrecompiledContract(p, input, gas) 332 } else { 333 addrCopy := addr 334 // Initialise a new contract and make initialise the delegate values 335 contract := NewContract(caller, AccountRef(caller.Address()), nil, gas).AsDelegate() 336 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) 337 ret, err = evm.interpreter.Run(contract, input, false) 338 gas = contract.Gas 339 } 340 if err != nil { 341 evm.StateDB.RevertToSnapshot(snapshot) 342 if err != ErrExecutionReverted { 343 gas = 0 344 } 345 } 346 return ret, gas, err 347 } 348 349 // StaticCall executes the contract associated with the addr with the given input 350 // as parameters while disallowing any modifications to the state during the call. 351 // Opcodes that attempt to perform such modifications will result in exceptions 352 // instead of performing the modifications. 353 func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) { 354 // Fail if we're trying to execute above the call depth limit 355 if evm.depth > int(params.CallCreateDepth) { 356 return nil, gas, ErrDepth 357 } 358 // We take a snapshot here. This is a bit counter-intuitive, and could probably be skipped. 359 // However, even a staticcall is considered a 'touch'. On mainnet, static calls were introduced 360 // after all empty accounts were deleted, so this is not required. However, if we omit this, 361 // then certain tests start failing; stRevertTest/RevertPrecompiledTouchExactOOG.json. 362 // We could change this, but for now it's left for legacy reasons 363 var snapshot = evm.StateDB.Snapshot() 364 365 // We do an AddBalance of zero here, just in order to trigger a touch. 366 // This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium, 367 // but is the correct thing to do and matters on other networks, in tests, and potential 368 // future scenarios 369 evm.StateDB.AddBalance(addr, big0) 370 371 // Invoke tracer hooks that signal entering/exiting a call frame 372 if evm.Config.Tracer != nil { 373 evm.Config.Tracer.CaptureEnter(STATICCALL, caller.Address(), addr, input, gas, nil) 374 defer func(startGas uint64) { 375 evm.Config.Tracer.CaptureExit(ret, startGas-gas, err) 376 }(gas) 377 } 378 379 if p, isPrecompile := evm.precompile(addr); isPrecompile { 380 ret, gas, err = RunPrecompiledContract(p, input, gas) 381 } else { 382 // At this point, we use a copy of address. If we don't, the go compiler will 383 // leak the 'contract' to the outer scope, and make allocation for 'contract' 384 // even if the actual execution ends on RunPrecompiled above. 385 addrCopy := addr 386 // Initialise a new contract and set the code that is to be used by the EVM. 387 // The contract is a scoped environment for this execution context only. 388 contract := NewContract(caller, AccountRef(addrCopy), new(big.Int), gas) 389 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) 390 // When an error was returned by the EVM or when setting the creation code 391 // above we revert to the snapshot and consume any gas remaining. Additionally 392 // when we're in Homestead this also counts for code storage gas errors. 393 ret, err = evm.interpreter.Run(contract, input, true) 394 gas = contract.Gas 395 } 396 if err != nil { 397 evm.StateDB.RevertToSnapshot(snapshot) 398 if err != ErrExecutionReverted { 399 gas = 0 400 } 401 } 402 return ret, gas, err 403 } 404 405 type codeAndHash struct { 406 code []byte 407 hash common.Hash 408 } 409 410 func (c *codeAndHash) Hash() common.Hash { 411 if c.hash == (common.Hash{}) { 412 c.hash = crypto.Keccak256Hash(c.code) 413 } 414 return c.hash 415 } 416 417 // create creates a new contract using code as deployment code. 418 func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address, typ OpCode) ([]byte, common.Address, uint64, error) { 419 // Depth check execution. Fail if we're trying to execute above the 420 // limit. 421 if evm.depth > int(params.CallCreateDepth) { 422 return nil, common.Address{}, gas, ErrDepth 423 } 424 if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 425 return nil, common.Address{}, gas, ErrInsufficientBalance 426 } 427 nonce := evm.StateDB.GetNonce(caller.Address()) 428 if nonce+1 < nonce { 429 return nil, common.Address{}, gas, ErrNonceUintOverflow 430 } 431 evm.StateDB.SetNonce(caller.Address(), nonce+1) 432 // We add this to the access list _before_ taking a snapshot. Even if the creation fails, 433 // the access-list change should not be rolled back 434 if evm.chainRules.IsBerlin { 435 evm.StateDB.AddAddressToAccessList(address) 436 } 437 // Ensure there's no existing contract already at the designated address 438 contractHash := evm.StateDB.GetCodeHash(address) 439 if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != types.EmptyCodeHash) { 440 return nil, common.Address{}, 0, ErrContractAddressCollision 441 } 442 // Create a new account on the state 443 snapshot := evm.StateDB.Snapshot() 444 evm.StateDB.CreateAccount(address) 445 if evm.chainRules.IsEIP158 { 446 evm.StateDB.SetNonce(address, 1) 447 } 448 evm.Context.Transfer(evm.StateDB, caller.Address(), address, value) 449 450 // Initialise a new contract and set the code that is to be used by the EVM. 451 // The contract is a scoped environment for this execution context only. 452 contract := NewContract(caller, AccountRef(address), value, gas) 453 contract.SetCodeOptionalHash(&address, codeAndHash) 454 455 if evm.Config.Tracer != nil { 456 if evm.depth == 0 { 457 evm.Config.Tracer.CaptureStart(evm, caller.Address(), address, true, codeAndHash.code, gas, value) 458 } else { 459 evm.Config.Tracer.CaptureEnter(typ, caller.Address(), address, codeAndHash.code, gas, value) 460 } 461 } 462 463 ret, err := evm.interpreter.Run(contract, nil, false) 464 465 // Check whether the max code size has been exceeded, assign err if the case. 466 if err == nil && evm.chainRules.IsEIP158 && len(ret) > params.MaxCodeSize { 467 err = ErrMaxCodeSizeExceeded 468 } 469 470 // Reject code starting with 0xEF if EIP-3541 is enabled. 471 if err == nil && len(ret) >= 1 && ret[0] == 0xEF && evm.chainRules.IsLondon { 472 err = ErrInvalidCode 473 } 474 475 // if the contract creation ran successfully and no errors were returned 476 // calculate the gas required to store the code. If the code could not 477 // be stored due to not enough gas set an error and let it be handled 478 // by the error checking condition below. 479 if err == nil { 480 createDataGas := uint64(len(ret)) * params.CreateDataGas 481 if contract.UseGas(createDataGas) { 482 evm.StateDB.SetCode(address, ret) 483 } else { 484 err = ErrCodeStoreOutOfGas 485 } 486 } 487 488 // When an error was returned by the EVM or when setting the creation code 489 // above we revert to the snapshot and consume any gas remaining. Additionally 490 // when we're in homestead this also counts for code storage gas errors. 491 if err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas) { 492 evm.StateDB.RevertToSnapshot(snapshot) 493 if err != ErrExecutionReverted { 494 contract.UseGas(contract.Gas) 495 } 496 } 497 498 if evm.Config.Tracer != nil { 499 if evm.depth == 0 { 500 evm.Config.Tracer.CaptureEnd(ret, gas-contract.Gas, err) 501 } else { 502 evm.Config.Tracer.CaptureExit(ret, gas-contract.Gas, err) 503 } 504 } 505 return ret, address, contract.Gas, err 506 } 507 508 // Create creates a new contract using code as deployment code. 509 func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { 510 contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address())) 511 return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr, CREATE) 512 } 513 514 // Create2 creates a new contract using code as deployment code. 515 // 516 // The different between Create2 with Create is Create2 uses keccak256(0xff ++ msg.sender ++ salt ++ keccak256(init_code))[12:] 517 // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at. 518 func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { 519 codeAndHash := &codeAndHash{code: code} 520 contractAddr = crypto.CreateAddress2(caller.Address(), salt.Bytes32(), codeAndHash.Hash().Bytes()) 521 return evm.create(caller, codeAndHash, gas, endowment, contractAddr, CREATE2) 522 } 523 524 // ChainConfig returns the environment's chain configuration 525 func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }