ethclient.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // Copyright 2016 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. // Contains a wrapper for the Ethereum client.
  17. package geth
  18. import (
  19. "math/big"
  20. "github.com/ethereum/go-ethereum/core/types"
  21. "github.com/ethereum/go-ethereum/ethclient"
  22. )
  23. // EthereumClient provides access to the Ethereum APIs.
  24. type EthereumClient struct {
  25. client *ethclient.Client
  26. }
  27. // NewEthereumClient connects a client to the given URL.
  28. func NewEthereumClient(rawurl string) (client *EthereumClient, _ error) {
  29. rawClient, err := ethclient.Dial(rawurl)
  30. return &EthereumClient{rawClient}, err
  31. }
  32. // GetBlockByHash returns the given full block.
  33. func (ec *EthereumClient) GetBlockByHash(ctx *Context, hash *Hash) (block *Block, _ error) {
  34. rawBlock, err := ec.client.BlockByHash(ctx.context, hash.hash)
  35. return &Block{rawBlock}, err
  36. }
  37. // GetBlockByNumber returns a block from the current canonical chain. If number is <0, the
  38. // latest known block is returned.
  39. func (ec *EthereumClient) GetBlockByNumber(ctx *Context, number int64) (block *Block, _ error) {
  40. if number < 0 {
  41. rawBlock, err := ec.client.BlockByNumber(ctx.context, nil)
  42. return &Block{rawBlock}, err
  43. }
  44. rawBlock, err := ec.client.BlockByNumber(ctx.context, big.NewInt(number))
  45. return &Block{rawBlock}, err
  46. }
  47. // GetHeaderByHash returns the block header with the given hash.
  48. func (ec *EthereumClient) GetHeaderByHash(ctx *Context, hash *Hash) (header *Header, _ error) {
  49. rawHeader, err := ec.client.HeaderByHash(ctx.context, hash.hash)
  50. return &Header{rawHeader}, err
  51. }
  52. // GetHeaderByNumber returns a block header from the current canonical chain. If number is <0,
  53. // the latest known header is returned.
  54. func (ec *EthereumClient) GetHeaderByNumber(ctx *Context, number int64) (header *Header, _ error) {
  55. if number < 0 {
  56. rawHeader, err := ec.client.HeaderByNumber(ctx.context, nil)
  57. return &Header{rawHeader}, err
  58. }
  59. rawHeader, err := ec.client.HeaderByNumber(ctx.context, big.NewInt(number))
  60. return &Header{rawHeader}, err
  61. }
  62. // GetTransactionByHash returns the transaction with the given hash.
  63. func (ec *EthereumClient) GetTransactionByHash(ctx *Context, hash *Hash) (tx *Transaction, _ error) {
  64. // TODO(karalabe): handle isPending
  65. rawTx, _, err := ec.client.TransactionByHash(ctx.context, hash.hash)
  66. return &Transaction{rawTx}, err
  67. }
  68. // GetTransactionSender returns the sender address of a transaction. The transaction must
  69. // be included in blockchain at the given block and index.
  70. func (ec *EthereumClient) GetTransactionSender(ctx *Context, tx *Transaction, blockhash *Hash, index int) (sender *Address, _ error) {
  71. addr, err := ec.client.TransactionSender(ctx.context, tx.tx, blockhash.hash, uint(index))
  72. return &Address{addr}, err
  73. }
  74. // GetTransactionCount returns the total number of transactions in the given block.
  75. func (ec *EthereumClient) GetTransactionCount(ctx *Context, hash *Hash) (count int, _ error) {
  76. rawCount, err := ec.client.TransactionCount(ctx.context, hash.hash)
  77. return int(rawCount), err
  78. }
  79. // GetTransactionInBlock returns a single transaction at index in the given block.
  80. func (ec *EthereumClient) GetTransactionInBlock(ctx *Context, hash *Hash, index int) (tx *Transaction, _ error) {
  81. rawTx, err := ec.client.TransactionInBlock(ctx.context, hash.hash, uint(index))
  82. return &Transaction{rawTx}, err
  83. }
  84. // GetTransactionReceipt returns the receipt of a transaction by transaction hash.
  85. // Note that the receipt is not available for pending transactions.
  86. func (ec *EthereumClient) GetTransactionReceipt(ctx *Context, hash *Hash) (receipt *Receipt, _ error) {
  87. rawReceipt, err := ec.client.TransactionReceipt(ctx.context, hash.hash)
  88. return &Receipt{rawReceipt}, err
  89. }
  90. // SyncProgress retrieves the current progress of the sync algorithm. If there's
  91. // no sync currently running, it returns nil.
  92. func (ec *EthereumClient) SyncProgress(ctx *Context) (progress *SyncProgress, _ error) {
  93. rawProgress, err := ec.client.SyncProgress(ctx.context)
  94. if rawProgress == nil {
  95. return nil, err
  96. }
  97. return &SyncProgress{*rawProgress}, err
  98. }
  99. // NewHeadHandler is a client-side subscription callback to invoke on events and
  100. // subscription failure.
  101. type NewHeadHandler interface {
  102. OnNewHead(header *Header)
  103. OnError(failure string)
  104. }
  105. // SubscribeNewHead subscribes to notifications about the current blockchain head
  106. // on the given channel.
  107. func (ec *EthereumClient) SubscribeNewHead(ctx *Context, handler NewHeadHandler, buffer int) (sub *Subscription, _ error) {
  108. // Subscribe to the event internally
  109. ch := make(chan *types.Header, buffer)
  110. rawSub, err := ec.client.SubscribeNewHead(ctx.context, ch)
  111. if err != nil {
  112. return nil, err
  113. }
  114. // Start up a dispatcher to feed into the callback
  115. go func() {
  116. for {
  117. select {
  118. case header := <-ch:
  119. handler.OnNewHead(&Header{header})
  120. case err := <-rawSub.Err():
  121. handler.OnError(err.Error())
  122. return
  123. }
  124. }
  125. }()
  126. return &Subscription{rawSub}, nil
  127. }
  128. // State Access
  129. // GetBalanceAt returns the wei balance of the given account.
  130. // The block number can be <0, in which case the balance is taken from the latest known block.
  131. func (ec *EthereumClient) GetBalanceAt(ctx *Context, account *Address, number int64) (balance *BigInt, _ error) {
  132. if number < 0 {
  133. rawBalance, err := ec.client.BalanceAt(ctx.context, account.address, nil)
  134. return &BigInt{rawBalance}, err
  135. }
  136. rawBalance, err := ec.client.BalanceAt(ctx.context, account.address, big.NewInt(number))
  137. return &BigInt{rawBalance}, err
  138. }
  139. // GetStorageAt returns the value of key in the contract storage of the given account.
  140. // The block number can be <0, in which case the value is taken from the latest known block.
  141. func (ec *EthereumClient) GetStorageAt(ctx *Context, account *Address, key *Hash, number int64) (storage []byte, _ error) {
  142. if number < 0 {
  143. return ec.client.StorageAt(ctx.context, account.address, key.hash, nil)
  144. }
  145. return ec.client.StorageAt(ctx.context, account.address, key.hash, big.NewInt(number))
  146. }
  147. // GetCodeAt returns the contract code of the given account.
  148. // The block number can be <0, in which case the code is taken from the latest known block.
  149. func (ec *EthereumClient) GetCodeAt(ctx *Context, account *Address, number int64) (code []byte, _ error) {
  150. if number < 0 {
  151. return ec.client.CodeAt(ctx.context, account.address, nil)
  152. }
  153. return ec.client.CodeAt(ctx.context, account.address, big.NewInt(number))
  154. }
  155. // GetNonceAt returns the account nonce of the given account.
  156. // The block number can be <0, in which case the nonce is taken from the latest known block.
  157. func (ec *EthereumClient) GetNonceAt(ctx *Context, account *Address, number int64) (nonce int64, _ error) {
  158. if number < 0 {
  159. rawNonce, err := ec.client.NonceAt(ctx.context, account.address, nil)
  160. return int64(rawNonce), err
  161. }
  162. rawNonce, err := ec.client.NonceAt(ctx.context, account.address, big.NewInt(number))
  163. return int64(rawNonce), err
  164. }
  165. // Filters
  166. // FilterLogs executes a filter query.
  167. func (ec *EthereumClient) FilterLogs(ctx *Context, query *FilterQuery) (logs *Logs, _ error) {
  168. rawLogs, err := ec.client.FilterLogs(ctx.context, query.query)
  169. if err != nil {
  170. return nil, err
  171. }
  172. // Temp hack due to vm.Logs being []*vm.Log
  173. res := make([]*types.Log, len(rawLogs))
  174. for i := range rawLogs {
  175. res[i] = &rawLogs[i]
  176. }
  177. return &Logs{res}, nil
  178. }
  179. // FilterLogsHandler is a client-side subscription callback to invoke on events and
  180. // subscription failure.
  181. type FilterLogsHandler interface {
  182. OnFilterLogs(log *Log)
  183. OnError(failure string)
  184. }
  185. // SubscribeFilterLogs subscribes to the results of a streaming filter query.
  186. func (ec *EthereumClient) SubscribeFilterLogs(ctx *Context, query *FilterQuery, handler FilterLogsHandler, buffer int) (sub *Subscription, _ error) {
  187. // Subscribe to the event internally
  188. ch := make(chan types.Log, buffer)
  189. rawSub, err := ec.client.SubscribeFilterLogs(ctx.context, query.query, ch)
  190. if err != nil {
  191. return nil, err
  192. }
  193. // Start up a dispatcher to feed into the callback
  194. go func() {
  195. for {
  196. select {
  197. case log := <-ch:
  198. handler.OnFilterLogs(&Log{&log})
  199. case err := <-rawSub.Err():
  200. handler.OnError(err.Error())
  201. return
  202. }
  203. }
  204. }()
  205. return &Subscription{rawSub}, nil
  206. }
  207. // Pending State
  208. // GetPendingBalanceAt returns the wei balance of the given account in the pending state.
  209. func (ec *EthereumClient) GetPendingBalanceAt(ctx *Context, account *Address) (balance *BigInt, _ error) {
  210. rawBalance, err := ec.client.PendingBalanceAt(ctx.context, account.address)
  211. return &BigInt{rawBalance}, err
  212. }
  213. // GetPendingStorageAt returns the value of key in the contract storage of the given account in the pending state.
  214. func (ec *EthereumClient) GetPendingStorageAt(ctx *Context, account *Address, key *Hash) (storage []byte, _ error) {
  215. return ec.client.PendingStorageAt(ctx.context, account.address, key.hash)
  216. }
  217. // GetPendingCodeAt returns the contract code of the given account in the pending state.
  218. func (ec *EthereumClient) GetPendingCodeAt(ctx *Context, account *Address) (code []byte, _ error) {
  219. return ec.client.PendingCodeAt(ctx.context, account.address)
  220. }
  221. // GetPendingNonceAt returns the account nonce of the given account in the pending state.
  222. // This is the nonce that should be used for the next transaction.
  223. func (ec *EthereumClient) GetPendingNonceAt(ctx *Context, account *Address) (nonce int64, _ error) {
  224. rawNonce, err := ec.client.PendingNonceAt(ctx.context, account.address)
  225. return int64(rawNonce), err
  226. }
  227. // GetPendingTransactionCount returns the total number of transactions in the pending state.
  228. func (ec *EthereumClient) GetPendingTransactionCount(ctx *Context) (count int, _ error) {
  229. rawCount, err := ec.client.PendingTransactionCount(ctx.context)
  230. return int(rawCount), err
  231. }
  232. // Contract Calling
  233. // CallContract executes a message call transaction, which is directly executed in the VM
  234. // of the node, but never mined into the blockchain.
  235. //
  236. // blockNumber selects the block height at which the call runs. It can be <0, in which
  237. // case the code is taken from the latest known block. Note that state from very old
  238. // blocks might not be available.
  239. func (ec *EthereumClient) CallContract(ctx *Context, msg *CallMsg, number int64) (output []byte, _ error) {
  240. if number < 0 {
  241. return ec.client.CallContract(ctx.context, msg.msg, nil)
  242. }
  243. return ec.client.CallContract(ctx.context, msg.msg, big.NewInt(number))
  244. }
  245. // PendingCallContract executes a message call transaction using the EVM.
  246. // The state seen by the contract call is the pending state.
  247. func (ec *EthereumClient) PendingCallContract(ctx *Context, msg *CallMsg) (output []byte, _ error) {
  248. return ec.client.PendingCallContract(ctx.context, msg.msg)
  249. }
  250. // SuggestGasPrice retrieves the currently suggested gas price to allow a timely
  251. // execution of a transaction.
  252. func (ec *EthereumClient) SuggestGasPrice(ctx *Context) (price *BigInt, _ error) {
  253. rawPrice, err := ec.client.SuggestGasPrice(ctx.context)
  254. return &BigInt{rawPrice}, err
  255. }
  256. // EstimateGas tries to estimate the gas needed to execute a specific transaction based on
  257. // the current pending state of the backend blockchain. There is no guarantee that this is
  258. // the true gas limit requirement as other transactions may be added or removed by miners,
  259. // but it should provide a basis for setting a reasonable default.
  260. func (ec *EthereumClient) EstimateGas(ctx *Context, msg *CallMsg) (gas int64, _ error) {
  261. rawGas, err := ec.client.EstimateGas(ctx.context, msg.msg)
  262. return int64(rawGas), err
  263. }
  264. // SendTransaction injects a signed transaction into the pending pool for execution.
  265. //
  266. // If the transaction was a contract creation use the TransactionReceipt method to get the
  267. // contract address after the transaction has been mined.
  268. func (ec *EthereumClient) SendTransaction(ctx *Context, tx *Transaction) error {
  269. return ec.client.SendTransaction(ctx.context, tx.tx)
  270. }