github.com/authcall/reference-optimistic-geth@v0.0.0-20220816224302-06313bfeb8d2/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/ethereum/go-ethereum/common" 25 "github.com/ethereum/go-ethereum/crypto" 26 "github.com/ethereum/go-ethereum/params" 27 "github.com/holiman/uint256" 28 ) 29 30 // emptyCodeHash is used by create to ensure deployment is disallowed to already 31 // deployed contract addresses (relevant after the account abstraction). 32 var emptyCodeHash = crypto.Keccak256Hash(nil) 33 34 type RollupMessage interface { 35 Nonce() uint64 36 RollupDataGas() uint64 37 } 38 39 type ( 40 // CanTransferFunc is the signature of a transfer guard function 41 CanTransferFunc func(StateDB, common.Address, *big.Int) bool 42 // TransferFunc is the signature of a transfer function 43 TransferFunc func(StateDB, common.Address, common.Address, *big.Int) 44 // GetHashFunc returns the n'th block hash in the blockchain 45 // and is used by the BLOCKHASH EVM op code. 46 GetHashFunc func(uint64) common.Hash 47 // L1CostFunc is used in the state transition to determine the cost of a rollup message. 48 // Returns nil if there is no cost. 49 L1CostFunc func(blockNum uint64, msg RollupMessage) *big.Int 50 ) 51 52 func (evm *EVM) precompile(addr common.Address) (PrecompiledContract, bool) { 53 var precompiles map[common.Address]PrecompiledContract 54 switch { 55 case evm.chainRules.IsBerlin: 56 precompiles = PrecompiledContractsBerlin 57 case evm.chainRules.IsIstanbul: 58 precompiles = PrecompiledContractsIstanbul 59 case evm.chainRules.IsByzantium: 60 precompiles = PrecompiledContractsByzantium 61 default: 62 precompiles = PrecompiledContractsHomestead 63 } 64 p, ok := precompiles[addr] 65 return p, ok 66 } 67 68 // BlockContext provides the EVM with auxiliary information. Once provided 69 // it shouldn't be modified. 70 type BlockContext struct { 71 // CanTransfer returns whether the account contains 72 // sufficient ether to transfer the value 73 CanTransfer CanTransferFunc 74 // Transfer transfers ether from one account to the other 75 Transfer TransferFunc 76 // GetHash returns the hash corresponding to n 77 GetHash GetHashFunc 78 // L1CostFunc returns the L1 cost of the rollup message, the function may be nil, or return nil 79 L1CostFunc L1CostFunc 80 81 // Block information 82 Coinbase common.Address // Provides information for COINBASE 83 GasLimit uint64 // Provides information for GASLIMIT 84 BlockNumber *big.Int // Provides information for NUMBER 85 Time *big.Int // Provides information for TIME 86 Difficulty *big.Int // Provides information for DIFFICULTY 87 BaseFee *big.Int // Provides information for BASEFEE 88 Random *common.Hash // Provides information for RANDOM 89 } 90 91 // TxContext provides the EVM with information about a transaction. 92 // All fields can change between transactions. 93 type TxContext struct { 94 // Message information 95 Origin common.Address // Provides information for ORIGIN 96 GasPrice *big.Int // Provides information for GASPRICE 97 } 98 99 // EVM is the Ethereum Virtual Machine base object and provides 100 // the necessary tools to run a contract on the given state with 101 // the provided context. It should be noted that any error 102 // generated through any of the calls should be considered a 103 // revert-state-and-consume-all-gas operation, no checks on 104 // specific errors should ever be performed. The interpreter makes 105 // sure that any errors generated are to be considered faulty code. 106 // 107 // The EVM should never be reused and is not thread safe. 108 type EVM struct { 109 // Context provides auxiliary blockchain related information 110 Context BlockContext 111 TxContext 112 // StateDB gives access to the underlying state 113 StateDB StateDB 114 // Depth is the current call stack 115 depth int 116 117 // chainConfig contains information about the current chain 118 chainConfig *params.ChainConfig 119 // chain rules contains the chain rules for the current epoch 120 chainRules params.Rules 121 // virtual machine configuration options used to initialise the 122 // evm. 123 Config Config 124 // global (to this context) ethereum virtual machine 125 // used throughout the execution of the tx. 126 interpreter *EVMInterpreter 127 // abort is used to abort the EVM calling operations 128 // NOTE: must be set atomically 129 abort int32 130 // callGasTemp holds the gas available for the current call. This is needed because the 131 // available gas is calculated in gasCall* according to the 63/64 rule and later 132 // applied in opCall*. 133 callGasTemp uint64 134 } 135 136 // NewEVM returns a new EVM. The returned EVM is not thread safe and should 137 // only ever be used *once*. 138 func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb StateDB, chainConfig *params.ChainConfig, config Config) *EVM { 139 evm := &EVM{ 140 Context: blockCtx, 141 TxContext: txCtx, 142 StateDB: statedb, 143 Config: config, 144 chainConfig: chainConfig, 145 chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil), 146 } 147 evm.interpreter = NewEVMInterpreter(evm, config) 148 return evm 149 } 150 151 // Reset resets the EVM with a new transaction context.Reset 152 // This is not threadsafe and should only be done very cautiously. 153 func (evm *EVM) Reset(txCtx TxContext, statedb StateDB) { 154 evm.TxContext = txCtx 155 evm.StateDB = statedb 156 } 157 158 // Cancel cancels any running EVM operation. This may be called concurrently and 159 // it's safe to be called multiple times. 160 func (evm *EVM) Cancel() { 161 atomic.StoreInt32(&evm.abort, 1) 162 } 163 164 // Cancelled returns true if Cancel has been called 165 func (evm *EVM) Cancelled() bool { 166 return atomic.LoadInt32(&evm.abort) == 1 167 } 168 169 // Interpreter returns the current interpreter 170 func (evm *EVM) Interpreter() *EVMInterpreter { 171 return evm.interpreter 172 } 173 174 // Call executes the contract associated with the addr with the given input as 175 // parameters. It also handles any necessary value transfer required and takes 176 // the necessary steps to create accounts and reverses the state in case of an 177 // execution error or failed value transfer. 178 func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { 179 // Fail if we're trying to execute above the call depth limit 180 if evm.depth > int(params.CallCreateDepth) { 181 return nil, gas, ErrDepth 182 } 183 // Fail if we're trying to transfer more than the available balance 184 if value.Sign() != 0 && !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 185 return nil, gas, ErrInsufficientBalance 186 } 187 snapshot := evm.StateDB.Snapshot() 188 p, isPrecompile := evm.precompile(addr) 189 190 if !evm.StateDB.Exist(addr) { 191 if !isPrecompile && evm.chainRules.IsEIP158 && value.Sign() == 0 { 192 // Calling a non existing account, don't do anything, but ping the tracer 193 if evm.Config.Debug { 194 if evm.depth == 0 { 195 evm.Config.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value) 196 evm.Config.Tracer.CaptureEnd(ret, 0, 0, nil) 197 } else { 198 evm.Config.Tracer.CaptureEnter(CALL, caller.Address(), addr, input, gas, value) 199 evm.Config.Tracer.CaptureExit(ret, 0, nil) 200 } 201 } 202 return nil, gas, nil 203 } 204 evm.StateDB.CreateAccount(addr) 205 } 206 evm.Context.Transfer(evm.StateDB, caller.Address(), addr, value) 207 208 // Capture the tracer start/end events in debug mode 209 if evm.Config.Debug { 210 if evm.depth == 0 { 211 evm.Config.Tracer.CaptureStart(evm, caller.Address(), addr, false, input, gas, value) 212 defer func(startGas uint64, startTime time.Time) { // Lazy evaluation of the parameters 213 evm.Config.Tracer.CaptureEnd(ret, startGas-gas, time.Since(startTime), err) 214 }(gas, time.Now()) 215 } else { 216 // Handle tracer events for entering and exiting a call frame 217 evm.Config.Tracer.CaptureEnter(CALL, caller.Address(), addr, input, gas, value) 218 defer func(startGas uint64) { 219 evm.Config.Tracer.CaptureExit(ret, startGas-gas, err) 220 }(gas) 221 } 222 } 223 224 if isPrecompile { 225 ret, gas, err = RunPrecompiledContract(p, input, gas) 226 } else { 227 // Initialise a new contract and set the code that is to be used by the EVM. 228 // The contract is a scoped environment for this execution context only. 229 code := evm.StateDB.GetCode(addr) 230 if len(code) == 0 { 231 ret, err = nil, nil // gas is unchanged 232 } else { 233 addrCopy := addr 234 // If the account has no code, we can abort here 235 // The depth-check is already done, and precompiles handled above 236 contract := NewContract(caller, AccountRef(addrCopy), value, gas) 237 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), code) 238 ret, err = evm.interpreter.Run(contract, input, false) 239 gas = contract.Gas 240 } 241 } 242 // When an error was returned by the EVM or when setting the creation code 243 // above we revert to the snapshot and consume any gas remaining. Additionally 244 // when we're in homestead this also counts for code storage gas errors. 245 if err != nil { 246 evm.StateDB.RevertToSnapshot(snapshot) 247 if err != ErrExecutionReverted { 248 gas = 0 249 } 250 // TODO: consider clearing up unused snapshots: 251 //} else { 252 // evm.StateDB.DiscardSnapshot(snapshot) 253 } 254 return ret, gas, err 255 } 256 257 // CallCode executes the contract associated with the addr with the given input 258 // as parameters. It also handles any necessary value transfer required and takes 259 // the necessary steps to create accounts and reverses the state in case of an 260 // execution error or failed value transfer. 261 // 262 // CallCode differs from Call in the sense that it executes the given address' 263 // code with the caller as context. 264 func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { 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.GetCodeHash(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 // Fail if we're trying to execute above the call depth limit 314 if evm.depth > int(params.CallCreateDepth) { 315 return nil, gas, ErrDepth 316 } 317 var snapshot = evm.StateDB.Snapshot() 318 319 // Invoke tracer hooks that signal entering/exiting a call frame 320 if evm.Config.Debug { 321 evm.Config.Tracer.CaptureEnter(DELEGATECALL, caller.Address(), addr, input, gas, nil) 322 defer func(startGas uint64) { 323 evm.Config.Tracer.CaptureExit(ret, startGas-gas, err) 324 }(gas) 325 } 326 327 // It is allowed to call precompiles, even via delegatecall 328 if p, isPrecompile := evm.precompile(addr); isPrecompile { 329 ret, gas, err = RunPrecompiledContract(p, input, gas) 330 } else { 331 addrCopy := addr 332 // Initialise a new contract and make initialise the delegate values 333 contract := NewContract(caller, AccountRef(caller.Address()), nil, gas).AsDelegate() 334 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) 335 ret, err = evm.interpreter.Run(contract, input, false) 336 gas = contract.Gas 337 } 338 if err != nil { 339 evm.StateDB.RevertToSnapshot(snapshot) 340 if err != ErrExecutionReverted { 341 gas = 0 342 } 343 } 344 return ret, gas, err 345 } 346 347 // StaticCall executes the contract associated with the addr with the given input 348 // as parameters while disallowing any modifications to the state during the call. 349 // Opcodes that attempt to perform such modifications will result in exceptions 350 // instead of performing the modifications. 351 func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) { 352 // Fail if we're trying to execute above the call depth limit 353 if evm.depth > int(params.CallCreateDepth) { 354 return nil, gas, ErrDepth 355 } 356 // We take a snapshot here. This is a bit counter-intuitive, and could probably be skipped. 357 // However, even a staticcall is considered a 'touch'. On mainnet, static calls were introduced 358 // after all empty accounts were deleted, so this is not required. However, if we omit this, 359 // then certain tests start failing; stRevertTest/RevertPrecompiledTouchExactOOG.json. 360 // We could change this, but for now it's left for legacy reasons 361 var snapshot = evm.StateDB.Snapshot() 362 363 // We do an AddBalance of zero here, just in order to trigger a touch. 364 // This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium, 365 // but is the correct thing to do and matters on other networks, in tests, and potential 366 // future scenarios 367 evm.StateDB.AddBalance(addr, big0) 368 369 // Invoke tracer hooks that signal entering/exiting a call frame 370 if evm.Config.Debug { 371 evm.Config.Tracer.CaptureEnter(STATICCALL, caller.Address(), addr, input, gas, nil) 372 defer func(startGas uint64) { 373 evm.Config.Tracer.CaptureExit(ret, startGas-gas, err) 374 }(gas) 375 } 376 377 if p, isPrecompile := evm.precompile(addr); isPrecompile { 378 ret, gas, err = RunPrecompiledContract(p, input, gas) 379 } else { 380 // At this point, we use a copy of address. If we don't, the go compiler will 381 // leak the 'contract' to the outer scope, and make allocation for 'contract' 382 // even if the actual execution ends on RunPrecompiled above. 383 addrCopy := addr 384 // Initialise a new contract and set the code that is to be used by the EVM. 385 // The contract is a scoped environment for this execution context only. 386 contract := NewContract(caller, AccountRef(addrCopy), new(big.Int), gas) 387 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) 388 // When an error was returned by the EVM or when setting the creation code 389 // above we revert to the snapshot and consume any gas remaining. Additionally 390 // when we're in Homestead this also counts for code storage gas errors. 391 ret, err = evm.interpreter.Run(contract, input, true) 392 gas = contract.Gas 393 } 394 if err != nil { 395 evm.StateDB.RevertToSnapshot(snapshot) 396 if err != ErrExecutionReverted { 397 gas = 0 398 } 399 } 400 return ret, gas, err 401 } 402 403 type codeAndHash struct { 404 code []byte 405 hash common.Hash 406 } 407 408 func (c *codeAndHash) Hash() common.Hash { 409 if c.hash == (common.Hash{}) { 410 c.hash = crypto.Keccak256Hash(c.code) 411 } 412 return c.hash 413 } 414 415 // create creates a new contract using code as deployment code. 416 func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address, typ OpCode) ([]byte, common.Address, uint64, error) { 417 // Depth check execution. Fail if we're trying to execute above the 418 // limit. 419 if evm.depth > int(params.CallCreateDepth) { 420 return nil, common.Address{}, gas, ErrDepth 421 } 422 if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 423 return nil, common.Address{}, gas, ErrInsufficientBalance 424 } 425 nonce := evm.StateDB.GetNonce(caller.Address()) 426 if nonce+1 < nonce { 427 return nil, common.Address{}, gas, ErrNonceUintOverflow 428 } 429 evm.StateDB.SetNonce(caller.Address(), nonce+1) 430 // We add this to the access list _before_ taking a snapshot. Even if the creation fails, 431 // the access-list change should not be rolled back 432 if evm.chainRules.IsBerlin { 433 evm.StateDB.AddAddressToAccessList(address) 434 } 435 // Ensure there's no existing contract already at the designated address 436 contractHash := evm.StateDB.GetCodeHash(address) 437 if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) { 438 return nil, common.Address{}, 0, ErrContractAddressCollision 439 } 440 // Create a new account on the state 441 snapshot := evm.StateDB.Snapshot() 442 evm.StateDB.CreateAccount(address) 443 if evm.chainRules.IsEIP158 { 444 evm.StateDB.SetNonce(address, 1) 445 } 446 evm.Context.Transfer(evm.StateDB, caller.Address(), address, value) 447 448 // Initialise a new contract and set the code that is to be used by the EVM. 449 // The contract is a scoped environment for this execution context only. 450 contract := NewContract(caller, AccountRef(address), value, gas) 451 contract.SetCodeOptionalHash(&address, codeAndHash) 452 453 if evm.Config.Debug { 454 if evm.depth == 0 { 455 evm.Config.Tracer.CaptureStart(evm, caller.Address(), address, true, codeAndHash.code, gas, value) 456 } else { 457 evm.Config.Tracer.CaptureEnter(typ, caller.Address(), address, codeAndHash.code, gas, value) 458 } 459 } 460 461 start := time.Now() 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.Debug { 499 if evm.depth == 0 { 500 evm.Config.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), 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 }