evm.go 18 KB

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