• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

bitcoindevkit / bdk / 5582722505

pending completion
5582722505

Pull #1002

github

web-flow
Merge 98a52d0cb into 81c761339
Pull Request #1002: Implement linked-list `LocalChain` and add rpc-chain module/example

945 of 945 new or added lines in 10 files covered. (100.0%)

8019 of 10332 relevant lines covered (77.61%)

5036.23 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/crates/esplora/src/blocking_ext.rs
1
use std::thread::JoinHandle;
2

3
use bdk_chain::bitcoin::{OutPoint, Txid};
4
use bdk_chain::collections::btree_map;
5
use bdk_chain::collections::BTreeMap;
6
use bdk_chain::{
7
    bitcoin::{BlockHash, Script},
8
    local_chain::CheckPoint,
9
};
10
use bdk_chain::{BlockId, ConfirmationTimeAnchor, TxGraph};
11
use esplora_client::{Error, TxStatus};
12

13
use crate::{anchor_from_status, ASSUME_FINAL_DEPTH};
14

15
/// Trait to extend the functionality of [`esplora_client::BlockingClient`].
16
///
17
/// Refer to [crate-level documentation] for more.
18
///
19
/// [crate-level documentation]: crate
20
pub trait EsploraExt {
21
    /// Prepare an [`LocalChain`] update with blocks fetched from Esplora.
22
    ///
23
    /// * `prev_tip` is the previous tip of [`LocalChain::tip`].
24
    /// * `get_heights` is the block heights that we are interested in fetching from Esplora.
25
    ///
26
    /// The result of this method can be applied to [`LocalChain::update`].
27
    ///
28
    /// [`LocalChain`]: bdk_chain::local_chain::LocalChain
29
    /// [`LocalChain::tip`]: bdk_chain::local_chain::LocalChain::tip
30
    /// [`LocalChain::update`]: bdk_chain::local_chain::LocalChain::update
31
    #[allow(clippy::result_large_err)]
32
    fn update_local_chain(
33
        &self,
34
        prev_tip: Option<CheckPoint>,
35
        get_heights: impl IntoIterator<Item = u32>,
36
    ) -> Result<CheckPoint, Error>;
37

38
    /// Scan Esplora for the data specified and return a [`TxGraph`] and a map of last active
39
    /// indices.
40
    ///
41
    /// * `keychain_spks`: keychains that we want to scan transactions for
42
    /// * `txids`: transactions for which we want updated [`ConfirmationTimeAnchor`]s
43
    /// * `outpoints`: transactions associated with these outpoints (residing, spending) that we
44
    ///     want to include in the update
45
    ///
46
    /// The scan for each keychain stops after a gap of `stop_gap` script pubkeys with no associated
47
    /// transactions. `parallel_requests` specifies the max number of HTTP requests to make in
48
    /// parallel.
49
    #[allow(clippy::result_large_err)]
50
    fn update_tx_graph<K: Ord + Clone>(
51
        &self,
52
        keychain_spks: BTreeMap<K, impl IntoIterator<Item = (u32, Script)>>,
53
        txids: impl IntoIterator<Item = Txid>,
54
        outpoints: impl IntoIterator<Item = OutPoint>,
55
        stop_gap: usize,
56
        parallel_requests: usize,
57
    ) -> Result<(TxGraph<ConfirmationTimeAnchor>, BTreeMap<K, u32>), Error>;
58

59
    /// Convenience method to call [`update_tx_graph`] without requiring a keychain.
60
    ///
61
    /// [`update_tx_graph`]: EsploraExt::update_tx_graph
62
    #[allow(clippy::result_large_err)]
63
    fn update_tx_graph_without_keychain(
×
64
        &self,
×
65
        misc_spks: impl IntoIterator<Item = Script>,
×
66
        txids: impl IntoIterator<Item = Txid>,
×
67
        outpoints: impl IntoIterator<Item = OutPoint>,
×
68
        parallel_requests: usize,
×
69
    ) -> Result<TxGraph<ConfirmationTimeAnchor>, Error> {
×
70
        self.update_tx_graph(
×
71
            [(
×
72
                (),
×
73
                misc_spks
×
74
                    .into_iter()
×
75
                    .enumerate()
×
76
                    .map(|(i, spk)| (i as u32, spk)),
×
77
            )]
×
78
            .into(),
×
79
            txids,
×
80
            outpoints,
×
81
            usize::MAX,
×
82
            parallel_requests,
×
83
        )
×
84
        .map(|(g, _)| g)
×
85
    }
×
86
}
87

