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