ethclient.go 15 KB

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