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

bitcoindevkit / bdk / 5640344360

pending completion
5640344360

Pull #1034

github

web-flow
Merge 56d7c522a into f4d2a7666
Pull Request #1034: Implement linked-list `LocalChain` and update chain-src crates/examples

709 of 709 new or added lines in 7 files covered. (100.0%)

7427 of 9460 relevant lines covered (78.51%)

5389.92 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::{local_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::apply_update`].
27
    ///
28
    /// [`LocalChain`]: bdk_chain::local_chain::LocalChain
29
    /// [`LocalChain::tip`]: bdk_chain::local_chain::LocalChain::tip
30
    /// [`LocalChain::apply_update`]: bdk_chain::local_chain::LocalChain::apply_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<local_chain::Update, 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<local_chain::Update, 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(local_chain::Update {
×
102
                    tip: prev_tip.clone(),
×
103
                    introduce_older_blocks: true,
×
104
                });
×
105
            }
×
106
        }
×
107

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

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

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

131
            new_blocks
×
132
        };
133

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

140
                for old_cp in old_tip.iter() {
×
141
                    let old_block = old_cp.block_id();
×
142

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

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

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

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

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

×
190
        Ok(local_chain::Update {
×
191
            tip: new_tip,
×
192
            introduce_older_blocks: true,
×
193
        })
×
194
    }
×
195

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

209
        for (keychain, spks) in keychain_spks {
×
210
            let mut spks = spks.into_iter();
×
211
            let mut last_index = Option::<u32>::None;
×
212
            let mut last_active_index = Option::<u32>::None;
×
213

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

×
238
                if handles.is_empty() {
×
239
                    break;
×
240
                }
×
241

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

256
                if last_index > last_active_index.map(|i| i + stop_gap as u32) {
×
257
                    break;
×
258
                }
×
259
            }
260

261
            if let Some(last_active_index) = last_active_index {
×
262
                last_active_indexes.insert(keychain, last_active_index);
×
263
            }
×
264
        }
265

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

×
280
            if handles.is_empty() {
×
281
                break;
×
282
            }
×
283

284
            for handle in handles {
×
285
                let (txid, status) = handle.join().expect("thread must not panic")?;
×
286
                if let Some(anchor) = anchor_from_status(&status) {
×
287
                    let _ = graph.insert_anchor(txid, anchor);
×
288
                }
×
289
            }
290
        }
291

292
        for op in outpoints.into_iter() {
×
293
            if graph.get_tx(op.txid).is_none() {
×
294
                if let Some(tx) = self.get_tx(&op.txid)? {
×
295
                    let _ = graph.insert_tx(tx);
×
296
                }
×
297
                let status = self.get_tx_status(&op.txid)?;
×
298
                if let Some(anchor) = anchor_from_status(&status) {
×
299
                    let _ = graph.insert_anchor(op.txid, anchor);
×
300
                }
×
301
            }
×
302

303
            if let Some(op_status) = self.get_output_status(&op.txid, op.vout as _)? {
×
304
                if let Some(txid) = op_status.txid {
×
305
                    if graph.get_tx(txid).is_none() {
×
306
                        if let Some(tx) = self.get_tx(&txid)? {
×
307
                            let _ = graph.insert_tx(tx);
×
308
                        }
×
309
                        let status = self.get_tx_status(&txid)?;
×
310
                        if let Some(anchor) = anchor_from_status(&status) {
×
311
                            let _ = graph.insert_anchor(txid, anchor);
×
312
                        }
×
313
                    }
×
314
                }
×
315
            }
×
316
        }
317

318
        Ok((graph, last_active_indexes))
×
319
    }
×
320
}
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