evm.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. // Interpreter returns the current interpreter
  156. func (evm *EVM) Interpreter() Interpreter {
  157. return evm.interpreter
  158. }
  159. // Call executes the contract associated with the addr with the given input as
  160. // parameters. It also handles any necessary value transfer required and takes
  161. // the necessary steps to create accounts and reverses the state in case of an
  162. // execution error or failed value transfer.
  163. func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
  164. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  165. return nil, gas, nil
  166. }
  167. // Fail if we're trying to execute above the call depth limit
  168. if evm.depth > int(params.CallCreateDepth) {
  169. return nil, gas, ErrDepth
  170. }
  171. // Fail if we're trying to transfer more than the available balance
  172. if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
  173. return nil, gas, ErrInsufficientBalance
  174. }
  175. var (
  176. to = AccountRef(addr)
  177. snapshot = evm.StateDB.Snapshot()
  178. )
  179. if !evm.StateDB.Exist(addr) {
  180. precompiles := PrecompiledContractsHomestead
  181. if evm.ChainConfig().IsByzantium(evm.BlockNumber) {
  182. precompiles = PrecompiledContractsByzantium
  183. }
  184. if precompiles[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 {
  185. // Calling a non existing account, don't do anything, but ping the tracer
  186. if evm.vmConfig.Debug && evm.depth == 0 {
  187. evm.vmConfig.Tracer.CaptureStart(caller.Address(), addr, false, input, gas, value)
  188. evm.vmConfig.Tracer.CaptureEnd(ret, 0, 0, nil)
  189. }
  190. return nil, gas, nil
  191. }
  192. evm.StateDB.CreateAccount(addr)
  193. }
  194. evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
  195. // Initialise a new contract and set the code that is to be used by the EVM.
  196. // The contract is a scoped environment for this execution context only.
  197. contract := NewContract(caller, to, value, gas)
  198. contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
  199. // Even if the account has no code, we need to continue because it might be a precompile
  200. start := time.Now()
  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() { // Lazy evaluation of the parameters
  205. evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
  206. }()
  207. }
  208. ret, err = run(evm, contract, input, false)
  209. // When an error was returned by the EVM or when setting the creation code
  210. // above we revert to the snapshot and consume any gas remaining. Additionally
  211. // when we're in homestead this also counts for code storage gas errors.
  212. if err != nil {
  213. evm.StateDB.RevertToSnapshot(snapshot)
  214. if err != errExecutionReverted {
  215. contract.UseGas(contract.Gas)
  216. }
  217. }
  218. return ret, contract.Gas, err
  219. }
  220. // CallCode executes the contract associated with the addr with the given input
  221. // as parameters. It also handles any necessary value transfer required and takes
  222. // the necessary steps to create accounts and reverses the state in case of an
  223. // execution error or failed value transfer.
  224. //
  225. // CallCode differs from Call in the sense that it executes the given address'
  226. // code with the caller as context.
  227. func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
  228. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  229. return nil, gas, nil
  230. }
  231. // Fail if we're trying to execute above the call depth limit
  232. if evm.depth > int(params.CallCreateDepth) {
  233. return nil, gas, ErrDepth
  234. }
  235. // Fail if we're trying to transfer more than the available balance
  236. if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
  237. return nil, gas, ErrInsufficientBalance
  238. }
  239. var (
  240. snapshot = evm.StateDB.Snapshot()
  241. to = AccountRef(caller.Address())
  242. )
  243. // Initialise a new contract and set the code that is to be used by the EVM.
  244. // The contract is a scoped environment for this execution context only.
  245. contract := NewContract(caller, to, value, gas)
  246. contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
  247. ret, err = run(evm, contract, input, false)
  248. if err != nil {
  249. evm.StateDB.RevertToSnapshot(snapshot)
  250. if err != errExecutionReverted {
  251. contract.UseGas(contract.Gas)
  252. }
  253. }
  254. return ret, contract.Gas, err
  255. }
  256. // DelegateCall executes the contract associated with the addr with the given input
  257. // as parameters. It reverses the state in case of an execution error.
  258. //
  259. // DelegateCall differs from CallCode in the sense that it executes the given address'
  260. // code with the caller as context and the caller is set to the caller of the caller.
  261. func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
  262. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  263. return nil, gas, nil
  264. }
  265. // Fail if we're trying to execute above the call depth limit
  266. if evm.depth > int(params.CallCreateDepth) {
  267. return nil, gas, ErrDepth
  268. }
  269. var (
  270. snapshot = evm.StateDB.Snapshot()
  271. to = AccountRef(caller.Address())
  272. )
  273. // Initialise a new contract and make initialise the delegate values
  274. contract := NewContract(caller, to, nil, gas).AsDelegate()
  275. contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
  276. ret, err = run(evm, contract, input, false)
  277. if err != nil {
  278. evm.StateDB.RevertToSnapshot(snapshot)
  279. if err != errExecutionReverted {
  280. contract.UseGas(contract.Gas)
  281. }
  282. }
  283. return ret, contract.Gas, err
  284. }
  285. // StaticCall executes the contract associated with the addr with the given input
  286. // as parameters while disallowing any modifications to the state during the call.
  287. // Opcodes that attempt to perform such modifications will result in exceptions
  288. // instead of performing the modifications.
  289. func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
  290. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  291. return nil, gas, nil
  292. }
  293. // Fail if we're trying to execute above the call depth limit
  294. if evm.depth > int(params.CallCreateDepth) {
  295. return nil, gas, ErrDepth
  296. }
  297. var (
  298. to = AccountRef(addr)
  299. snapshot = evm.StateDB.Snapshot()
  300. )
  301. // Initialise a new contract and set the code that is to be used by the EVM.
  302. // The contract is a scoped environment for this execution context only.
  303. contract := NewContract(caller, to, new(big.Int), gas)
  304. contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
  305. // We do an AddBalance of zero here, just in order to trigger a touch.
  306. // This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium,
  307. // but is the correct thing to do and matters on other networks, in tests, and potential
  308. // future scenarios
  309. evm.StateDB.AddBalance(addr, bigZero)
  310. // When an error was returned by the EVM or when setting the creation code
  311. // above we revert to the snapshot and consume any gas remaining. Additionally
  312. // when we're in Homestead this also counts for code storage gas errors.
  313. ret, err = run(evm, contract, input, true)
  314. if err != nil {
  315. evm.StateDB.RevertToSnapshot(snapshot)
  316. if err != errExecutionReverted {
  317. contract.UseGas(contract.Gas)
  318. }
  319. }
  320. return ret, contract.Gas, err
  321. }
  322. type codeAndHash struct {
  323. code []byte
  324. hash common.Hash
  325. }
  326. func (c *codeAndHash) Hash() common.Hash {
  327. if c.hash == (common.Hash{}) {
  328. c.hash = crypto.Keccak256Hash(c.code)
  329. }
  330. return c.hash
  331. }
  332. // create creates a new contract using code as deployment code.
  333. func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
  334. // Depth check execution. Fail if we're trying to execute above the
  335. // limit.
  336. if evm.depth > int(params.CallCreateDepth) {
  337. return nil, common.Address{}, gas, ErrDepth
  338. }
  339. if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
  340. return nil, common.Address{}, gas, ErrInsufficientBalance
  341. }
  342. nonce := evm.StateDB.GetNonce(caller.Address())
  343. evm.StateDB.SetNonce(caller.Address(), nonce+1)
  344. // Ensure there's no existing contract already at the designated address
  345. contractHash := evm.StateDB.GetCodeHash(address)
  346. if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
  347. return nil, common.Address{}, 0, ErrContractAddressCollision
  348. }
  349. // Create a new account on the state
  350. snapshot := evm.StateDB.Snapshot()
  351. evm.StateDB.CreateAccount(address)
  352. if evm.ChainConfig().IsEIP158(evm.BlockNumber) {
  353. evm.StateDB.SetNonce(address, 1)
  354. }
  355. evm.Transfer(evm.StateDB, caller.Address(), address, value)
  356. // Initialise a new contract and set the code that is to be used by the EVM.
  357. // The contract is a scoped environment for this execution context only.
  358. contract := NewContract(caller, AccountRef(address), value, gas)
  359. contract.SetCodeOptionalHash(&address, codeAndHash)
  360. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  361. return nil, address, gas, nil
  362. }
  363. if evm.vmConfig.Debug && evm.depth == 0 {
  364. evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value)
  365. }
  366. start := time.Now()
  367. ret, err := run(evm, contract, nil, false)
  368. // check whether the max code size has been exceeded
  369. maxCodeSizeExceeded := evm.ChainConfig().IsEIP158(evm.BlockNumber) && len(ret) > params.MaxCodeSize
  370. // if the contract creation ran successfully and no errors were returned
  371. // calculate the gas required to store the code. If the code could not
  372. // be stored due to not enough gas set an error and let it be handled
  373. // by the error checking condition below.
  374. if err == nil && !maxCodeSizeExceeded {
  375. createDataGas := uint64(len(ret)) * params.CreateDataGas
  376. if contract.UseGas(createDataGas) {
  377. evm.StateDB.SetCode(address, ret)
  378. } else {
  379. err = ErrCodeStoreOutOfGas
  380. }
  381. }
  382. // When an error was returned by the EVM or when setting the creation code
  383. // above we revert to the snapshot and consume any gas remaining. Additionally
  384. // when we're in homestead this also counts for code storage gas errors.
  385. if maxCodeSizeExceeded || (err != nil && (evm.ChainConfig().IsHomestead(evm.BlockNumber) || err != ErrCodeStoreOutOfGas)) {
  386. evm.StateDB.RevertToSnapshot(snapshot)
  387. if err != errExecutionReverted {
  388. contract.UseGas(contract.Gas)
  389. }
  390. }
  391. // Assign err if contract code size exceeds the max while the err is still empty.
  392. if maxCodeSizeExceeded && err == nil {
  393. err = errMaxCodeSizeExceeded
  394. }
  395. if evm.vmConfig.Debug && evm.depth == 0 {
  396. evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
  397. }
  398. return ret, address, contract.Gas, err
  399. }
  400. // Create creates a new contract using code as deployment code.
  401. func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
  402. contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
  403. return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
  404. }
  405. // Create2 creates a new contract using code as deployment code.
  406. //
  407. // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
  408. // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
  409. 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) {
  410. codeAndHash := &codeAndHash{code: code}
  411. contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), codeAndHash.Hash().Bytes())
  412. return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
  413. }
  414. // ChainConfig returns the environment's chain configuration
  415. func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }