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