evm.go 15 KB

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