bdkffi/
electrum.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
use crate::bitcoin::{BlockHash, Header, Transaction, Txid};
use crate::error::ElectrumError;
use crate::types::Update;
use crate::types::{FullScanRequest, SyncRequest};

use bdk_electrum::electrum_client::HeaderNotification as BdkHeaderNotification;
use bdk_electrum::electrum_client::ServerFeaturesRes as BdkServerFeaturesRes;
use bdk_electrum::BdkElectrumClient as BdkBdkElectrumClient;
use bdk_wallet::bitcoin::Transaction as BdkTransaction;
use bdk_wallet::chain::spk_client::FullScanRequest as BdkFullScanRequest;
use bdk_wallet::chain::spk_client::FullScanResponse as BdkFullScanResponse;
use bdk_wallet::chain::spk_client::SyncRequest as BdkSyncRequest;
use bdk_wallet::chain::spk_client::SyncResponse as BdkSyncResponse;
use bdk_wallet::KeychainKind;
use bdk_wallet::Update as BdkUpdate;

use bdk_electrum::electrum_client::ElectrumApi;
use bdk_wallet::bitcoin::hex::{Case, DisplayHex};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::sync::Arc;

/// Wrapper around an electrum_client::ElectrumApi which includes an internal in-memory transaction
/// cache to avoid re-fetching already downloaded transactions.
#[derive(uniffi::Object)]
pub struct ElectrumClient(BdkBdkElectrumClient<bdk_electrum::electrum_client::Client>);

#[uniffi::export]
impl ElectrumClient {
    /// Creates a new bdk client from a electrum_client::ElectrumApi
    /// Optional: Set the proxy of the builder
    #[uniffi::constructor(default(socks5 = None))]
    pub fn new(url: String, socks5: Option<String>) -> Result<Self, ElectrumError> {
        let mut config = bdk_electrum::electrum_client::ConfigBuilder::new();
        if let Some(socks5) = socks5 {
            config = config.socks5(Some(bdk_electrum::electrum_client::Socks5Config::new(
                socks5.as_str(),
            )));
        }
        let inner_client =
            bdk_electrum::electrum_client::Client::from_config(url.as_str(), config.build())?;
        let client = BdkBdkElectrumClient::new(inner_client);
        Ok(Self(client))
    }

    /// Full scan the keychain scripts specified with the blockchain (via an Electrum client) and
    /// returns updates for bdk_chain data structures.
    ///
    /// - `request`: struct with data required to perform a spk-based blockchain client
    ///   full scan, see `FullScanRequest`.
    /// - `stop_gap`: the full scan for each keychain stops after a gap of script pubkeys with no
    ///   associated transactions.
    /// - `batch_size`: specifies the max number of script pubkeys to request for in a single batch
    ///   request.
    /// - `fetch_prev_txouts`: specifies whether we want previous `TxOuts` for fee calculation. Note
    ///   that this requires additional calls to the Electrum server, but is necessary for
    ///   calculating the fee on a transaction if your wallet does not own the inputs. Methods like
    ///   `Wallet.calculate_fee` and `Wallet.calculate_fee_rate` will return a
    ///   `CalculateFeeError::MissingTxOut` error if those TxOuts are not present in the transaction
    ///   graph.
    pub fn full_scan(
        &self,
        request: Arc<FullScanRequest>,
        stop_gap: u64,
        batch_size: u64,
        fetch_prev_txouts: bool,
    ) -> Result<Arc<Update>, ElectrumError> {
        // using option and take is not ideal but the only way to take full ownership of the request
        let request: BdkFullScanRequest<KeychainKind> = request
            .0
            .lock()
            .unwrap()
            .take()
            .ok_or(ElectrumError::RequestAlreadyConsumed)?;

        let full_scan_result: BdkFullScanResponse<KeychainKind> = self.0.full_scan(
            request,
            stop_gap as usize,
            batch_size as usize,
            fetch_prev_txouts,
        )?;

        let update = BdkUpdate {
            last_active_indices: full_scan_result.last_active_indices,
            tx_update: full_scan_result.tx_update,
            chain: full_scan_result.chain_update,
        };

        Ok(Arc::new(Update(update)))
    }

    /// Sync a set of scripts with the blockchain (via an Electrum client) for the data specified and returns updates for bdk_chain data structures.
    ///
    /// - `request`: struct with data required to perform a spk-based blockchain client
    ///   sync, see `SyncRequest`.
    /// - `batch_size`: specifies the max number of script pubkeys to request for in a single batch
    ///   request.
    /// - `fetch_prev_txouts`: specifies whether we want previous `TxOuts` for fee calculation. Note
    ///   that this requires additional calls to the Electrum server, but is necessary for
    ///   calculating the fee on a transaction if your wallet does not own the inputs. Methods like
    ///   `Wallet.calculate_fee` and `Wallet.calculate_fee_rate` will return a
    ///   `CalculateFeeError::MissingTxOut` error if those TxOuts are not present in the transaction
    ///   graph.
    ///
    /// If the scripts to sync are unknown, such as when restoring or importing a keychain that may
    /// include scripts that have been used, use full_scan with the keychain.
    pub fn sync(
        &self,
        request: Arc<SyncRequest>,
        batch_size: u64,
        fetch_prev_txouts: bool,
    ) -> Result<Arc<Update>, ElectrumError> {
        // using option and take is not ideal but the only way to take full ownership of the request
        let request: BdkSyncRequest<(KeychainKind, u32)> = request
            .0
            .lock()
            .unwrap()
            .take()
            .ok_or(ElectrumError::RequestAlreadyConsumed)?;

        let sync_result: BdkSyncResponse =
            self.0
                .sync(request, batch_size as usize, fetch_prev_txouts)?;

        let update = BdkUpdate {
            last_active_indices: BTreeMap::default(),
            tx_update: sync_result.tx_update,
            chain: sync_result.chain_update,
        };

        Ok(Arc::new(Update(update)))
    }

