evm.go 15 KB

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