evm.go 22 KB

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