fedimint_server_bitcoin_rpc/
bitcoind.rs

1use anyhow::{Context, anyhow};
2use bitcoin::{BlockHash, Network, Transaction};
3use bitcoincore_rpc::Error::JsonRpc;
4use bitcoincore_rpc::bitcoincore_rpc_json::EstimateMode;
5use bitcoincore_rpc::jsonrpc::Error::Rpc;
6use bitcoincore_rpc::{Auth, Client, RpcApi};
7use fedimint_core::Feerate;
8use fedimint_core::envs::BitcoinRpcConfig;
9use fedimint_core::runtime::block_in_place;
10use fedimint_core::util::SafeUrl;
11use fedimint_logging::LOG_BITCOIND_CORE;
12use fedimint_server_core::bitcoin_rpc::IServerBitcoinRpc;
13use tracing::info;
14
15#[derive(Debug)]
16pub struct BitcoindClient {
17    client: Client,
18    url: SafeUrl,
19}
20
21impl BitcoindClient {
22    pub fn new(url: &SafeUrl) -> anyhow::Result<Self> {
23        let auth = Auth::UserPass(
24            url.username().to_owned(),
25            url.password()
26                .context("Bitcoin RPC URL is missing password")?
27                .to_owned(),
28        );
29
30        let url = url
31            .without_auth()
32            .map_err(|()| anyhow!("Failed to strip auth from Bitcoin Rpc Url"))?;
33
34        Ok(Self {
35            client: Client::new(url.as_str(), auth)?,
36            url,
37        })
38    }
39}
40
41#[async_trait::async_trait]
42impl IServerBitcoinRpc for BitcoindClient {
43    fn get_bitcoin_rpc_config(&self) -> BitcoinRpcConfig {
44        BitcoinRpcConfig {
45            kind: "bitcoind".to_string(),
46            url: self.url.clone(),
47        }
48    }
49
50    fn get_url(&self) -> SafeUrl {
51        self.url.clone()
52    }
53
54    async fn get_network(&self) -> anyhow::Result<Network> {
55        block_in_place(|| self.client.get_blockchain_info())
56            .map(|network| network.chain)
57            .map_err(anyhow::Error::from)
58    }
59
60    async fn get_block_count(&self) -> anyhow::Result<u64> {
61        // The RPC function is confusingly named and actually returns the block height
62        block_in_place(|| self.client.get_block_count())
63            .map(|height| height + 1)
64            .map_err(anyhow::Error::from)
65    }
66
67    async fn get_block_hash(&self, height: u64) -> anyhow::Result<BlockHash> {
68        block_in_place(|| self.client.get_block_hash(height)).map_err(anyhow::Error::from)
69    }
70
71    async fn get_block(&self, hash: &BlockHash) -> anyhow::Result<bitcoin::Block> {
72        block_in_place(|| self.client.get_block(hash)).map_err(anyhow::Error::from)
73    }
74
75    async fn get_feerate(&self) -> anyhow::Result<Option<Feerate>> {
76        let feerate = block_in_place(|| {
77            self.client
78                .estimate_smart_fee(1, Some(EstimateMode::Conservative))
79        })?
80        .fee_rate
81        .map(|per_kb| Feerate {
82            sats_per_kvb: per_kb.to_sat(),
83        });
84
85        Ok(feerate)
86    }
87
88    async fn submit_transaction(&self, transaction: Transaction) {
89        match block_in_place(|| self.client.send_raw_transaction(&transaction)) {
90            // Bitcoin core's RPC will return error code -27 if a transaction is already in a block.
91            // This is considered a success case, so we don't surface the error log.
92            //
93            // https://github.com/bitcoin/bitcoin/blob/daa56f7f665183bcce3df146f143be37f33c123e/src/rpc/protocol.h#L48
94            Err(JsonRpc(Rpc(e))) if e.code == -27 => (),
95            Err(e) => info!(target: LOG_BITCOIND_CORE, ?e, "Error broadcasting transaction"),
96            Ok(_) => (),
97        }
98    }
99
100    async fn get_sync_percentage(&self) -> anyhow::Result<Option<f64>> {
101        Ok(Some(
102            block_in_place(|| self.client.get_blockchain_info())?.verification_progress,
103        ))
104    }
105}