bitcoin_async_client/
queryable.rs

1use crate::client::Result;
2use crate::client::RpcApi;
3
4/// A type that can be queried from Bitcoin Core.
5#[async_trait::async_trait]
6pub trait Queryable<C: RpcApi>: Sized {
7    /// Type of the ID used to query the item.
8    type Id;
9    /// Query the item using `rpc` and convert to `Self`.
10    async fn query(rpc: &C, id: &Self::Id) -> Result<Self>;
11}
12
13#[async_trait::async_trait]
14impl<C: RpcApi + Sync> Queryable<C> for bitcoin::block::Block {
15    type Id = bitcoin::BlockHash;
16
17    async fn query(rpc: &C, id: &Self::Id) -> Result<Self> {
18        let rpc_name = "getblock";
19        let hex: String =
20            rpc.call(rpc_name, [serde_json::to_value(id)?, 0.into()].as_slice()).await?;
21        Ok(bitcoin::consensus::encode::deserialize_hex(&hex)?)
22    }
23}
24
25#[async_trait::async_trait]
26impl<C: RpcApi + Sync> Queryable<C> for bitcoin::transaction::Transaction {
27    type Id = bitcoin::Txid;
28
29    async fn query(rpc: &C, id: &Self::Id) -> Result<Self> {
30        let rpc_name = "getrawtransaction";
31        let hex: String = rpc.call(rpc_name, [serde_json::to_value(id)?].as_slice()).await?;
32        Ok(bitcoin::consensus::encode::deserialize_hex(&hex)?)
33    }
34}
35
36#[async_trait::async_trait]
37impl<C: RpcApi + Sync> Queryable<C> for Option<bitcoin_json::GetTxOutResult> {
38    type Id = bitcoin::OutPoint;
39
40    async fn query(rpc: &C, id: &Self::Id) -> Result<Self> {
41        rpc.get_tx_out(&id.txid, id.vout, Some(true)).await
42    }
43}