evm.go 15 KB

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