ethclient.go 19 KB

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