ethclient.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. // Package ethclient provides a client for the Ethereum RPC API.
  17. package ethclient
  18. import (
  19. "encoding/json"
  20. "fmt"
  21. "math/big"
  22. "github.com/ethereum/go-ethereum"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/common/hexutil"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. "github.com/ethereum/go-ethereum/rpc"
  28. "golang.org/x/net/context"
  29. )
  30. // Client defines typed wrappers for the Ethereum RPC API.
  31. type Client struct {
  32. c *rpc.Client
  33. }
  34. // Dial connects a client to the given URL.
  35. func Dial(rawurl string) (*Client, error) {
  36. c, err := rpc.Dial(rawurl)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return NewClient(c), nil
  41. }
  42. // NewClient creates a client that uses the given RPC client.
  43. func NewClient(c *rpc.Client) *Client {
  44. return &Client{c}
  45. }
  46. // Blockchain Access
  47. // BlockByHash returns the given full block.
  48. //
  49. // Note that loading full blocks requires two requests. Use HeaderByHash
  50. // if you don't need all transactions or uncle headers.
  51. func (ec *Client) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
  52. return ec.getBlock(ctx, "eth_getBlockByHash", hash, true)
  53. }
  54. // BlockByNumber returns a block from the current canonical chain. If number is nil, the
  55. // latest known block is returned.
  56. //
  57. // Note that loading full blocks requires two requests. Use HeaderByNumber
  58. // if you don't need all transactions or uncle headers.
  59. func (ec *Client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
  60. return ec.getBlock(ctx, "eth_getBlockByNumber", toBlockNumArg(number), true)
  61. }
  62. type rpcBlock struct {
  63. Hash common.Hash `json:"hash"`
  64. Transactions []*types.Transaction `json:"transactions"`
  65. UncleHashes []common.Hash `json:"uncles"`
  66. }
  67. func (ec *Client) getBlock(ctx context.Context, method string, args ...interface{}) (*types.Block, error) {
  68. var raw json.RawMessage
  69. err := ec.c.CallContext(ctx, &raw, method, args...)
  70. if err != nil {
  71. return nil, err
  72. } else if len(raw) == 0 {
  73. return nil, ethereum.NotFound
  74. }
  75. // Decode header and transactions.
  76. var head *types.Header
  77. var body rpcBlock
  78. if err := json.Unmarshal(raw, &head); err != nil {
  79. return nil, err
  80. }
  81. if err := json.Unmarshal(raw, &body); err != nil {
  82. return nil, err
  83. }
  84. // Quick-verify transaction and uncle lists. This mostly helps with debugging the server.
  85. if head.UncleHash == types.EmptyUncleHash && len(body.UncleHashes) > 0 {
  86. return nil, fmt.Errorf("server returned non-empty uncle list but block header indicates no uncles")
  87. }
  88. if head.UncleHash != types.EmptyUncleHash && len(body.UncleHashes) == 0 {
  89. return nil, fmt.Errorf("server returned empty uncle list but block header indicates uncles")
  90. }
  91. if head.TxHash == types.EmptyRootHash && len(body.Transactions) > 0 {
  92. return nil, fmt.Errorf("server returned non-empty transaction list but block header indicates no transactions")
  93. }
  94. if head.TxHash != types.EmptyRootHash && len(body.Transactions) == 0 {
  95. return nil, fmt.Errorf("server returned empty transaction list but block header indicates transactions")
  96. }
  97. // Load uncles because they are not included in the block response.
  98. var uncles []*types.Header
  99. if len(body.UncleHashes) > 0 {
  100. uncles = make([]*types.Header, len(body.UncleHashes))
  101. reqs := make([]rpc.BatchElem, len(body.UncleHashes))
  102. for i := range reqs {
  103. reqs[i] = rpc.BatchElem{
  104. Method: "eth_getUncleByBlockHashAndIndex",
  105. Args: []interface{}{body.Hash, hexutil.EncodeUint64(uint64(i))},
  106. Result: &uncles[i],
  107. }
  108. }
  109. if err := ec.c.BatchCallContext(ctx, reqs); err != nil {
  110. return nil, err
  111. }
  112. for i := range reqs {
  113. if reqs[i].Error != nil {
  114. return nil, reqs[i].Error
  115. }
  116. if uncles[i] == nil {
  117. return nil, fmt.Errorf("got null header for uncle %d of block %x", i, body.Hash[:])
  118. }
  119. }
  120. }
  121. return types.NewBlockWithHeader(head).WithBody(body.Transactions, uncles), nil
  122. }
  123. // HeaderByHash returns the block header with the given hash.
  124. func (ec *Client) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
  125. var head *types.Header
  126. err := ec.c.CallContext(ctx, &head, "eth_getBlockByHash", hash, false)
  127. if err == nil && head == nil {
  128. err = ethereum.NotFound
  129. }
  130. return head, err
  131. }
  132. // HeaderByNumber returns a block header from the current canonical chain. If number is
  133. // nil, the latest known header is returned.
  134. func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
  135. var head *types.Header
  136. err := ec.c.CallContext(ctx, &head, "eth_getBlockByNumber", toBlockNumArg(number), false)
  137. if err == nil && head == nil {
  138. err = ethereum.NotFound
  139. }
  140. return head, err
  141. }
  142. // TransactionByHash returns the transaction with the given hash.
  143. func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx *types.Transaction, isPending bool, err error) {
  144. var raw json.RawMessage
  145. err = ec.c.CallContext(ctx, &raw, "eth_getTransactionByHash", hash)
  146. if err != nil {
  147. return nil, false, err
  148. } else if len(raw) == 0 {
  149. return nil, false, ethereum.NotFound
  150. }
  151. if err := json.Unmarshal(raw, &tx); err != nil {
  152. return nil, false, err
  153. } else if _, r, _ := tx.RawSignatureValues(); r == nil {
  154. return nil, false, fmt.Errorf("server returned transaction without signature")
  155. }
  156. var block struct{ BlockHash *common.Hash }
  157. if err := json.Unmarshal(raw, &block); err != nil {
  158. return nil, false, err
  159. }
  160. return tx, block.BlockHash == nil, nil
  161. }
  162. // TransactionCount returns the total number of transactions in the given block.
  163. func (ec *Client) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) {
  164. var num hexutil.Uint
  165. err := ec.c.CallContext(ctx, &num, "eth_getBlockTransactionCountByHash", blockHash)
  166. return uint(num), err
  167. }
  168. // TransactionInBlock returns a single transaction at index in the given block.
  169. func (ec *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) {
  170. var tx *types.Transaction
  171. err := ec.c.CallContext(ctx, &tx, "eth_getTransactionByBlockHashAndIndex", blockHash, hexutil.Uint64(index))
  172. if err == nil {
  173. if tx == nil {
  174. return nil, ethereum.NotFound
  175. } else if _, r, _ := tx.RawSignatureValues(); r == nil {
  176. return nil, fmt.Errorf("server returned transaction without signature")
  177. }
  178. }
  179. return tx, err
  180. }
  181. // TransactionReceipt returns the receipt of a transaction by transaction hash.
  182. // Note that the receipt is not available for pending transactions.
  183. func (ec *Client) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
  184. var r *types.Receipt
  185. err := ec.c.CallContext(ctx, &r, "eth_getTransactionReceipt", txHash)
  186. if err == nil {
  187. if r == nil {
  188. return nil, ethereum.NotFound
  189. } else if len(r.PostState) == 0 {
  190. return nil, fmt.Errorf("server returned receipt without post state")
  191. }
  192. }
  193. return r, err
  194. }
  195. func toBlockNumArg(number *big.Int) string {
  196. if number == nil {
  197. return "latest"
  198. }
  199. return hexutil.EncodeBig(number)
  200. }
  201. type rpcProgress struct {
  202. StartingBlock hexutil.Uint64
  203. CurrentBlock hexutil.Uint64
  204. HighestBlock hexutil.Uint64
  205. PulledStates hexutil.Uint64
  206. KnownStates hexutil.Uint64
  207. }
  208. // SyncProgress retrieves the current progress of the sync algorithm. If there's
  209. // no sync currently running, it returns nil.
  210. func (ec *Client) SyncProgress(ctx context.Context) (*ethereum.SyncProgress, error) {
  211. var raw json.RawMessage
  212. if err := ec.c.CallContext(ctx, &raw, "eth_syncing"); err != nil {
  213. return nil, err
  214. }
  215. // Handle the possible response types
  216. var syncing bool
  217. if err := json.Unmarshal(raw, &syncing); err == nil {
  218. return nil, nil // Not syncing (always false)
  219. }
  220. var progress *rpcProgress
  221. if err := json.Unmarshal(raw, &progress); err != nil {
  222. return nil, err
  223. }
  224. return &ethereum.SyncProgress{
  225. StartingBlock: uint64(progress.StartingBlock),
  226. CurrentBlock: uint64(progress.CurrentBlock),
  227. HighestBlock: uint64(progress.HighestBlock),
  228. PulledStates: uint64(progress.PulledStates),
  229. KnownStates: uint64(progress.KnownStates),
  230. }, nil
  231. }
  232. // SubscribeNewHead subscribes to notifications about the current blockchain head
  233. // on the given channel.
  234. func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {
  235. return ec.c.EthSubscribe(ctx, ch, "newHeads", map[string]struct{}{})
  236. }
  237. // State Access
  238. // BalanceAt returns the wei balance of the given account.
  239. // The block number can be nil, in which case the balance is taken from the latest known block.
  240. func (ec *Client) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) {
  241. var result hexutil.Big
  242. err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, toBlockNumArg(blockNumber))
  243. return (*big.Int)(&result), err
  244. }
  245. // StorageAt returns the value of key in the contract storage of the given account.
  246. // The block number can be nil, in which case the value is taken from the latest known block.
  247. func (ec *Client) StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
  248. var result hexutil.Bytes
  249. err := ec.c.CallContext(ctx, &result, "eth_getStorageAt", account, key, toBlockNumArg(blockNumber))
  250. return result, err
  251. }
  252. // CodeAt returns the contract code of the given account.
  253. // The block number can be nil, in which case the code is taken from the latest known block.
  254. func (ec *Client) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) {
  255. var result hexutil.Bytes
  256. err := ec.c.CallContext(ctx, &result, "eth_getCode", account, toBlockNumArg(blockNumber))
  257. return result, err
  258. }
  259. // NonceAt returns the account nonce of the given account.
  260. // The block number can be nil, in which case the nonce is taken from the latest known block.
  261. func (ec *Client) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) {
  262. var result hexutil.Uint64
  263. err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, toBlockNumArg(blockNumber))
  264. return uint64(result), err
  265. }
  266. // Filters
  267. // FilterLogs executes a filter query.
  268. func (ec *Client) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) {
  269. var result []types.Log
  270. err := ec.c.CallContext(ctx, &result, "eth_getLogs", toFilterArg(q))
  271. return result, err
  272. }
  273. // SubscribeFilterLogs subscribes to the results of a streaming filter query.
  274. func (ec *Client) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
  275. return ec.c.EthSubscribe(ctx, ch, "logs", toFilterArg(q))
  276. }
  277. func toFilterArg(q ethereum.FilterQuery) interface{} {
  278. arg := map[string]interface{}{
  279. "fromBlock": toBlockNumArg(q.FromBlock),
  280. "toBlock": toBlockNumArg(q.ToBlock),
  281. "address": q.Addresses,
  282. "topics": q.Topics,
  283. }
  284. if q.FromBlock == nil {
  285. arg["fromBlock"] = "0x0"
  286. }
  287. return arg
  288. }
  289. // Pending State
  290. // PendingBalanceAt returns the wei balance of the given account in the pending state.
  291. func (ec *Client) PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error) {
  292. var result hexutil.Big
  293. err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, "pending")
  294. return (*big.Int)(&result), err
  295. }
  296. // PendingStorageAt returns the value of key in the contract storage of the given account in the pending state.
  297. func (ec *Client) PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) ([]byte, error) {
  298. var result hexutil.Bytes
  299. err := ec.c.CallContext(ctx, &result, "eth_getStorageAt", account, key, "pending")
  300. return result, err
  301. }
  302. // PendingCodeAt returns the contract code of the given account in the pending state.
  303. func (ec *Client) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) {
  304. var result hexutil.Bytes
  305. err := ec.c.CallContext(ctx, &result, "eth_getCode", account, "pending")
  306. return result, err
  307. }
  308. // PendingNonceAt returns the account nonce of the given account in the pending state.
  309. // This is the nonce that should be used for the next transaction.
  310. func (ec *Client) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
  311. var result hexutil.Uint64
  312. err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, "pending")
  313. return uint64(result), err
  314. }
  315. // PendingTransactionCount returns the total number of transactions in the pending state.
  316. func (ec *Client) PendingTransactionCount(ctx context.Context) (uint, error) {
  317. var num hexutil.Uint
  318. err := ec.c.CallContext(ctx, &num, "eth_getBlockTransactionCountByNumber", "pending")
  319. return uint(num), err
  320. }
  321. // TODO: SubscribePendingTransactions (needs server side)
  322. // Contract Calling
  323. // CallContract executes a message call transaction, which is directly executed in the VM
  324. // of the node, but never mined into the blockchain.
  325. //
  326. // blockNumber selects the block height at which the call runs. It can be nil, in which
  327. // case the code is taken from the latest known block. Note that state from very old
  328. // blocks might not be available.
  329. func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
  330. var hex hexutil.Bytes
  331. err := ec.c.CallContext(ctx, &hex, "eth_call", toCallArg(msg), toBlockNumArg(blockNumber))
  332. if err != nil {
  333. return nil, err
  334. }
  335. return hex, nil
  336. }
  337. // PendingCallContract executes a message call transaction using the EVM.
  338. // The state seen by the contract call is the pending state.
  339. func (ec *Client) PendingCallContract(ctx context.Context, msg ethereum.CallMsg) ([]byte, error) {
  340. var hex hexutil.Bytes
  341. err := ec.c.CallContext(ctx, &hex, "eth_call", toCallArg(msg), "pending")
  342. if err != nil {
  343. return nil, err
  344. }
  345. return hex, nil
  346. }
  347. // SuggestGasPrice retrieves the currently suggested gas price to allow a timely
  348. // execution of a transaction.
  349. func (ec *Client) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
  350. var hex hexutil.Big
  351. if err := ec.c.CallContext(ctx, &hex, "eth_gasPrice"); err != nil {
  352. return nil, err
  353. }
  354. return (*big.Int)(&hex), nil
  355. }
  356. // EstimateGas tries to estimate the gas needed to execute a specific transaction based on
  357. // the current pending state of the backend blockchain. There is no guarantee that this is
  358. // the true gas limit requirement as other transactions may be added or removed by miners,
  359. // but it should provide a basis for setting a reasonable default.
  360. func (ec *Client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (*big.Int, error) {
  361. var hex hexutil.Big
  362. err := ec.c.CallContext(ctx, &hex, "eth_estimateGas", toCallArg(msg))
  363. if err != nil {
  364. return nil, err
  365. }
  366. return (*big.Int)(&hex), nil
  367. }
  368. // SendTransaction injects a signed transaction into the pending pool for execution.
  369. //
  370. // If the transaction was a contract creation use the TransactionReceipt method to get the
  371. // contract address after the transaction has been mined.
  372. func (ec *Client) SendTransaction(ctx context.Context, tx *types.Transaction) error {
  373. data, err := rlp.EncodeToBytes(tx)
  374. if err != nil {
  375. return err
  376. }
  377. return ec.c.CallContext(ctx, nil, "eth_sendRawTransaction", common.ToHex(data))
  378. }
  379. func toCallArg(msg ethereum.CallMsg) interface{} {
  380. arg := map[string]interface{}{
  381. "from": msg.From,
  382. "to": msg.To,
  383. }
  384. if len(msg.Data) > 0 {
  385. arg["data"] = hexutil.Bytes(msg.Data)
  386. }
  387. if msg.Value != nil {
  388. arg["value"] = (*hexutil.Big)(msg.Value)
  389. }
  390. if msg.Gas != nil {
  391. arg["gas"] = (*hexutil.Big)(msg.Gas)
  392. }
  393. if msg.GasPrice != nil {
  394. arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice)
  395. }
  396. return arg
  397. }