evm.go 18 KB

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