evm.go 20 KB

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