1use std::{ops::Deref, sync::Arc};
2
3use serde::Serialize;
4use serde_json::Value;
5
6use crate::{
7 PendingRpcRequest, Result, RpcNamespace,
8 rpc::{BatchPolicy, HttpJsonRpcTransport},
9};
10
11pub const BITCOIN_RPC_METHODS: &[&str] = &[
13 "estimatesmartfee",
14 "getbestblockhash",
15 "getblock",
16 "getblockchaininfo",
17 "getblockcount",
18 "getblockhash",
19 "getblockheader",
20 "getmempoolinfo",
21 "getnetworkinfo",
22 "getrawmempool",
23 "getrawtransaction",
24 "gettxout",
25];
26
27#[derive(Clone)]
29pub struct BitcoinClient {
30 pub rpc: BitcoinRpcClient,
32}
33
34impl BitcoinClient {
35 pub(crate) const fn new(transport: Arc<HttpJsonRpcTransport>) -> Self {
36 Self {
37 rpc: BitcoinRpcClient::new(transport),
38 }
39 }
40}
41
42#[derive(Clone)]
44pub struct BitcoinRpcClient {
45 namespace: RpcNamespace,
46}
47
48impl BitcoinRpcClient {
49 pub(crate) const fn new(transport: Arc<HttpJsonRpcTransport>) -> Self {
50 Self {
51 namespace: RpcNamespace::new(transport, BatchPolicy::Any),
52 }
53 }
54}
55
56impl Deref for BitcoinRpcClient {
57 type Target = RpcNamespace;
58
59 fn deref(&self) -> &Self::Target {
60 &self.namespace
61 }
62}
63
64macro_rules! bitcoin_no_params {
65 ($(($name:ident, $wire:literal, $result:ty)),* $(,)?) => {
66 impl BitcoinRpcClient {
67 $(
68 #[doc = concat!("Creates a pending `", $wire, "` request.")]
69 #[must_use]
70 pub fn $name(&self) -> PendingRpcRequest<$result> {
71 self.namespace
72 .request($wire, Vec::<Value>::new())
73 .expect("empty parameters serialize")
74 }
75 )*
76 }
77 };
78}
79
80macro_rules! bitcoin_with_params {
81 ($(($name:ident, $wire:literal, $result:ty)),* $(,)?) => {
82 impl BitcoinRpcClient {
83 $(
84 #[doc = concat!("Creates a pending `", $wire, "` request from positional parameters.")]
85 pub fn $name<P: Serialize>(&self, params: P) -> Result<PendingRpcRequest<$result>> {
86 self.namespace.request($wire, params)
87 }
88 )*
89 }
90 };
91}
92
93bitcoin_no_params!(
94 (get_best_block_hash, "getbestblockhash", String),
95 (get_blockchain_info, "getblockchaininfo", Value),
96 (get_block_count, "getblockcount", u64),
97 (get_mempool_info, "getmempoolinfo", Value),
98 (get_network_info, "getnetworkinfo", Value),
99);
100
101bitcoin_with_params!(
102 (estimate_smart_fee, "estimatesmartfee", Value),
103 (get_block, "getblock", Value),
104 (get_block_hash, "getblockhash", String),
105 (get_block_header, "getblockheader", Value),
106 (get_raw_mempool, "getrawmempool", Value),
107 (get_raw_transaction, "getrawtransaction", Value),
108 (get_tx_out, "gettxout", Option<Value>),
109);