    /// Broadcasts a transaction to the network.
    pub fn transaction_broadcast(&self, tx: &Transaction) -> Result<Arc<Txid>, ElectrumError> {
        let bdk_transaction: BdkTransaction = tx.into();
        self.0
            .transaction_broadcast(&bdk_transaction)
            .map_err(ElectrumError::from)
            .map(|txid| Arc::new(Txid(txid)))
    }

    /// Fetch transaction of given `Txid`.
    ///
    /// If it hits the cache it will return the cached version and avoid making the request.
    pub fn fetch_tx(&self, txid: Arc<Txid>) -> Result<Arc<Transaction>, ElectrumError> {
        let tx = self.0.fetch_tx(txid.0).map_err(ElectrumError::from)?;
        Ok(Arc::new(Transaction::from(tx.as_ref().clone())))
    }

    /// Returns the capabilities of the server.
    pub fn server_features(&self) -> Result<ServerFeaturesRes, ElectrumError> {
        let res = self
            .0
            .inner
            .server_features()
            .map_err(ElectrumError::from)?;

        ServerFeaturesRes::try_from(res)
    }

    /// Estimates the fee required in bitcoin per kilobyte to confirm a transaction in `number` blocks.
    pub fn estimate_fee(&self, number: u64) -> Result<f64, ElectrumError> {
        self.0
            .inner
            .estimate_fee(number as usize)
            .map_err(ElectrumError::from)
    }

    /// Gets the block header for height `height`.
    pub fn block_header(&self, height: u64) -> Result<Header, ElectrumError> {
        self.0
            .inner
            .block_header(height as usize)
            .map_err(ElectrumError::from)
            .map(Header::from)
    }

    /// Subscribes to notifications for new block headers, by sending a blockchain.headers.subscribe call.
    pub fn block_headers_subscribe(&self) -> Result<HeaderNotification, ElectrumError> {
        self.0
            .inner
            .block_headers_subscribe()
            .map_err(ElectrumError::from)
            .map(HeaderNotification::from)
    }

    /// Tries to pop one queued notification for a new block header that we might have received.
    /// Returns `None` if there are no items in the queue.
    pub fn block_headers_pop(&self) -> Result<Option<HeaderNotification>, ElectrumError> {
        self.0
            .inner
            .block_headers_pop()
            .map_err(ElectrumError::from)
            .map(|notification| notification.map(HeaderNotification::from))
    }

    /// Pings the server.
    pub fn ping(&self) -> Result<(), ElectrumError> {
        self.0.inner.ping().map_err(ElectrumError::from)
    }

    /// Returns the minimum accepted fee by the server’s node in Bitcoin, not Satoshi.
    pub fn relay_fee(&self) -> Result<f64, ElectrumError> {
        self.0.inner.relay_fee().map_err(ElectrumError::from)
    }

    /// Gets the raw bytes of a transaction with txid. Returns an error if not found.
    pub fn transaction_get_raw(&self, txid: Arc<Txid>) -> Result<Vec<u8>, ElectrumError> {
        self.0
            .inner
            .transaction_get_raw(&txid.0)
            .map_err(ElectrumError::from)
    }
}

/// Response to an ElectrumClient.server_features request.
#[derive(uniffi::Record)]
pub struct ServerFeaturesRes {
    /// Server version reported.
    pub server_version: String,
    /// Hash of the genesis block.
    pub genesis_hash: Arc<BlockHash>,
    /// Minimum supported version of the protocol.
    pub protocol_min: String,
    /// Maximum supported version of the protocol.
    pub protocol_max: String,
    /// Hash function used to create the `ScriptHash`.
    pub hash_function: Option<String>,
    /// Pruned height of the server.
    pub pruning: Option<i64>,
}

impl TryFrom<BdkServerFeaturesRes> for ServerFeaturesRes {
    type Error = ElectrumError;

    fn try_from(value: BdkServerFeaturesRes) -> Result<ServerFeaturesRes, ElectrumError> {
        let hash_str = value.genesis_hash.to_hex_string(Case::Lower);
        let blockhash = hash_str
            .parse::<bdk_wallet::bitcoin::BlockHash>()
            .map_err(|err| ElectrumError::InvalidResponse {
                error_message: format!(
                    "invalid genesis hash returned by server: {hash_str} ({err})"
                ),
            })?;

        Ok(ServerFeaturesRes {
            server_version: value.server_version,
            genesis_hash: Arc::new(BlockHash(blockhash)),
            protocol_min: value.protocol_min,
            protocol_max: value.protocol_max,
            hash_function: value.hash_function,
            pruning: value.pruning,
        })
    }
}

/// Notification of a new block header.
#[derive(uniffi::Record)]
pub struct HeaderNotification {
    /// New block height.
    pub height: u64,
    /// Newly added header.
    pub header: Header,
}

impl From<BdkHeaderNotification> for HeaderNotification {
    fn from(value: BdkHeaderNotification) -> HeaderNotification {
        HeaderNotification {
            height: value.height as u64,
            header: value.header.into(),
        }
    }
}