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