evm.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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
  244. // EVM. The contract is a scoped environment for this execution context
  245. // only.
  246. contract := NewContract(caller, to, value, gas)
  247. contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
  248. ret, err = run(evm, contract, input, false)
  249. if err != nil {
  250. evm.StateDB.RevertToSnapshot(snapshot)
  251. if err != errExecutionReverted {
  252. contract.UseGas(contract.Gas)
  253. }
  254. }
  255. return ret, contract.Gas, err
  256. }
  257. // DelegateCall executes the contract associated with the addr with the given input
  258. // as parameters. It reverses the state in case of an execution error.
  259. //
  260. // DelegateCall differs from CallCode in the sense that it executes the given address'
  261. // code with the caller as context and the caller is set to the caller of the caller.
  262. func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
  263. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  264. return nil, gas, nil
  265. }
  266. // Fail if we're trying to execute above the call depth limit
  267. if evm.depth > int(params.CallCreateDepth) {
  268. return nil, gas, ErrDepth
  269. }
  270. var (
  271. snapshot = evm.StateDB.Snapshot()
  272. to = AccountRef(caller.Address())
  273. )
  274. // Initialise a new contract and make initialise the delegate values
  275. contract := NewContract(caller, to, nil, gas).AsDelegate()
  276. contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
  277. ret, err = run(evm, contract, input, false)
  278. if err != nil {
  279. evm.StateDB.RevertToSnapshot(snapshot)
  280. if err != errExecutionReverted {
  281. contract.UseGas(contract.Gas)
  282. }
  283. }
  284. return ret, contract.Gas, err
  285. }
  286. // StaticCall executes the contract associated with the addr with the given input
  287. // as parameters while disallowing any modifications to the state during the call.
  288. // Opcodes that attempt to perform such modifications will result in exceptions
  289. // instead of performing the modifications.
  290. func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
  291. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  292. return nil, gas, nil
  293. }
  294. // Fail if we're trying to execute above the call depth limit
  295. if evm.depth > int(params.CallCreateDepth) {
  296. return nil, gas, ErrDepth
  297. }
  298. var (
  299. to = AccountRef(addr)
  300. snapshot = evm.StateDB.Snapshot()
  301. )
  302. // Initialise a new contract and set the code that is to be used by the
  303. // EVM. The contract is a scoped environment for this execution context
  304. // only.
  305. contract := NewContract(caller, to, new(big.Int), gas)
  306. contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
  307. // When an error was returned by the EVM or when setting the creation code
  308. // above we revert to the snapshot and consume any gas remaining. Additionally
  309. // when we're in Homestead this also counts for code storage gas errors.
  310. ret, err = run(evm, contract, input, true)
  311. if err != nil {
  312. evm.StateDB.RevertToSnapshot(snapshot)
  313. if err != errExecutionReverted {
  314. contract.UseGas(contract.Gas)
  315. }
  316. }
  317. return ret, contract.Gas, err
  318. }
  319. type codeAndHash struct {
  320. code []byte
  321. hash common.Hash
  322. }
  323. func (c *codeAndHash) Hash() common.Hash {
  324. if c.hash == (common.Hash{}) {
  325. c.hash = crypto.Keccak256Hash(c.code)
  326. }
  327. return c.hash
  328. }
  329. // create creates a new contract using code as deployment code.
  330. func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
  331. // Depth check execution. Fail if we're trying to execute above the
  332. // limit.
  333. if evm.depth > int(params.CallCreateDepth) {
  334. return nil, common.Address{}, gas, ErrDepth
  335. }
  336. if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
  337. return nil, common.Address{}, gas, ErrInsufficientBalance
  338. }
  339. nonce := evm.StateDB.GetNonce(caller.Address())
  340. evm.StateDB.SetNonce(caller.Address(), nonce+1)
  341. // Ensure there's no existing contract already at the designated address
  342. contractHash := evm.StateDB.GetCodeHash(address)
  343. if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
  344. return nil, common.Address{}, 0, ErrContractAddressCollision
  345. }
  346. // Create a new account on the state
  347. snapshot := evm.StateDB.Snapshot()
  348. evm.StateDB.CreateAccount(address)
  349. if evm.ChainConfig().IsEIP158(evm.BlockNumber) {
  350. evm.StateDB.SetNonce(address, 1)
  351. }
  352. evm.Transfer(evm.StateDB, caller.Address(), address, value)
  353. // initialise a new contract and set the code that is to be used by the
  354. // EVM. The contract is a scoped environment for this execution context
  355. // only.
  356. contract := NewContract(caller, AccountRef(address), value, gas)
  357. contract.SetCodeOptionalHash(&address, codeAndHash)
  358. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  359. return nil, address, gas, nil
  360. }
  361. if evm.vmConfig.Debug && evm.depth == 0 {
  362. evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, codeAndHash.code, gas, value)
  363. }
  364. start := time.Now()
  365. ret, err := run(evm, contract, nil, false)
  366. // check whether the max code size has been exceeded
  367. maxCodeSizeExceeded := evm.ChainConfig().IsEIP158(evm.BlockNumber) && len(ret) > params.MaxCodeSize
  368. // if the contract creation ran successfully and no errors were returned
  369. // calculate the gas required to store the code. If the code could not
  370. // be stored due to not enough gas set an error and let it be handled
  371. // by the error checking condition below.
  372. if err == nil && !maxCodeSizeExceeded {
  373. createDataGas := uint64(len(ret)) * params.CreateDataGas
  374. if contract.UseGas(createDataGas) {
  375. evm.StateDB.SetCode(address, ret)
  376. } else {
  377. err = ErrCodeStoreOutOfGas
  378. }
  379. }
  380. // When an error was returned by the EVM or when setting the creation code
  381. // above we revert to the snapshot and consume any gas remaining. Additionally
  382. // when we're in homestead this also counts for code storage gas errors.
  383. if maxCodeSizeExceeded || (err != nil && (evm.ChainConfig().IsHomestead(evm.BlockNumber) || err != ErrCodeStoreOutOfGas)) {
  384. evm.StateDB.RevertToSnapshot(snapshot)
  385. if err != errExecutionReverted {
  386. contract.UseGas(contract.Gas)
  387. }
  388. }
  389. // Assign err if contract code size exceeds the max while the err is still empty.
  390. if maxCodeSizeExceeded && err == nil {
  391. err = errMaxCodeSizeExceeded
  392. }
  393. if evm.vmConfig.Debug && evm.depth == 0 {
  394. evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
  395. }
  396. return ret, address, contract.Gas, err
  397. }
  398. // Create creates a new contract using code as deployment code.
  399. func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
  400. contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
  401. return evm.create(caller, &codeAndHash{code: code}, gas, value, contractAddr)
  402. }
  403. // Create2 creates a new contract using code as deployment code.
  404. //
  405. // The different between Create2 with Create is Create2 uses sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))[12:]
  406. // instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
  407. 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) {
  408. codeAndHash := &codeAndHash{code: code}
  409. contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), codeAndHash.Hash().Bytes())
  410. return evm.create(caller, codeAndHash, gas, endowment, contractAddr)
  411. }
  412. // ChainConfig returns the environment's chain configuration
  413. func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }