evm.go 22 KB

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