evm.go 22 KB

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