bitcoincore_rpc/
queryable.rs

1// To the extent possible under law, the author(s) have dedicated all
2// copyright and related and neighboring rights to this software to
3// the public domain worldwide. This software is distributed without
4// any warranty.
5//
6// You should have received a copy of the CC0 Public Domain Dedication
7// along with this software.
8// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
9//
10
11use crate::bitcoin;
12use serde_json;
13
14use crate::client::Result;
15use crate::client::RpcApi;
16
17/// A type that can be queried from Bitcoin Core.
18pub trait Queryable<C: RpcApi>: Sized {
19    /// Type of the ID used to query the item.
20    type Id;
21    /// Query the item using `rpc` and convert to `Self`.
22    fn query(rpc: &C, id: &Self::Id) -> Result<Self>;
23}
24
25impl<C: RpcApi> Queryable<C> for bitcoin::block::Block {
26    type Id = bitcoin::BlockHash;
27
28    fn query(rpc: &C, id: &Self::Id) -> Result<Self> {
29        let rpc_name = "getblock";
30        let hex: String = rpc.call(rpc_name, &[serde_json::to_value(id)?, 0.into()])?;
31        Ok(bitcoin::consensus::encode::deserialize_hex(&hex)?)
32    }
33}
34
35impl<C: RpcApi> Queryable<C> for bitcoin::transaction::Transaction {
36    type Id = bitcoin::Txid;
37
38    fn query(rpc: &C, id: &Self::Id) -> Result<Self> {
39        let rpc_name = "getrawtransaction";
40        let hex: String = rpc.call(rpc_name, &[serde_json::to_value(id)?])?;
41        Ok(bitcoin::consensus::encode::deserialize_hex(&hex)?)
42    }
43}
44
45impl<C: RpcApi> Queryable<C> for Option<crate::json::GetTxOutResult> {
46    type Id = bitcoin::OutPoint;
47
48    fn query(rpc: &C, id: &Self::Id) -> Result<Self> {
49        rpc.get_tx_out(&id.txid, id.vout, Some(true))
50    }
51}