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::bitcoint4;
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 bitcoint4::block::Block {
26    type Id = bitcoint4::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        let bytes: Vec<u8> = bitcoint4::hashes::hex::FromHex::from_hex(&hex)?;
32        Ok(bitcoint4::consensus::encode::deserialize(&bytes)?)
33    }
34}
35
36impl<C: RpcApi> Queryable<C> for bitcoint4::transaction::Transaction {
37    type Id = bitcoint4::Txid;
38
39    fn query(rpc: &C, id: &Self::Id) -> Result<Self> {
40        let rpc_name = "getrawtransaction";
41        let hex: String = rpc.call(rpc_name, &[serde_json::to_value(id)?])?;
42        let bytes: Vec<u8> = bitcoint4::hashes::hex::FromHex::from_hex(&hex)?;
43        Ok(bitcoint4::consensus::encode::deserialize(&bytes)?)
44    }
45}
46
47impl<C: RpcApi> Queryable<C> for Option<crate::json::GetTxOutResult> {
48    type Id = bitcoint4::OutPoint;
49
50    fn query(rpc: &C, id: &Self::Id) -> Result<Self> {
51        rpc.get_tx_out(&id.txid, id.vout, Some(true))
52    }
53}