evm.go 11 KB

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