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