evm.go 17 KB

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