evm.go 18 KB

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