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