evm.go 14 KB

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