88
impl EsploraExt for esplora_client::BlockingClient {
89
    fn update_local_chain(
×
90
        &self,
×
91
        prev_tip: Option<CheckPoint>,
×
92
        get_heights: impl IntoIterator<Item = u32>,
×
93
    ) -> Result<CheckPoint, Error> {
×
94
        let new_tip_height = self.get_height()?;
×
95

96
        // If esplora returns a tip height that is lower than our previous tip, then checkpoints do
97
        // not need updating. We just return the previous tip and use that as the point of
98
        // agreement.
99
        if let Some(prev_tip) = prev_tip.as_ref() {
×
100
            if new_tip_height < prev_tip.height() {
×
101
                return Ok(prev_tip.clone());
×
102
            }
×
103
        }
×
104

105
        // Fetch new block IDs that are to be included in the update. This includes:
106
        // 1. Atomically fetched most-recent blocks so we have a consistent view even during reorgs.
107
        // 2. Heights the caller is interested in (as specified in `get_heights`).
108
        let mut new_blocks = {
×
109
            let heights = (0..=new_tip_height).rev();
×
110
            let hashes = self
×
111
                .get_blocks(Some(new_tip_height))?
×
112
                .into_iter()
×
113
                .map(|b| b.id);
×
114

×
115
            let mut new_blocks = heights.zip(hashes).collect::<BTreeMap<u32, BlockHash>>();
×
116

117
            for height in get_heights {
×
118
                // do not fetch blocks higher than known tip
119
                if height > new_tip_height {
×
120
                    continue;
×
121
                }
×
122
                if let btree_map::Entry::Vacant(entry) = new_blocks.entry(height) {
×
123
                    let hash = self.get_block_hash(height)?;
×
124
                    entry.insert(hash);
×
125
                }
×
126
            }
127

128
            new_blocks
×
129
        };
130

131
        // Determine the checkpoint to start building our update tip from.
132
        let first_cp = match prev_tip {
×
133
            Some(old_tip) => {
×
134
                let old_tip_height = old_tip.height();
×
135
                let mut earliest_agreement_cp = Option::<CheckPoint>::None;
×
136

137
                for old_cp in old_tip.iter() {
×
138
                    let old_block = old_cp.block_id();
×
139

140
                    let new_hash = match new_blocks.entry(old_block.height) {
×
141
                        btree_map::Entry::Vacant(entry) => *entry.insert(
×
142
                            if old_tip_height - old_block.height >= ASSUME_FINAL_DEPTH {
×
143
                                old_block.hash
×
144
                            } else {
145
                                self.get_block_hash(old_block.height)?
×
146
                            },
147
                        ),
148
                        btree_map::Entry::Occupied(entry) => *entry.get(),
×
149
                    };
150

151
                    // Since we may introduce blocks below the point of agreement, we cannot break
152
                    // here unconditionally. We only break if we guarantee there are no new heights
153
                    // below our current.
154
                    if old_block.hash == new_hash {
×
155
                        earliest_agreement_cp = Some(old_cp);
×
156

×
157
                        let first_new_height = *new_blocks
×
158
                            .keys()
×
159
                            .next()
×
160
                            .expect("must have atleast one new block");
×
161
                        if first_new_height <= old_block.height {
×
162
                            break;
×
163
                        }
×
164
                    }
×
165
                }
166

167
                earliest_agreement_cp
×
168
            }
169
            None => None,
×
170
        }
171
        .unwrap_or_else(|| {
×
172
            let (&height, &hash) = new_blocks
×
173
                .iter()
×
174
                .next()
×
175
                .expect("must have atleast one new block");
×
176
            CheckPoint::new(BlockId { height, hash })
×
177
        });
×
178

×
179
        let new_tip = new_blocks
×
180
            .split_off(&(first_cp.height() + 1))
×
181
            .into_iter()
×
182
            .map(|(height, hash)| BlockId { height, hash })
×
183
            .fold(first_cp, |prev_cp, block| {
×
184
                prev_cp.push(block).expect("must extend checkpoint")
×
185
            });
×
186

×
187
        Ok(new_tip)
×
188
    }
×
189

190
    fn update_tx_graph<K: Ord + Clone>(
×
191
        &self,
×
192
        keychain_spks: BTreeMap<K, impl IntoIterator<Item = (u32, Script)>>,
×
193
        txids: impl IntoIterator<Item = Txid>,
×
194
        outpoints: impl IntoIterator<Item = OutPoint>,
×
195
        stop_gap: usize,
×
196
        parallel_requests: usize,
×
197
    ) -> Result<(TxGraph<ConfirmationTimeAnchor>, BTreeMap<K, u32>), Error> {
×
198
        type TxsOfSpkIndex = (u32, Vec<esplora_client::Tx>);
×
199
        let parallel_requests = Ord::max(parallel_requests, 1);
×
200
        let mut graph = TxGraph::<ConfirmationTimeAnchor>::default();
×
201
        let mut last_active_indexes = BTreeMap::<K, u32>::new();
×
202

203
        for (keychain, spks) in keychain_spks {
×
204
            let mut spks = spks.into_iter();
×
205
            let mut last_index = Option::<u32>::None;
×
206
            let mut last_active_index = Option::<u32>::None;
×
207

208
            loop {
×
209
                let handles = spks
×
210
                    .by_ref()
×
211
                    .take(parallel_requests)
×
212
                    .map(|(spk_index, spk)| {
×
213
                        std::thread::spawn({
×
214
                            let client = self.clone();
×
215
                            move || -> Result<TxsOfSpkIndex, Error> {
×
216
                                let mut last_seen = None;
×
217
                                let mut spk_txs = Vec::new();
×
218
                                loop {
219
                                    let txs = client.scripthash_txs(&spk, last_seen)?;
×
220
                                    let tx_count = txs.len();
×
221
                                    last_seen = txs.last().map(|tx| tx.txid);
×
222
                                    spk_txs.extend(txs);
×
223
                                    if tx_count < 25 {
×
224
                                        break Ok((spk_index, spk_txs));
×
225
                                    }
×
226
                                }
227
                            }
×
228
                        })
×
229
                    })
×
230
                    .collect::<Vec<JoinHandle<Result<TxsOfSpkIndex, Error>>>>();
×
231

×
232
                if handles.is_empty() {
×
233
                    break;
×
234
                }
×
235

236
                for handle in handles {
×
237
                    let (index, txs) = handle.join().expect("thread must not panic")?;
×
238
                    last_index = Some(index);
×
239
                    if !txs.is_empty() {
×
240
                        last_active_index = Some(index);
×
241
                    }
×
242
                    for tx in txs {
×
243
                        let _ = graph.insert_tx(tx.to_tx());
×
244
                        if let Some(anchor) = anchor_from_status(&tx.status) {
×
245
                            let _ = graph.insert_anchor(tx.txid, anchor);
×
246
                        }
×
247
                    }
248
                }
249

250
                if last_index > last_active_index.map(|i| i + stop_gap as u32) {
×
251
                    break;
×
252
                }
×
253
            }
254

255
            if let Some(last_active_index) = last_active_index {
×
256
                last_active_indexes.insert(keychain, last_active_index);
×
257
            }
×
258
        }
259

260
        let mut txids = txids.into_iter();
×
261
        loop {
×
262
            let handles = txids
×
263
                .by_ref()
×
264
                .take(parallel_requests)
×
265
                .filter(|&txid| graph.get_tx(txid).is_none())
×
266
                .map(|txid| {
×
267
                    std::thread::spawn({
×
268
                        let client = self.clone();
×
269
                        move || client.get_tx_status(&txid).map(|s| (txid, s))
×
270
                    })
×
271
                })
×
272
                .collect::<Vec<JoinHandle<Result<(Txid, TxStatus), Error>>>>();
×
273

×
274
            if handles.is_empty() {
×
275
                break;
×
276
            }
×
277

278
            for handle in handles {
×
279
                let (txid, status) = handle.join().expect("thread must not panic")?;
×
280
                if let Some(anchor) = anchor_from_status(&status) {
×
281
                    let _ = graph.insert_anchor(txid, anchor);
×
282
                }
×
283
            }
284
        }
285

286
        for op in outpoints.into_iter() {
×
287
            if graph.get_tx(op.txid).is_none() {
×
288
                if let Some(tx) = self.get_tx(&op.txid)? {
×
289
                    let _ = graph.insert_tx(tx);
×
290
                }
×
291
                let status = self.get_tx_status(&op.txid)?;
×
292
                if let Some(anchor) = anchor_from_status(&status) {
×
293
                    let _ = graph.insert_anchor(op.txid, anchor);
×
294
                }
×
295
            }
×
296

297
            if let Some(op_status) = self.get_output_status(&op.txid, op.vout as _)? {
×
298
                if let Some(txid) = op_status.txid {
×
299
                    if graph.get_tx(txid).is_none() {
×
300
                        if let Some(tx) = self.get_tx(&txid)? {
×
301
                            let _ = graph.insert_tx(tx);
×
302
                        }
×
303
                        let status = self.get_tx_status(&txid)?;
×
304
                        if let Some(anchor) = anchor_from_status(&status) {
×
305
                            let _ = graph.insert_anchor(txid, anchor);
×
306
                        }
×
307
                    }
×
308
                }
×
309
            }
×
310
        }
311

312
        Ok((graph, last_active_indexes))
×
313
    }
×
314
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc