ethclient.go 16 KB

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