evm.go 12 KB

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