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