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