evm.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/crypto"
  22. "github.com/ethereum/go-ethereum/params"
  23. )
  24. // emptyCodeHash is used by create to ensure deployment is disallowed to already
  25. // deployed contract addresses (relevant after the account abstraction).
  26. var emptyCodeHash = crypto.Keccak256Hash(nil)
  27. type (
  28. CanTransferFunc func(StateDB, common.Address, *big.Int) bool
  29. TransferFunc func(StateDB, common.Address, common.Address, *big.Int)
  30. // GetHashFunc returns the nth block hash in the blockchain
  31. // and is used by the BLOCKHASH EVM op code.
  32. GetHashFunc func(uint64) common.Hash
  33. )
  34. // run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
  35. func run(evm *EVM, snapshot int, contract *Contract, input []byte) ([]byte, error) {
  36. if contract.CodeAddr != nil {
  37. precompiles := PrecompiledContractsHomestead
  38. if evm.ChainConfig().IsMetropolis(evm.BlockNumber) {
  39. precompiles = PrecompiledContractsMetropolis
  40. }
  41. if p := precompiles[*contract.CodeAddr]; p != nil {
  42. return RunPrecompiledContract(p, input, contract)
  43. }
  44. }
  45. return evm.interpreter.Run(snapshot, contract, input)
  46. }
  47. // Context provides the EVM with auxiliary information. Once provided
  48. // it shouldn't be modified.
  49. type Context struct {
  50. // CanTransfer returns whether the account contains
  51. // sufficient ether to transfer the value
  52. CanTransfer CanTransferFunc
  53. // Transfer transfers ether from one account to the other
  54. Transfer TransferFunc
  55. // GetHash returns the hash corresponding to n
  56. GetHash GetHashFunc
  57. // Message information
  58. Origin common.Address // Provides information for ORIGIN
  59. GasPrice *big.Int // Provides information for GASPRICE
  60. // Block information
  61. Coinbase common.Address // Provides information for COINBASE
  62. GasLimit *big.Int // Provides information for GASLIMIT
  63. BlockNumber *big.Int // Provides information for NUMBER
  64. Time *big.Int // Provides information for TIME
  65. Difficulty *big.Int // Provides information for DIFFICULTY
  66. }
  67. // EVM is the Ethereum Virtual Machine base object and provides
  68. // the necessary tools to run a contract on the given state with
  69. // the provided context. It should be noted that any error
  70. // generated through any of the calls should be considered a
  71. // revert-state-and-consume-all-gas operation, no checks on
  72. // specific errors should ever be performed. The interpreter makes
  73. // sure that any errors generated are to be considered faulty code.
  74. //
  75. // The EVM should never be reused and is not thread safe.
  76. type EVM struct {
  77. // Context provides auxiliary blockchain related information
  78. Context
  79. // StateDB gives access to the underlying state
  80. StateDB StateDB
  81. // Depth is the current call stack
  82. depth int
  83. // chainConfig contains information about the current chain
  84. chainConfig *params.ChainConfig
  85. // chain rules contains the chain rules for the current epoch
  86. chainRules params.Rules
  87. // virtual machine configuration options used to initialise the
  88. // evm.
  89. vmConfig Config
  90. // global (to this context) ethereum virtual machine
  91. // used throughout the execution of the tx.
  92. interpreter *Interpreter
  93. // abort is used to abort the EVM calling operations
  94. // NOTE: must be set atomically
  95. abort int32
  96. }
  97. // NewEVM retutrns a new EVM . The returned EVM is not thread safe and should
  98. // only ever be used *once*.
  99. func NewEVM(ctx Context, statedb StateDB, chainConfig *params.ChainConfig, vmConfig Config) *EVM {
  100. evm := &EVM{
  101. Context: ctx,
  102. StateDB: statedb,
  103. vmConfig: vmConfig,
  104. chainConfig: chainConfig,
  105. chainRules: chainConfig.Rules(ctx.BlockNumber),
  106. }
  107. evm.interpreter = NewInterpreter(evm, vmConfig)
  108. return evm
  109. }
  110. // Cancel cancels any running EVM operation. This may be called concurrently and
  111. // it's safe to be called multiple times.
  112. func (evm *EVM) Cancel() {
  113. atomic.StoreInt32(&evm.abort, 1)
  114. }
  115. // Call executes the contract associated with the addr with the given input as
  116. // parameters. It also handles any necessary value transfer required and takes
  117. // the necessary steps to create accounts and reverses the state in case of an
  118. // execution error or failed value transfer.
  119. func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
  120. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  121. return nil, gas, nil
  122. }
  123. // Fail if we're trying to execute above the call depth limit
  124. if evm.depth > int(params.CallCreateDepth) {
  125. return nil, gas, ErrDepth
  126. }
  127. // Fail if we're trying to transfer more than the available balance
  128. if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
  129. return nil, gas, ErrInsufficientBalance
  130. }
  131. var (
  132. to = AccountRef(addr)
  133. snapshot = evm.StateDB.Snapshot()
  134. )
  135. if !evm.StateDB.Exist(addr) {
  136. precompiles := PrecompiledContractsHomestead
  137. if evm.ChainConfig().IsMetropolis(evm.BlockNumber) {
  138. precompiles = PrecompiledContractsMetropolis
  139. }
  140. if precompiles[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 {
  141. return nil, gas, nil
  142. }
  143. evm.StateDB.CreateAccount(addr)
  144. }
  145. evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
  146. // initialise a new contract and set the code that is to be used by the
  147. // E The contract is a scoped environment for this execution context
  148. // only.
  149. contract := NewContract(caller, to, value, gas)
  150. contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
  151. ret, err = run(evm, snapshot, contract, input)
  152. // When an error was returned by the EVM or when setting the creation code
  153. // above we revert to the snapshot and consume any gas remaining. Additionally
  154. // when we're in homestead this also counts for code storage gas errors.
  155. if err != nil {
  156. evm.StateDB.RevertToSnapshot(snapshot)
  157. if err != errExecutionReverted {
  158. contract.UseGas(contract.Gas)
  159. }
  160. }
  161. return ret, contract.Gas, err
  162. }
  163. // CallCode executes the contract associated with the addr with the given input
  164. // as parameters. It also handles any necessary value transfer required and takes
  165. // the necessary steps to create accounts and reverses the state in case of an
  166. // execution error or failed value transfer.
  167. //
  168. // CallCode differs from Call in the sense that it executes the given address'
  169. // code with the caller as context.
  170. func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {
  171. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  172. return nil, gas, nil
  173. }
  174. // Fail if we're trying to execute above the call depth limit
  175. if evm.depth > int(params.CallCreateDepth) {
  176. return nil, gas, ErrDepth
  177. }
  178. // Fail if we're trying to transfer more than the available balance
  179. if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
  180. return nil, gas, ErrInsufficientBalance
  181. }
  182. var (
  183. snapshot = evm.StateDB.Snapshot()
  184. to = AccountRef(caller.Address())
  185. )
  186. // initialise a new contract and set the code that is to be used by the
  187. // E The contract is a scoped evmironment for this execution context
  188. // only.
  189. contract := NewContract(caller, to, value, gas)
  190. contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
  191. ret, err = run(evm, snapshot, contract, input)
  192. if err != nil {
  193. evm.StateDB.RevertToSnapshot(snapshot)
  194. if err != errExecutionReverted {
  195. contract.UseGas(contract.Gas)
  196. }
  197. }
  198. return ret, contract.Gas, err
  199. }
  200. // DelegateCall executes the contract associated with the addr with the given input
  201. // as parameters. It reverses the state in case of an execution error.
  202. //
  203. // DelegateCall differs from CallCode in the sense that it executes the given address'
  204. // code with the caller as context and the caller is set to the caller of the caller.
  205. func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
  206. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  207. return nil, gas, nil
  208. }
  209. // Fail if we're trying to execute above the call depth limit
  210. if evm.depth > int(params.CallCreateDepth) {
  211. return nil, gas, ErrDepth
  212. }
  213. var (
  214. snapshot = evm.StateDB.Snapshot()
  215. to = AccountRef(caller.Address())
  216. )
  217. // Initialise a new contract and make initialise the delegate values
  218. contract := NewContract(caller, to, nil, gas).AsDelegate()
  219. contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
  220. ret, err = run(evm, snapshot, contract, input)
  221. if err != nil {
  222. evm.StateDB.RevertToSnapshot(snapshot)
  223. if err != errExecutionReverted {
  224. contract.UseGas(contract.Gas)
  225. }
  226. }
  227. return ret, contract.Gas, err
  228. }
  229. // StaticCall executes the contract associated with the addr with the given input
  230. // as parameters while disallowing any modifications to the state during the call.
  231. // Opcodes that attempt to perform such modifications will result in exceptions
  232. // instead of performing the modifications.
  233. func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte, gas uint64) (ret []byte, leftOverGas uint64, err error) {
  234. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  235. return nil, gas, nil
  236. }
  237. // Fail if we're trying to execute above the call depth limit
  238. if evm.depth > int(params.CallCreateDepth) {
  239. return nil, gas, ErrDepth
  240. }
  241. // Make sure the readonly is only set if we aren't in readonly yet
  242. // this makes also sure that the readonly flag isn't removed for
  243. // child calls.
  244. if !evm.interpreter.readOnly {
  245. evm.interpreter.readOnly = true
  246. defer func() { evm.interpreter.readOnly = false }()
  247. }
  248. var (
  249. to = AccountRef(addr)
  250. snapshot = evm.StateDB.Snapshot()
  251. )
  252. // Initialise a new contract and set the code that is to be used by the
  253. // EVM. The contract is a scoped environment for this execution context
  254. // only.
  255. contract := NewContract(caller, to, new(big.Int), gas)
  256. contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
  257. // When an error was returned by the EVM or when setting the creation code
  258. // above we revert to the snapshot and consume any gas remaining. Additionally
  259. // when we're in Homestead this also counts for code storage gas errors.
  260. ret, err = run(evm, snapshot, contract, input)
  261. if err != nil {
  262. evm.StateDB.RevertToSnapshot(snapshot)
  263. if err != errExecutionReverted {
  264. contract.UseGas(contract.Gas)
  265. }
  266. }
  267. return ret, contract.Gas, err
  268. }
  269. // Create creates a new contract using code as deployment code.
  270. func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
  271. if evm.vmConfig.NoRecursion && evm.depth > 0 {
  272. return nil, common.Address{}, gas, nil
  273. }
  274. // Depth check execution. Fail if we're trying to execute above the
  275. // limit.
  276. if evm.depth > int(params.CallCreateDepth) {
  277. return nil, common.Address{}, gas, ErrDepth
  278. }
  279. if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
  280. return nil, common.Address{}, gas, ErrInsufficientBalance
  281. }
  282. // Ensure there's no existing contract already at the designated address
  283. nonce := evm.StateDB.GetNonce(caller.Address())
  284. evm.StateDB.SetNonce(caller.Address(), nonce+1)
  285. contractAddr = crypto.CreateAddress(caller.Address(), nonce)
  286. contractHash := evm.StateDB.GetCodeHash(contractAddr)
  287. if evm.StateDB.GetNonce(contractAddr) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
  288. return nil, common.Address{}, 0, ErrContractAddressCollision
  289. }
  290. // Create a new account on the state
  291. snapshot := evm.StateDB.Snapshot()
  292. evm.StateDB.CreateAccount(contractAddr)
  293. if evm.ChainConfig().IsEIP158(evm.BlockNumber) {
  294. evm.StateDB.SetNonce(contractAddr, 1)
  295. }
  296. evm.Transfer(evm.StateDB, caller.Address(), contractAddr, value)
  297. // initialise a new contract and set the code that is to be used by the
  298. // E The contract is a scoped evmironment for this execution context
  299. // only.
  300. contract := NewContract(caller, AccountRef(contractAddr), value, gas)
  301. contract.SetCallCode(&contractAddr, crypto.Keccak256Hash(code), code)
  302. ret, err = run(evm, snapshot, contract, nil)
  303. // check whether the max code size has been exceeded
  304. maxCodeSizeExceeded := len(ret) > params.MaxCodeSize
  305. // if the contract creation ran successfully and no errors were returned
  306. // calculate the gas required to store the code. If the code could not
  307. // be stored due to not enough gas set an error and let it be handled
  308. // by the error checking condition below.
  309. if err == nil && !maxCodeSizeExceeded {
  310. createDataGas := uint64(len(ret)) * params.CreateDataGas
  311. if contract.UseGas(createDataGas) {
  312. evm.StateDB.SetCode(contractAddr, ret)
  313. } else {
  314. err = ErrCodeStoreOutOfGas
  315. }
  316. }
  317. // When an error was returned by the EVM or when setting the creation code
  318. // above we revert to the snapshot and consume any gas remaining. Additionally
  319. // when we're in homestead this also counts for code storage gas errors.
  320. if maxCodeSizeExceeded || (err != nil && (evm.ChainConfig().IsHomestead(evm.BlockNumber) || err != ErrCodeStoreOutOfGas)) {
  321. evm.StateDB.RevertToSnapshot(snapshot)
  322. if err != errExecutionReverted {
  323. contract.UseGas(contract.Gas)
  324. }
  325. }
  326. // Assign err if contract code size exceeds the max while the err is still empty.
  327. if maxCodeSizeExceeded && err == nil {
  328. err = errMaxCodeSizeExceeded
  329. }
  330. return ret, contractAddr, contract.Gas, err
  331. }
  332. // ChainConfig returns the evmironment's chain configuration
  333. func (evm *EVM) ChainConfig() *params.ChainConfig { return evm.chainConfig }
  334. // Interpreter returns the EVM interpreter
  335. func (evm *EVM) Interpreter() *Interpreter { return evm.interpreter }