github.com/ethereum/go-ethereum@v1.14.4-0.20240516095835-473ee8fc07a3/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 "errors" 21 "math/big" 22 "sync/atomic" 23 24 "github.com/ethereum/go-ethereum/common" 25 "github.com/ethereum/go-ethereum/core/state" 26 "github.com/ethereum/go-ethereum/core/tracing" 27 "github.com/ethereum/go-ethereum/core/types" 28 "github.com/ethereum/go-ethereum/crypto" 29 "github.com/ethereum/go-ethereum/params" 30 "github.com/holiman/uint256" 31 ) 32 33 type ( 34 // CanTransferFunc is the signature of a transfer guard function 35 CanTransferFunc func(StateDB, common.Address, *uint256.Int) bool 36 // TransferFunc is the signature of a transfer function 37 TransferFunc func(StateDB, common.Address, common.Address, *uint256.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.IsVerkle: 47 precompiles = PrecompiledContractsVerkle 48 case evm.chainRules.IsPrague: 49 precompiles = PrecompiledContractsPrague 50 case evm.chainRules.IsCancun: 51 precompiles = PrecompiledContractsCancun 52 case evm.chainRules.IsBerlin: 53 precompiles = PrecompiledContractsBerlin 54 case evm.chainRules.IsIstanbul: 55 precompiles = PrecompiledContractsIstanbul 56 case evm.chainRules.IsByzantium: 57 precompiles = PrecompiledContractsByzantium 58 default: 59 precompiles = PrecompiledContractsHomestead 60 } 61 p, ok := precompiles[addr] 62 return p, ok 63 } 64 65 // BlockContext provides the EVM with auxiliary information. Once provided 66 // it shouldn't be modified. 67 type BlockContext struct { 68 // CanTransfer returns whether the account contains 69 // sufficient ether to transfer the value 70 CanTransfer CanTransferFunc 71 // Transfer transfers ether from one account to the other 72 Transfer TransferFunc 73 // GetHash returns the hash corresponding to n 74 GetHash GetHashFunc 75 76 // Block information 77 Coinbase common.Address // Provides information for COINBASE 78 GasLimit uint64 // Provides information for GASLIMIT 79 BlockNumber *big.Int // Provides information for NUMBER 80 Time uint64 // Provides information for TIME 81 Difficulty *big.Int // Provides information for DIFFICULTY 82 BaseFee *big.Int // Provides information for BASEFEE (0 if vm runs with NoBaseFee flag and 0 gas price) 83 BlobBaseFee *big.Int // Provides information for BLOBBASEFEE (0 if vm runs with NoBaseFee flag and 0 blob gas price) 84 Random *common.Hash // Provides information for PREVRANDAO 85 } 86 87 // TxContext provides the EVM with information about a transaction. 88 // All fields can change between transactions. 89 type TxContext struct { 90 // Message information 91 Origin common.Address // Provides information for ORIGIN 92 GasPrice *big.Int // Provides information for GASPRICE (and is used to zero the basefee if NoBaseFee is set) 93 BlobHashes []common.Hash // Provides information for BLOBHASH 94 BlobFeeCap *big.Int // Is used to zero the blobbasefee if NoBaseFee is set 95 AccessEvents *state.AccessEvents // Capture all state accesses for this tx 96 } 97 98 // EVM is the Ethereum Virtual Machine base object and provides 99 // the necessary tools to run a contract on the given state with 100 // the provided context. It should be noted that any error 101 // generated through any of the calls should be considered a 102 // revert-state-and-consume-all-gas operation, no checks on 103 // specific errors should ever be performed. The interpreter makes 104 // sure that any errors generated are to be considered faulty code. 105 // 106 // The EVM should never be reused and is not thread safe. 107 type EVM struct { 108 // Context provides auxiliary blockchain related information 109 Context BlockContext 110 TxContext 111 // StateDB gives access to the underlying state 112 StateDB StateDB 113 // Depth is the current call stack 114 depth int 115 116 // chainConfig contains information about the current chain 117 chainConfig *params.ChainConfig 118 // chain rules contains the chain rules for the current epoch 119 chainRules params.Rules 120 // virtual machine configuration options used to initialise the 121 // evm. 122 Config Config 123 // global (to this context) ethereum virtual machine 124 // used throughout the execution of the tx. 125 interpreter *EVMInterpreter 126 // abort is used to abort the EVM calling operations 127 abort atomic.Bool 128 // callGasTemp holds the gas available for the current call. This is needed because the 129 // available gas is calculated in gasCall* according to the 63/64 rule and later 130 // applied in opCall*. 131 callGasTemp uint64 132 } 133 134 // NewEVM returns a new EVM. The returned EVM is not thread safe and should 135 // only ever be used *once*. 136 func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb StateDB, chainConfig *params.ChainConfig, config Config) *EVM { 137 // If basefee tracking is disabled (eth_call, eth_estimateGas, etc), and no 138 // gas prices were specified, lower the basefee to 0 to avoid breaking EVM 139 // invariants (basefee < feecap) 140 if config.NoBaseFee { 141 if txCtx.GasPrice.BitLen() == 0 { 142 blockCtx.BaseFee = new(big.Int) 143 } 144 if txCtx.BlobFeeCap != nil && txCtx.BlobFeeCap.BitLen() == 0 { 145 blockCtx.BlobBaseFee = new(big.Int) 146 } 147 } 148 evm := &EVM{ 149 Context: blockCtx, 150 TxContext: txCtx, 151 StateDB: statedb, 152 Config: config, 153 chainConfig: chainConfig, 154 chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time), 155 } 156 evm.interpreter = NewEVMInterpreter(evm) 157 return evm 158 } 159 160 // Reset resets the EVM with a new transaction context.Reset 161 // This is not threadsafe and should only be done very cautiously. 162 func (evm *EVM) Reset(txCtx TxContext, statedb StateDB) { 163 if evm.chainRules.IsEIP4762 { 164 txCtx.AccessEvents = state.NewAccessEvents(statedb.PointCache()) 165 } 166 evm.TxContext = txCtx 167 evm.StateDB = statedb 168 } 169 170 // Cancel cancels any running EVM operation. This may be called concurrently and 171 // it's safe to be called multiple times. 172 func (evm *EVM) Cancel() { 173 evm.abort.Store(true) 174 } 175 176 // Cancelled returns true if Cancel has been called 177 func (evm *EVM) Cancelled() bool { 178 return evm.abort.Load() 179 } 180 181 // Interpreter returns the current interpreter 182 func (evm *EVM) Interpreter() *EVMInterpreter { 183 return evm.interpreter 184 } 185 186 // Call executes the contract associated with the addr with the given input as 187 // parameters. It also handles any necessary value transfer required and takes 188 // the necessary steps to create accounts and reverses the state in case of an 189 // execution error or failed value transfer. 190 func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) { 191 // Capture the tracer start/end events in debug mode 192 if evm.Config.Tracer != nil { 193 evm.captureBegin(evm.depth, CALL, caller.Address(), addr, input, gas, value.ToBig()) 194 defer func(startGas uint64) { 195 evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err) 196 }(gas) 197 } 198 // Fail if we're trying to execute above the call depth limit 199 if evm.depth > int(params.CallCreateDepth) { 200 return nil, gas, ErrDepth 201 } 202 // Fail if we're trying to transfer more than the available balance 203 if !value.IsZero() && !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 204 return nil, gas, ErrInsufficientBalance 205 } 206 snapshot := evm.StateDB.Snapshot() 207 p, isPrecompile := evm.precompile(addr) 208 209 if !evm.StateDB.Exist(addr) { 210 if !isPrecompile && evm.chainRules.IsEIP4762 { 211 // add proof of absence to witness 212 wgas := evm.AccessEvents.AddAccount(addr, false) 213 if gas < wgas { 214 evm.StateDB.RevertToSnapshot(snapshot) 215 return nil, 0, ErrOutOfGas 216 } 217 gas -= wgas 218 } 219 220 if !isPrecompile && evm.chainRules.IsEIP158 && value.IsZero() { 221 // Calling a non-existing account, don't do anything. 222 return nil, gas, nil 223 } 224 evm.StateDB.CreateAccount(addr) 225 } 226 evm.Context.Transfer(evm.StateDB, caller.Address(), addr, value) 227 228 if isPrecompile { 229 ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer) 230 } else { 231 // Initialise a new contract and set the code that is to be used by the EVM. 232 // The contract is a scoped environment for this execution context only. 233 code := evm.StateDB.GetCode(addr) 234 if len(code) == 0 { 235 ret, err = nil, nil // gas is unchanged 236 } else { 237 addrCopy := addr 238 // If the account has no code, we can abort here 239 // The depth-check is already done, and precompiles handled above 240 contract := NewContract(caller, AccountRef(addrCopy), value, gas) 241 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), code) 242 ret, err = evm.interpreter.Run(contract, input, false) 243 gas = contract.Gas 244 } 245 } 246 // When an error was returned by the EVM or when setting the creation code 247 // above we revert to the snapshot and consume any gas remaining. Additionally, 248 // when we're in homestead this also counts for code storage gas errors. 249 if err != nil { 250 evm.StateDB.RevertToSnapshot(snapshot) 251 if err != ErrExecutionReverted { 252 if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil { 253 evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution) 254 } 255 256 gas = 0 257 } 258 // TODO: consider clearing up unused snapshots: 259 //} else { 260 // evm.StateDB.DiscardSnapshot(snapshot) 261 } 262 return ret, gas, err 263 } 264 265 // CallCode executes the contract associated with the addr with the given input 266 // as parameters. It also handles any necessary value transfer required and takes 267 // the necessary steps to create accounts and reverses the state in case of an 268 // execution error or failed value transfer. 269 // 270 // CallCode differs from Call in the sense that it executes the given address' 271 // code with the caller as context. 272 func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *uint256.Int) (ret []byte, leftOverGas uint64, err error) { 273 // Invoke tracer hooks that signal entering/exiting a call frame 274 if evm.Config.Tracer != nil { 275 evm.captureBegin(evm.depth, CALLCODE, caller.Address(), addr, input, gas, value.ToBig()) 276 defer func(startGas uint64) { 277 evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err) 278 }(gas) 279 } 280 // Fail if we're trying to execute above the call depth limit 281 if evm.depth > int(params.CallCreateDepth) { 282 return nil, gas, ErrDepth 283 } 284 // Fail if we're trying to transfer more than the available balance 285 // Note although it's noop to transfer X ether to caller itself. But 286 // if caller doesn't have enough balance, it would be an error to allow 287 // over-charging itself. So the check here is necessary. 288 if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 289 return nil, gas, ErrInsufficientBalance 290 } 291 var snapshot = evm.StateDB.Snapshot() 292 293 // It is allowed to call precompiles, even via delegatecall 294 if p, isPrecompile := evm.precompile(addr); isPrecompile { 295 ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer) 296 } else { 297 addrCopy := addr 298 // Initialise a new contract and set the code that is to be used by the EVM. 299 // The contract is a scoped environment for this execution context only. 300 contract := NewContract(caller, AccountRef(caller.Address()), value, gas) 301 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) 302 ret, err = evm.interpreter.Run(contract, input, false) 303 gas = contract.Gas 304 } 305 if err != nil { 306 evm.StateDB.RevertToSnapshot(snapshot) 307 if err != ErrExecutionReverted { 308 if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil { 309 evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution) 310 } 311 312 gas = 0 313 } 314 } 315 return ret, gas, err 316 } 317 318 // DelegateCall executes the contract associated with the addr with the given input 319 // as parameters. It reverses the state in case of an execution error. 320 // 321 // DelegateCall differs from CallCode in the sense that it executes the given address' 322 // code with the caller as context and the caller is set to the caller of the caller. 323 func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) { 324 // Invoke tracer hooks that signal entering/exiting a call frame 325 if evm.Config.Tracer != nil { 326 // NOTE: caller must, at all times be a contract. It should never happen 327 // that caller is something other than a Contract. 328 parent := caller.(*Contract) 329 // DELEGATECALL inherits value from parent call 330 evm.captureBegin(evm.depth, DELEGATECALL, caller.Address(), addr, input, gas, parent.value.ToBig()) 331 defer func(startGas uint64) { 332 evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err) 333 }(gas) 334 } 335 // Fail if we're trying to execute above the call depth limit 336 if evm.depth > int(params.CallCreateDepth) { 337 return nil, gas, ErrDepth 338 } 339 var snapshot = evm.StateDB.Snapshot() 340 341 // It is allowed to call precompiles, even via delegatecall 342 if p, isPrecompile := evm.precompile(addr); isPrecompile { 343 ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer) 344 } else { 345 addrCopy := addr 346 // Initialise a new contract and make initialise the delegate values 347 contract := NewContract(caller, AccountRef(caller.Address()), nil, gas).AsDelegate() 348 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) 349 ret, err = evm.interpreter.Run(contract, input, false) 350 gas = contract.Gas 351 } 352 if err != nil { 353 evm.StateDB.RevertToSnapshot(snapshot) 354 if err != ErrExecutionReverted { 355 if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil { 356 evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution) 357 } 358 gas = 0 359 } 360 } 361 return ret, gas, err 362 } 363 364 // StaticCall executes the contract associated with the addr with the given input 365 // as parameters while disallowing any modifications to the state during the call. 366 // Opcodes that attempt to perform such modifications will result in exceptions 367 // instead of performing the modifications. 368 func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) { 369 // Invoke tracer hooks that signal entering/exiting a call frame 370 if evm.Config.Tracer != nil { 371 evm.captureBegin(evm.depth, STATICCALL, caller.Address(), addr, input, gas, nil) 372 defer func(startGas uint64) { 373 evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err) 374 }(gas) 375 } 376 // Fail if we're trying to execute above the call depth limit 377 if evm.depth > int(params.CallCreateDepth) { 378 return nil, gas, ErrDepth 379 } 380 // We take a snapshot here. This is a bit counter-intuitive, and could probably be skipped. 381 // However, even a staticcall is considered a 'touch'. On mainnet, static calls were introduced 382 // after all empty accounts were deleted, so this is not required. However, if we omit this, 383 // then certain tests start failing; stRevertTest/RevertPrecompiledTouchExactOOG.json. 384 // We could change this, but for now it's left for legacy reasons 385 var snapshot = evm.StateDB.Snapshot() 386 387 // We do an AddBalance of zero here, just in order to trigger a touch. 388 // This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium, 389 // but is the correct thing to do and matters on other networks, in tests, and potential 390 // future scenarios 391 evm.StateDB.AddBalance(addr, new(uint256.Int), tracing.BalanceChangeTouchAccount) 392 393 if p, isPrecompile := evm.precompile(addr); isPrecompile { 394 ret, gas, err = RunPrecompiledContract(p, input, gas, evm.Config.Tracer) 395 } else { 396 // At this point, we use a copy of address. If we don't, the go compiler will 397 // leak the 'contract' to the outer scope, and make allocation for 'contract' 398 // even if the actual execution ends on RunPrecompiled above. 399 addrCopy := addr 400 // Initialise a new contract and set the code that is to be used by the EVM. 401 // The contract is a scoped environment for this execution context only. 402 contract := NewContract(caller, AccountRef(addrCopy), new(uint256.Int), gas) 403 contract.SetCallCode(&addrCopy, evm.StateDB.GetCodeHash(addrCopy), evm.StateDB.GetCode(addrCopy)) 404 // When an error was returned by the EVM or when setting the creation code 405 // above we revert to the snapshot and consume any gas remaining. Additionally 406 // when we're in Homestead this also counts for code storage gas errors. 407 ret, err = evm.interpreter.Run(contract, input, true) 408 gas = contract.Gas 409 } 410 if err != nil { 411 evm.StateDB.RevertToSnapshot(snapshot) 412 if err != ErrExecutionReverted { 413 if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil { 414 evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution) 415 } 416 417 gas = 0 418 } 419 } 420 return ret, gas, err 421 } 422 423 type codeAndHash struct { 424 code []byte 425 hash common.Hash 426 } 427 428 func (c *codeAndHash) Hash() common.Hash { 429 if c.hash == (common.Hash{}) { 430 c.hash = crypto.Keccak256Hash(c.code) 431 } 432 return c.hash 433 } 434 435 // create creates a new contract using code as deployment code. 436 func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *uint256.Int, address common.Address, typ OpCode) (ret []byte, createAddress common.Address, leftOverGas uint64, err error) { 437 if evm.Config.Tracer != nil { 438 evm.captureBegin(evm.depth, typ, caller.Address(), address, codeAndHash.code, gas, value.ToBig()) 439 defer func(startGas uint64) { 440 evm.captureEnd(evm.depth, startGas, leftOverGas, ret, err) 441 }(gas) 442 } 443 // Depth check execution. Fail if we're trying to execute above the 444 // limit. 445 if evm.depth > int(params.CallCreateDepth) { 446 return nil, common.Address{}, gas, ErrDepth 447 } 448 if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { 449 return nil, common.Address{}, gas, ErrInsufficientBalance 450 } 451 nonce := evm.StateDB.GetNonce(caller.Address()) 452 if nonce+1 < nonce { 453 return nil, common.Address{}, gas, ErrNonceUintOverflow 454 } 455 evm.StateDB.SetNonce(caller.Address(), nonce+1) 456 457 // We add this to the access list _before_ taking a snapshot. Even if the 458 // creation fails, the access-list change should not be rolled back. 459 if evm.chainRules.IsEIP2929 { 460 evm.StateDB.AddAddressToAccessList(address) 461 } 462 // Ensure there's no existing contract already at the designated address. 463 // Account is regarded as existent if any of these three conditions is met: 464 // - the nonce is non-zero 465 // - the code is non-empty 466 // - the storage is non-empty 467 contractHash := evm.StateDB.GetCodeHash(address) 468 storageRoot := evm.StateDB.GetStorageRoot(address) 469 if evm.StateDB.GetNonce(address) != 0 || 470 (contractHash != (common.Hash{}) && contractHash != types.EmptyCodeHash) || // non-empty code 471 (storageRoot != (common.Hash{}) && storageRoot != types.EmptyRootHash) { // non-empty storage 472 if evm.Config.Tracer != nil && evm.Config.Tracer.OnGasChange != nil { 473 evm.Config.Tracer.OnGasChange(gas, 0, tracing.GasChangeCallFailedExecution) 474 } 475 return nil, common.Address{}, 0, ErrContractAddressCollision 476 } 477 // Create a new account on the state only if the object was not present. 478 // It might be possible the contract code is deployed to a pre-existent 479 // account with non-zero balance. 480 snapshot := evm.StateDB.Snapshot() 481 if !evm.StateDB.Exist(address) { 482 evm.StateDB.CreateAccount(address) 483 } 484 // CreateContract means that regardless of whether the account previously existed 485 // in the state trie or not, it _now_ becomes created as a _contract_ account. 486 // This is performed _prior_ to executing the initcode, since the initcode 487 // acts inside that account. 488 evm.StateDB.CreateContract(address) 489 490 if evm.chainRules.IsEIP158 { 491 evm.StateDB.SetNonce(address, 1) 492 } 493 evm.Context.Transfer(evm.StateDB, caller.Address(), address, value) 494 495 // Initialise a new contract and set the code that is to be used by the EVM. 496 // The contract is a scoped environment for this execution context only. 497 contract := NewContract(caller, AccountRef(address), value, gas) 498 contract.SetCodeOptionalHash(&address, codeAndHash) 499 contract.IsDeployment = true 500 501 // Charge the contract creation init gas in verkle mode 502 if evm.chainRules.IsEIP4762 { 503 if !contract.UseGas(evm.AccessEvents.ContractCreateInitGas(address, value.Sign() != 0), evm.Config.Tracer, tracing.GasChangeWitnessContractInit) { 504 err = ErrOutOfGas 505 } 506 } 507 508 if err == nil { 509 ret, err = evm.interpreter.Run(contract, nil, false) 510 } 511 512 // Check whether the max code size has been exceeded, assign err if the case. 513 if err == nil && evm.chainRules.IsEIP158 && len(ret) > params.MaxCodeSize { 514 err = ErrMaxCodeSizeExceeded 515 } 516 517 // Reject code starting with 0xEF if EIP-3541 is enabled. 518 if err == nil && len(ret) >= 1 && ret[0] == 0xEF && evm.chainRules.IsLondon { 519 err = ErrInvalidCode 520 } 521 522 // if the contract creation ran successfully and no errors were returned 523 // calculate the gas required to store the code. If the code could not 524 // be stored due to not enough gas set an error and let it be handled 525 // by the error checking condition below. 526 if err == nil { 527 if !evm.chainRules.IsEIP4762 { 528 createDataGas := uint64(len(ret)) * params.CreateDataGas 529 if !contract.UseGas(createDataGas, evm.Config.Tracer, tracing.GasChangeCallCodeStorage) { 530 err = ErrCodeStoreOutOfGas 531 } 532 } else { 533 // Contract creation completed, touch the missing fields in the contract 534 if !contract.UseGas(evm.AccessEvents.AddAccount(address, true), evm.Config.Tracer, tracing.GasChangeWitnessContractCreation) { 535 err = ErrCodeStoreOutOfGas 536 } 537 538 if err == nil && len(ret) > 0 && !contract.UseGas(evm.AccessEvents.CodeChunksRangeGas(address, 0, uint64(len(ret)), uint64(len(ret)), true), evm.Config.Tracer, tracing.GasChangeWitnessCodeChunk) { 539 err = ErrCodeStoreOutOfGas 540 } 541 } 542 543 if err == nil { 544 evm.StateDB.SetCode(address, ret) 545 } 546 } 547 548 // When an error was returned by the EVM or when setting the creation code 549 // above we revert to the snapshot and consume any gas remaining. Additionally, 550 // when we're in homestead this also counts for code storage gas errors. 551 if err != nil && (evm.chainRules.IsHomestead || err != ErrCodeStoreOutOfGas) { 552 evm.StateDB.RevertToSnapshot(snapshot) 553 if err != ErrExecutionReverted { 554 contract.UseGas(contract.Gas, evm.Config.Tracer, tracing.GasChangeCallFailedExecution) 555 } 556 } 557 558 return ret, address, contract.Gas, err 559 } 560 561 // Create creates a new contract using code as deployment code. 562 func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { 563 contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address())) 564 return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr, CREATE) 565 } 566 567 // Create2 creates a new contract using code as deployment code. 568 // 569 // The different between Create2 with Create is Create2 uses keccak256(0xff ++ msg.sender ++ salt ++ keccak256(init_code))[12:] 570 // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at. 571 func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *uint256.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) { 572 codeAndHash := &codeAndHash{code: code} 573 contractAddr = crypto.CreateAddress2(caller.Address(), salt.Bytes32(), codeAndHash.Hash().Bytes()) 574 return evm.create(caller, codeAndHash, gas, endowment, contractAddr, CREATE2) 575 } 576 577 // ChainConfig returns the environment's chain configuration 578 func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig } 579 580 func (evm *EVM) captureBegin(depth int, typ OpCode, from common.Address, to common.Address, input []byte, startGas uint64, value *big.Int) { 581 tracer := evm.Config.Tracer 582 if tracer.OnEnter != nil { 583 tracer.OnEnter(depth, byte(typ), from, to, input, startGas, value) 584 } 585 if tracer.OnGasChange != nil { 586 tracer.OnGasChange(0, startGas, tracing.GasChangeCallInitialBalance) 587 } 588 } 589 590 func (evm *EVM) captureEnd(depth int, startGas uint64, leftOverGas uint64, ret []byte, err error) { 591 tracer := evm.Config.Tracer 592 if leftOverGas != 0 && tracer.OnGasChange != nil { 593 tracer.OnGasChange(leftOverGas, 0, tracing.GasChangeCallLeftOverReturned) 594 } 595 var reverted bool 596 if err != nil { 597 reverted = true 598 } 599 if !evm.chainRules.IsHomestead && errors.Is(err, ErrCodeStoreOutOfGas) { 600 reverted = false 601 } 602 if tracer.OnExit != nil { 603 tracer.OnExit(depth, ret, startGas-leftOverGas, VMErrorFromErr(err), reverted) 604 } 605 } 606 607 // GetVMContext provides context about the block being executed as well as state 608 // to the tracers. 609 func (evm *EVM) GetVMContext() *tracing.VMContext { 610 return &tracing.VMContext{ 611 Coinbase: evm.Context.Coinbase, 612 BlockNumber: evm.Context.BlockNumber, 613 Time: evm.Context.Time, 614 Random: evm.Context.Random, 615 GasPrice: evm.TxContext.GasPrice, 616 ChainConfig: evm.ChainConfig(), 617 StateDB: evm.StateDB, 618 } 619 }