ethclient.go 12 KB

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