ethclient.go 12 KB

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