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

bitcoindevkit / bdk / 9737955023

01 Jul 2024 04:01AM UTC coverage: 83.182% (+0.2%) from 83.029%
9737955023

Pull #1478

github

web-flow
Merge d05135804 into 22368ab7b
Pull Request #1478: Make `bdk_esplora` more modular

358 of 422 new or added lines in 2 files covered. (84.83%)

213 existing lines in 7 files now uncovered.

11148 of 13402 relevant lines covered (83.18%)

16721.16 hits per line

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

90.24
/crates/esplora/src/blocking_ext.rs
1
use std::collections::BTreeSet;
2
use std::thread::JoinHandle;
3

4
use bdk_chain::collections::BTreeMap;
5
use bdk_chain::spk_client::{FullScanRequest, FullScanResult, SyncRequest, SyncResult};
6
use bdk_chain::{
7
    bitcoin::{Amount, BlockHash, OutPoint, ScriptBuf, TxOut, Txid},
8
    local_chain::CheckPoint,
9
    BlockId, ConfirmationTimeHeightAnchor, TxGraph,
10
};
11
use bdk_chain::{Anchor, Indexed};
12
use esplora_client::{OutputStatus, Tx, TxStatus};
13

14
use crate::anchor_from_status;
15

16
/// [`esplora_client::Error`] wrapped in a [`Box`].
17
pub type Error = Box<esplora_client::Error>;
18

19
/// Trait to extend the functionality of [`esplora_client::BlockingClient`].
20
///
21
/// Refer to [crate-level documentation](crate) for more.
22
pub trait EsploraExt {
23
    /// Scan keychain scripts for transactions against Esplora, returning an update that can be
24
    /// applied to the receiving structures.
25
    ///
26
    /// `request` provides the data required to perform a script-pubkey-based full scan
27
    /// (see [`FullScanRequest`]). The full scan for each keychain (`K`) stops after a gap of
28
    /// `stop_gap` script pubkeys with no associated transactions. `parallel_requests` specifies
29
    /// the maximum number of HTTP requests to make in parallel.
30
    ///
31
    /// Refer to [crate-level docs](crate) for more.
32
    fn full_scan<K: Ord + Clone>(
33
        &self,
34
        request: FullScanRequest<K>,
35
        stop_gap: usize,
36
        parallel_requests: usize,
37
    ) -> Result<FullScanResult<K>, Error>;
38

39
    /// Sync a set of scripts, txids, and/or outpoints against Esplora.
40
    ///
41
    /// `request` provides the data required to perform a script-pubkey-based sync (see
42
    /// [`SyncRequest`]). `parallel_requests` specifies the maximum number of HTTP requests to make
43
    /// in parallel.
44
    ///
45
    /// Refer to [crate-level docs](crate) for more.
46
    fn sync(&self, request: SyncRequest, parallel_requests: usize) -> Result<SyncResult, Error>;
47

48
    /// Populate the `tx_graph` with transactions and associated [`ConfirmationTimeHeightAnchor`]s
49
    /// by scanning `keychain_spks` against Esplora.
50
    ///
51
    /// `keychain_spks` is an *unbounded* indexed-[`ScriptBuf`] iterator that represents scripts
52
    /// derived from a keychain. The scanning logic stops after a `stop_gap` number of consecutive
53
    /// scripts with no transaction history is reached. `parallel_requests` specifies the maximum
54
    /// number of HTTP requests to make in parallel.
55
    ///
56
    /// The last active keychain index (if any) is returned. This is the keychain index of the last
57
    /// script that contains a non-empty transaction history.
58
    ///
59
    /// Refer to [crate-level docs](crate) for more.
60
    fn populate_using_keychain_spks<I: Iterator<Item = Indexed<ScriptBuf>>>(
61
        &self,
62
        tx_graph: &mut TxGraph<ConfirmationTimeHeightAnchor>,
63
        keychain_spks: I,
64
        stop_gap: usize,
65
        parallel_requests: usize,
66
    ) -> Result<Option<u32>, Error>;
67

68
    /// Populate the `tx_graph` with transactions and associated [`ConfirmationTimeHeightAnchor`]s
69
    /// by scanning `spks` against Esplora.
70
    ///
71
    /// Unlike with [`EsploraExt::populate_using_keychain_spks`], `spks` must be *bounded* as all
72
    /// contained scripts will be scanned. `parallel_requests` specifies the maximum number of HTTP
73
    /// requests to make in parallel.
74
    ///
75
    /// Refer to [crate-level docs](crate) for more.
76
    fn populate_using_spks<I: IntoIterator<Item = ScriptBuf>>(
77
        &self,
78
        tx_graph: &mut TxGraph<ConfirmationTimeHeightAnchor>,
79
        spks: I,
80
        parallel_requests: usize,
81
    ) -> Result<(), Error>
82
    where
83
        I::IntoIter: ExactSizeIterator;
84

85
    /// Populate the `tx_graph` with transactions and associated [`ConfirmationTimeHeightAnchor`]s
86
    /// by scanning `txids` against Esplora.
87
    ///
88
    /// `parallel_requests` specifies the maximum number of HTTP requests to make in parallel.
89
    ///
90
    /// Refer to [crate-level docs](crate) for more.
91
    fn populate_using_txids<I: IntoIterator<Item = Txid>>(
92
        &self,
93
        tx_graph: &mut TxGraph<ConfirmationTimeHeightAnchor>,
94
        txids: I,
95
        parallel_requests: usize,
96
    ) -> Result<(), Error>
97
    where
98
        I::IntoIter: ExactSizeIterator;
99

100
    /// Populate the `tx_graph` with residing and spending transactions and
101
    /// [`ConfirmationTimeHeightAnchor`]s by scanning `outpoints` against Esplora.
102
    ///
103
    /// `parallel_requests` specifies the maximum number of HTTP requests to make in parallel.
104
    ///
105
    /// Refer to [crate-level docs](crate) for more.
106
    fn populate_using_outpoints<I: IntoIterator<Item = OutPoint>>(
107
        &self,
108
        tx_graph: &mut TxGraph<ConfirmationTimeHeightAnchor>,
109
        outpoints: I,
110
        parallel_requests: usize,
111
    ) -> Result<(), Error>
112
    where
113
        I::IntoIter: ExactSizeIterator;
114
}
115

116
impl EsploraExt for esplora_client::BlockingClient {
117
    fn full_scan<K: Ord + Clone>(
4✔
118
        &self,
4✔
119
        request: FullScanRequest<K>,
4✔
120
        stop_gap: usize,
4✔
121
        parallel_requests: usize,
4✔
122
    ) -> Result<FullScanResult<K>, Error> {
4✔
123
        let latest_blocks = fetch_latest_blocks(self)?;
4✔
124
        let mut graph_update = TxGraph::default();
4✔
125
        let mut last_active_indices = BTreeMap::<K, u32>::new();
4✔
126
        for (keychain, keychain_spks) in request.spks_by_keychain {
8✔
127
            if let Some(last_active_index) = self.populate_using_keychain_spks(
4✔
128
                &mut graph_update,
4✔
129
                keychain_spks,
4✔
130
                stop_gap,
4✔
131
                parallel_requests,
4✔
132
            )? {
4✔
133
                last_active_indices.insert(keychain, last_active_index);
3✔
134
            };
3✔
135
        }
136
        let chain_update = chain_update(
4✔
137
            self,
4✔
138
            &latest_blocks,
4✔
139
            &request.chain_tip,
4✔
140
            graph_update.all_anchors(),
4✔
141
        )?;
4✔
142
        Ok(FullScanResult {
4✔
143
            chain_update,
4✔
144
            graph_update,
4✔
145
            last_active_indices,
4✔
146
        })
4✔
147
    }
4✔
148

149
    fn sync(&self, request: SyncRequest, parallel_requests: usize) -> Result<SyncResult, Error> {
2✔
150
        let latest_blocks = fetch_latest_blocks(self)?;
2✔
151
        let mut graph_update = TxGraph::default();
2✔
152
        self.populate_using_spks(&mut graph_update, request.spks, parallel_requests)?;
2✔
153
        self.populate_using_txids(&mut graph_update, request.txids, parallel_requests)?;
2✔
154
        self.populate_using_outpoints(&mut graph_update, request.outpoints, parallel_requests)?;
2✔
155
        let chain_update = chain_update(
2✔
156
            self,
2✔
157
            &latest_blocks,
2✔
158
            &request.chain_tip,
2✔
159
            graph_update.all_anchors(),
2✔
160
        )?;
2✔
161
        Ok(SyncResult {
2✔
162
            chain_update,
2✔
163
            graph_update,
2✔
164
        })
2✔
165
    }
2✔
166

167
    fn populate_using_keychain_spks<S: Iterator<Item = Indexed<ScriptBuf>>>(
6✔
168
        &self,
6✔
169
        tx_graph: &mut TxGraph<ConfirmationTimeHeightAnchor>,
6✔
170
        mut keychain_spks: S,
6✔
171
        stop_gap: usize,
6✔
172
        parallel_requests: usize,
6✔
173
    ) -> Result<Option<u32>, Error> {
6✔
174
        type TxsOfSpkIndex = (u32, Vec<esplora_client::Tx>);
6✔
175

6✔
176
        let mut last_index = Option::<u32>::None;
6✔
177
        let mut last_active_index = Option::<u32>::None;
6✔
178

179
        loop {
37✔
180
            let handles = keychain_spks
37✔
181
                .by_ref()
37✔
182
                .take(parallel_requests)
37✔
183
                .map(|(spk_index, spk)| {
37✔
184
                    std::thread::spawn({
34✔
185
                        let client = self.clone();
34✔
186
                        move || -> Result<TxsOfSpkIndex, Error> {
34✔
187
                            let mut last_seen = None;
34✔
188
                            let mut spk_txs = Vec::new();
34✔
189
                            loop {
190
                                let txs = client.scripthash_txs(&spk, last_seen)?;
34✔
191
                                let tx_count = txs.len();
34✔
192
                                last_seen = txs.last().map(|tx| tx.txid);
34✔
193
                                spk_txs.extend(txs);
34✔
194
                                if tx_count < 25 {
34✔
195
                                    break Ok((spk_index, spk_txs));
34✔
NEW
UNCOV
196
                                }
×
197
                            }
198
                        }
34✔
199
                    })
34✔
200
                })
37✔
201
                .collect::<Vec<JoinHandle<Result<TxsOfSpkIndex, Error>>>>();
37✔
202

37✔
203
            if handles.is_empty() {
37✔
204
                break;
3✔
205
            }
34✔
206

207
            for handle in handles {
68✔
208
                let (index, txs) = handle.join().expect("thread must not panic")?;
34✔
209
                last_index = Some(index);
34✔
210
                if !txs.is_empty() {
34✔
211
                    last_active_index = Some(index);
8✔
212
                }
28✔
213
                for tx in txs {
42✔
214
                    let _ = tx_graph.insert_tx(tx.to_tx());
8✔
215
                    if let Some(anchor) = anchor_from_status(&tx.status) {
8✔
216
                        let _ = tx_graph.insert_anchor(tx.txid, anchor);
8✔
217
                    }
8✔
218

219
                    let previous_outputs = tx.vin.iter().filter_map(|vin| {
8✔
220
                        let prevout = vin.prevout.as_ref()?;
8✔
221
                        Some((
8✔
222
                            OutPoint {
8✔
223
                                txid: vin.txid,
8✔
224
                                vout: vin.vout,
8✔
225
                            },
8✔
226
                            TxOut {
8✔
227
                                script_pubkey: prevout.scriptpubkey.clone(),
8✔
228
                                value: Amount::from_sat(prevout.value),
8✔
229
                            },
8✔
230
                        ))
8✔
231
                    });
8✔
232

233
                    for (outpoint, txout) in previous_outputs {
16✔
234
                        let _ = tx_graph.insert_txout(outpoint, txout);
8✔
235
                    }
8✔
236
                }
237
            }
238

239
            let last_index = last_index.expect("Must be set since handles wasn't empty.");
34✔
240
            let gap_limit_reached = if let Some(i) = last_active_index {
34✔
241
                last_index >= i.saturating_add(stop_gap as u32)
22✔
242
            } else {
243
                last_index + 1 >= stop_gap as u32
12✔
244
            };
245
            if gap_limit_reached {
34✔
246
                break;
3✔
247
            }
31✔
248
        }
249

250
        Ok(last_active_index)
6✔
251
    }
6✔
252

253
    fn populate_using_spks<I: IntoIterator<Item = ScriptBuf>>(
2✔
254
        &self,
2✔
255
        tx_graph: &mut TxGraph<ConfirmationTimeHeightAnchor>,
2✔
256
        spks: I,
2✔
257
        parallel_requests: usize,
2✔
258
    ) -> Result<(), Error>
2✔
259
    where
2✔
260
        I::IntoIter: ExactSizeIterator,
2✔
261
    {
2✔
262
        self.populate_using_keychain_spks(
2✔
263
            tx_graph,
2✔
264
            spks.into_iter().enumerate().map(|(i, spk)| (i as u32, spk)),
4✔
265
            usize::MAX,
2✔
266
            parallel_requests,
2✔
267
        )
2✔
268
        .map(|_| ())
2✔
269
    }
2✔
270

271
    fn populate_using_txids<I: IntoIterator<Item = Txid>>(
6✔
272
        &self,
6✔
273
        tx_graph: &mut TxGraph<ConfirmationTimeHeightAnchor>,
6✔
274
        txids: I,
6✔
275
        parallel_requests: usize,
6✔
276
    ) -> Result<(), Error>
6✔
277
    where
6✔
278
        I::IntoIter: ExactSizeIterator,
6✔
279
    {
6✔
280
        enum EsploraResp {
6✔
281
            TxStatus(TxStatus),
6✔
282
            Tx(Option<Tx>),
6✔
283
        }
6✔
284

6✔
285
        let mut txids = txids.into_iter();
6✔
286
        loop {
6✔
287
            let handles = txids
6✔
288
                .by_ref()
6✔
289
                .take(parallel_requests)
6✔
290
                .map(|txid| {
6✔
NEW
291
                    let client = self.clone();
×
NEW
292
                    let tx_already_exists = tx_graph.get_tx(txid).is_some();
×
NEW
293
                    std::thread::spawn(move || {
×
NEW
294
                        if tx_already_exists {
×
NEW
UNCOV
295
                            client
×
NEW
UNCOV
296
                                .get_tx_status(&txid)
×
NEW
UNCOV
297
                                .map_err(Box::new)
×
NEW
298
                                .map(|s| (txid, EsploraResp::TxStatus(s)))
×
299
                        } else {
NEW
300
                            client
×
NEW
301
                                .get_tx_info(&txid)
×
NEW
302
                                .map_err(Box::new)
×
NEW
303
                                .map(|t| (txid, EsploraResp::Tx(t)))
×
304
                        }
NEW
305
                    })
×
306
                })
6✔
307
                .collect::<Vec<JoinHandle<Result<(Txid, EsploraResp), Error>>>>();
6✔
308

6✔
309
            if handles.is_empty() {
6✔
310
                break;
6✔
NEW
UNCOV
311
            }
×
312

NEW
313
            for handle in handles {
×
NEW
314
                let (txid, resp) = handle.join().expect("thread must not panic")?;
×
NEW
315
                match resp {
×
NEW
316
                    EsploraResp::TxStatus(status) => {
×
NEW
317
                        if let Some(anchor) = anchor_from_status(&status) {
×
NEW
318
                            let _ = tx_graph.insert_anchor(txid, anchor);
×
NEW
319
                        }
×
320
                    }
NEW
UNCOV
321
                    EsploraResp::Tx(Some(tx_info)) => {
×
NEW
322
                        let _ = tx_graph.insert_tx(tx_info.to_tx());
×
NEW
UNCOV
323
                        if let Some(anchor) = anchor_from_status(&tx_info.status) {
×
NEW
UNCOV
324
                            let _ = tx_graph.insert_anchor(txid, anchor);
×
NEW
325
                        }
×
326
                    }
NEW
327
                    _ => continue,
×
328
                }
329
            }
330
        }
331
        Ok(())
6✔
332
    }
6✔
333

334
    fn populate_using_outpoints<I: IntoIterator<Item = OutPoint>>(
2✔
335
        &self,
2✔
336
        tx_graph: &mut TxGraph<ConfirmationTimeHeightAnchor>,
2✔
337
        outpoints: I,
2✔
338
        parallel_requests: usize,
2✔
339
    ) -> Result<(), Error>
2✔
340
    where
2✔
341
        I::IntoIter: ExactSizeIterator,
2✔
342
    {
2✔
343
        let outpoints = outpoints.into_iter().collect::<Vec<_>>();
2✔
344

2✔
345
        // make sure txs exists in graph and tx statuses are updated
2✔
346
        // TODO: We should maintain a tx cache (like we do with Electrum).
2✔
347
        self.populate_using_txids(
2✔
348
            tx_graph,
2✔
349
            outpoints.iter().map(|op| op.txid),
2✔
350
            parallel_requests,
2✔
351
        )?;
2✔
352

353
        // get outpoint spend-statuses
354
        let mut outpoints = outpoints.into_iter();
2✔
355
        let mut missing_txs = Vec::<Txid>::with_capacity(outpoints.len());
2✔
356
        loop {
2✔
357
            let handles = outpoints
2✔
358
                .by_ref()
2✔
359
                .take(parallel_requests)
2✔
360
                .map(|op| {
2✔
NEW
361
                    let client = self.clone();
×
NEW
362
                    std::thread::spawn(move || {
×
NEW
363
                        client
×
NEW
364
                            .get_output_status(&op.txid, op.vout as _)
×
NEW
365
                            .map_err(Box::new)
×
NEW
366
                    })
×
367
                })
2✔
368
                .collect::<Vec<JoinHandle<Result<Option<OutputStatus>, Error>>>>();
2✔
369

2✔
370
            if handles.is_empty() {
2✔
371
                break;
2✔
NEW
UNCOV
372
            }
×
373

NEW
UNCOV
374
            for handle in handles {
×
NEW
UNCOV
375
                if let Some(op_status) = handle.join().expect("thread must not panic")? {
×
NEW
UNCOV
376
                    let spend_txid = match op_status.txid {
×
NEW
377
                        Some(txid) => txid,
×
NEW
UNCOV
378
                        None => continue,
×
379
                    };
NEW
380
                    if tx_graph.get_tx(spend_txid).is_none() {
×
NEW
381
                        missing_txs.push(spend_txid);
×
NEW
382
                    }
×
NEW
383
                    if let Some(spend_status) = op_status.status {
×
NEW
384
                        if let Some(spend_anchor) = anchor_from_status(&spend_status) {
×
NEW
385
                            let _ = tx_graph.insert_anchor(spend_txid, spend_anchor);
×
NEW
386
                        }
×
NEW
387
                    }
×
NEW
388
                }
×
389
            }
390
        }
391

392
        self.populate_using_txids(tx_graph, missing_txs, parallel_requests)?;
2✔
393
        Ok(())
2✔
394
    }
2✔
395
}
396

397
/// Fetch latest blocks from Esplora in an atomic call.
398
///
399
/// We want to do this before fetching transactions and anchors as we cannot fetch latest blocks AND
400
/// transactions atomically, and the checkpoint tip is used to determine last-scanned block (for
401
/// block-based chain-sources). Therefore it's better to be conservative when setting the tip (use
402
/// an earlier tip rather than a later tip) otherwise the caller may accidentally skip blocks when
403
/// alternating between chain-sources.
404
fn fetch_latest_blocks(
28✔
405
    client: &esplora_client::BlockingClient,
28✔
406
) -> Result<BTreeMap<u32, BlockHash>, Error> {
28✔
407
    Ok(client
28✔
408
        .get_blocks(None)?
28✔
409
        .into_iter()
28✔
410
        .map(|b| (b.time.height, b.id))
280✔
411
        .collect())
28✔
412
}
28✔
413

414
/// Used instead of [`esplora_client::BlockingClient::get_block_hash`].
415
///
416
/// This first checks the previously fetched `latest_blocks` before fetching from Esplora again.
417
fn fetch_block(
66✔
418
    client: &esplora_client::BlockingClient,
66✔
419
    latest_blocks: &BTreeMap<u32, BlockHash>,
66✔
420
    height: u32,
66✔
421
) -> Result<Option<BlockHash>, Error> {
66✔
422
    if let Some(&hash) = latest_blocks.get(&height) {
66✔
423
        return Ok(Some(hash));
17✔
424
    }
49✔
425

49✔
426
    // We avoid fetching blocks higher than previously fetched `latest_blocks` as the local chain
49✔
427
    // tip is used to signal for the last-synced-up-to-height.
49✔
428
    let &tip_height = latest_blocks
49✔
429
        .keys()
49✔
430
        .last()
49✔
431
        .expect("must have atleast one entry");
49✔
432
    if height > tip_height {
49✔
433
        return Ok(None);
×
434
    }
49✔
435

49✔
436
    Ok(Some(client.get_block_hash(height)?))
49✔
437
}
66✔
438

439
/// Create the [`local_chain::Update`].
440
///
441
/// We want to have a corresponding checkpoint per anchor height. However, checkpoints fetched
442
/// should not surpass `latest_blocks`.
443
fn chain_update<A: Anchor>(
28✔
444
    client: &esplora_client::BlockingClient,
28✔
445
    latest_blocks: &BTreeMap<u32, BlockHash>,
28✔
446
    local_tip: &CheckPoint,
28✔
447
    anchors: &BTreeSet<(A, Txid)>,
28✔
448
) -> Result<CheckPoint, Error> {
28✔
449
    let mut point_of_agreement = None;
28✔
450
    let mut conflicts = vec![];
28✔
451
    for local_cp in local_tip.iter() {
37✔
452
        let remote_hash = match fetch_block(client, latest_blocks, local_cp.height())? {
37✔
453
            Some(hash) => hash,
37✔
UNCOV
454
            None => continue,
×
455
        };
456
        if remote_hash == local_cp.hash() {
37✔
457
            point_of_agreement = Some(local_cp.clone());
28✔
458
            break;
28✔
459
        } else {
9✔
460
            // it is not strictly necessary to include all the conflicted heights (we do need the
9✔
461
            // first one) but it seems prudent to make sure the updated chain's heights are a
9✔
462
            // superset of the existing chain after update.
9✔
463
            conflicts.push(BlockId {
9✔
464
                height: local_cp.height(),
9✔
465
                hash: remote_hash,
9✔
466
            });
9✔
467
        }
9✔
468
    }
469

470
    let mut tip = point_of_agreement.expect("remote esplora should have same genesis block");
28✔
471

28✔
472
    tip = tip
28✔
473
        .extend(conflicts.into_iter().rev())
28✔
474
        .expect("evicted are in order");
28✔
475

476
    for anchor in anchors {
67✔
477
        let height = anchor.0.anchor_block().height;
39✔
478
        if tip.get(height).is_none() {
39✔
479
            let hash = match fetch_block(client, latest_blocks, height)? {
29✔
480
                Some(hash) => hash,
29✔
UNCOV
481
                None => continue,
×
482
            };
483
            tip = tip.insert(BlockId { height, hash });
29✔
484
        }
10✔
485
    }
486

487
    // insert the most recent blocks at the tip to make sure we update the tip and make the update
488
    // robust.
489
    for (&height, &hash) in latest_blocks.iter() {
280✔
490
        tip = tip.insert(BlockId { height, hash });
280✔
491
    }
280✔
492

493
    Ok(tip)
28✔
494
}
28✔
495

496
#[cfg(test)]
497
mod test {
498
    use crate::blocking_ext::{chain_update, fetch_latest_blocks};
499
    use bdk_chain::bitcoin::hashes::Hash;
500
    use bdk_chain::bitcoin::Txid;
501
    use bdk_chain::local_chain::LocalChain;
502
    use bdk_chain::BlockId;
503
    use bdk_testenv::{anyhow, bitcoincore_rpc::RpcApi, TestEnv};
504
    use esplora_client::{BlockHash, Builder};
505
    use std::collections::{BTreeMap, BTreeSet};
506
    use std::time::Duration;
507

508
    macro_rules! h {
509
        ($index:literal) => {{
510
            bdk_chain::bitcoin::hashes::Hash::hash($index.as_bytes())
511
        }};
512
    }
513

514
    macro_rules! local_chain {
515
        [ $(($height:expr, $block_hash:expr)), * ] => {{
516
            #[allow(unused_mut)]
517
            bdk_chain::local_chain::LocalChain::from_blocks([$(($height, $block_hash).into()),*].into_iter().collect())
518
                .expect("chain must have genesis block")
519
        }};
520
    }
521

522
    /// Ensure that update does not remove heights (from original), and all anchor heights are included.
523
    #[test]
524
    pub fn test_finalize_chain_update() -> anyhow::Result<()> {
1✔
525
        struct TestCase<'a> {
1✔
526
            name: &'a str,
1✔
527
            /// Initial blockchain height to start the env with.
1✔
528
            initial_env_height: u32,
1✔
529
            /// Initial checkpoint heights to start with in the local chain.
1✔
530
            initial_cps: &'a [u32],
1✔
531
            /// The final blockchain height of the env.
1✔
532
            final_env_height: u32,
1✔
533
            /// The anchors to test with: `(height, txid)`. Only the height is provided as we can fetch
1✔
534
            /// the blockhash from the env.
1✔
535
            anchors: &'a [(u32, Txid)],
1✔
536
        }
1✔
537

1✔
538
        let test_cases = [
1✔
539
            TestCase {
1✔
540
                name: "chain_extends",
1✔
541
                initial_env_height: 60,
1✔
542
                initial_cps: &[59, 60],
1✔
543
                final_env_height: 90,
1✔
544
                anchors: &[],
1✔
545
            },
1✔
546
            TestCase {
1✔
547
                name: "introduce_older_heights",
1✔
548
                initial_env_height: 50,
1✔
549
                initial_cps: &[10, 15],
1✔
550
                final_env_height: 50,
1✔
551
                anchors: &[(11, h!("A")), (14, h!("B"))],
1✔
552
            },
1✔
553
            TestCase {
1✔
554
                name: "introduce_older_heights_after_chain_extends",
1✔
555
                initial_env_height: 50,
1✔
556
                initial_cps: &[10, 15],
1✔
557
                final_env_height: 100,
1✔
558
                anchors: &[(11, h!("A")), (14, h!("B"))],
1✔
559
            },
1✔
560
        ];
1✔
561

562
        for (i, t) in test_cases.into_iter().enumerate() {
3✔
563
            println!("[{}] running test case: {}", i, t.name);
3✔
564

565
            let env = TestEnv::new()?;
3✔
566
            let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
3✔
567
            let client = Builder::new(base_url.as_str()).build_blocking();
3✔
568

569
            // set env to `initial_env_height`
570
            if let Some(to_mine) = t
3✔
571
                .initial_env_height
3✔
572
                .checked_sub(env.make_checkpoint_tip().height())
3✔
573
            {
574
                env.mine_blocks(to_mine as _, None)?;
3✔
UNCOV
575
            }
×
576
            while client.get_height()? < t.initial_env_height {
1,293✔
577
                std::thread::sleep(Duration::from_millis(10));
1,290✔
578
            }
1,290✔
579

580
            // craft initial `local_chain`
581
            let local_chain = {
3✔
582
                let (mut chain, _) = LocalChain::from_genesis_hash(env.genesis_hash()?);
3✔
583
                // force `chain_update_blocking` to add all checkpoints in `t.initial_cps`
584
                let anchors = t
3✔
585
                    .initial_cps
3✔
586
                    .iter()
3✔
587
                    .map(|&height| -> anyhow::Result<_> {
6✔
588
                        Ok((
6✔
589
                            BlockId {
6✔
590
                                height,
6✔
591
                                hash: env.bitcoind.client.get_block_hash(height as _)?,
6✔
592
                            },
593
                            Txid::all_zeros(),
6✔
594
                        ))
595
                    })
6✔
596
                    .collect::<anyhow::Result<BTreeSet<_>>>()?;
3✔
597
                let update = chain_update(
3✔
598
                    &client,
3✔
599
                    &fetch_latest_blocks(&client)?,
3✔
600
                    &chain.tip(),
3✔
601
                    &anchors,
3✔
UNCOV
602
                )?;
×
603
                chain.apply_update(update)?;
3✔
604
                chain
3✔
605
            };
3✔
606
            println!("local chain height: {}", local_chain.tip().height());
3✔
607

608
            // extend env chain
609
            if let Some(to_mine) = t
3✔
610
                .final_env_height
3✔
611
                .checked_sub(env.make_checkpoint_tip().height())
3✔
612
            {
613
                env.mine_blocks(to_mine as _, None)?;
3✔
UNCOV
614
            }
×
615
            while client.get_height()? < t.final_env_height {
950✔
616
                std::thread::sleep(Duration::from_millis(10));
947✔
617
            }
947✔
618

619
            // craft update
620
            let update = {
3✔
621
                let anchors = t
3✔
622
                    .anchors
3✔
623
                    .iter()
3✔
624
                    .map(|&(height, txid)| -> anyhow::Result<_> {
4✔
625
                        Ok((
4✔
626
                            BlockId {
4✔
627
                                height,
4✔
628
                                hash: env.bitcoind.client.get_block_hash(height as _)?,
4✔
629
                            },
630
                            txid,
4✔
631
                        ))
632
                    })
4✔
633
                    .collect::<anyhow::Result<_>>()?;
3✔
634
                chain_update(
635
                    &client,
3✔
636
                    &fetch_latest_blocks(&client)?,
3✔
637
                    &local_chain.tip(),
3✔
638
                    &anchors,
3✔
UNCOV
639
                )?
×
640
            };
641

642
            // apply update
643
            let mut updated_local_chain = local_chain.clone();
3✔
644
            updated_local_chain.apply_update(update)?;
3✔
645
            println!(
3✔
646
                "updated local chain height: {}",
3✔
647
                updated_local_chain.tip().height()
3✔
648
            );
3✔
649

3✔
650
            assert!(
3✔
651
                {
3✔
652
                    let initial_heights = local_chain
3✔
653
                        .iter_checkpoints()
3✔
654
                        .map(|cp| cp.height())
37✔
655
                        .collect::<BTreeSet<_>>();
3✔
656
                    let updated_heights = updated_local_chain
3✔
657
                        .iter_checkpoints()
3✔
658
                        .map(|cp| cp.height())
61✔
659
                        .collect::<BTreeSet<_>>();
3✔
660
                    updated_heights.is_superset(&initial_heights)
3✔
661
                },
UNCOV
662
                "heights from the initial chain must all be in the updated chain",
×
663
            );
664

665
            assert!(
3✔
666
                {
3✔
667
                    let exp_anchor_heights = t
3✔
668
                        .anchors
3✔
669
                        .iter()
3✔
670
                        .map(|(h, _)| *h)
4✔
671
                        .chain(t.initial_cps.iter().copied())
3✔
672
                        .collect::<BTreeSet<_>>();
3✔
673
                    let anchor_heights = updated_local_chain
3✔
674
                        .iter_checkpoints()
3✔
675
                        .map(|cp| cp.height())
61✔
676
                        .collect::<BTreeSet<_>>();
3✔
677
                    anchor_heights.is_superset(&exp_anchor_heights)
3✔
678
                },
UNCOV
679
                "anchor heights must all be in updated chain",
×
680
            );
681
        }
682

683
        Ok(())
1✔
684
    }
1✔
685

686
    #[test]
687
    fn update_local_chain() -> anyhow::Result<()> {
1✔
688
        const TIP_HEIGHT: u32 = 50;
689

690
        let env = TestEnv::new()?;
1✔
691
        let blocks = {
1✔
692
            let bitcoind_client = &env.bitcoind.client;
1✔
693
            assert_eq!(bitcoind_client.get_block_count()?, 1);
1✔
694
            [
695
                (0, bitcoind_client.get_block_hash(0)?),
1✔
696
                (1, bitcoind_client.get_block_hash(1)?),
1✔
697
            ]
698
            .into_iter()
1✔
699
            .chain((2..).zip(env.mine_blocks((TIP_HEIGHT - 1) as usize, None)?))
1✔
700
            .collect::<BTreeMap<_, _>>()
1✔
701
        };
702
        // so new blocks can be seen by Electrs
703
        let env = env.reset_electrsd()?;
1✔
704
        let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
1✔
705
        let client = Builder::new(base_url.as_str()).build_blocking();
1✔
706

1✔
707
        struct TestCase {
1✔
708
            name: &'static str,
1✔
709
            /// Original local chain to start off with.
1✔
710
            chain: LocalChain,
1✔
711
            /// Heights of floating anchors. [`chain_update_blocking`] will request for checkpoints
1✔
712
            /// of these heights.
1✔
713
            request_heights: &'static [u32],
1✔
714
            /// The expected local chain result (heights only).
1✔
715
            exp_update_heights: &'static [u32],
1✔
716
        }
1✔
717

1✔
718
        let test_cases = [
1✔
719
            TestCase {
1✔
720
                name: "request_later_blocks",
1✔
721
                chain: local_chain![(0, blocks[&0]), (21, blocks[&21])],
1✔
722
                request_heights: &[22, 25, 28],
1✔
723
                exp_update_heights: &[21, 22, 25, 28],
1✔
724
            },
1✔
725
            TestCase {
1✔
726
                name: "request_prev_blocks",
1✔
727
                chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (5, blocks[&5])],
1✔
728
                request_heights: &[4],
1✔
729
                exp_update_heights: &[4, 5],
1✔
730
            },
1✔
731
            TestCase {
1✔
732
                name: "request_prev_blocks_2",
1✔
733
                chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (10, blocks[&10])],
1✔
734
                request_heights: &[4, 6],
1✔
735
                exp_update_heights: &[4, 6, 10],
1✔
736
            },
1✔
737
            TestCase {
1✔
738
                name: "request_later_and_prev_blocks",
1✔
739
                chain: local_chain![(0, blocks[&0]), (7, blocks[&7]), (11, blocks[&11])],
1✔
740
                request_heights: &[8, 9, 15],
1✔
741
                exp_update_heights: &[8, 9, 11, 15],
1✔
742
            },
1✔
743
            TestCase {
1✔
744
                name: "request_tip_only",
1✔
745
                chain: local_chain![(0, blocks[&0]), (5, blocks[&5]), (49, blocks[&49])],
1✔
746
                request_heights: &[TIP_HEIGHT],
1✔
747
                exp_update_heights: &[49],
1✔
748
            },
1✔
749
            TestCase {
1✔
750
                name: "request_nothing",
1✔
751
                chain: local_chain![(0, blocks[&0]), (13, blocks[&13]), (23, blocks[&23])],
1✔
752
                request_heights: &[],
1✔
753
                exp_update_heights: &[23],
1✔
754
            },
1✔
755
            TestCase {
1✔
756
                name: "request_nothing_during_reorg",
1✔
757
                chain: local_chain![(0, blocks[&0]), (13, blocks[&13]), (23, h!("23"))],
1✔
758
                request_heights: &[],
1✔
759
                exp_update_heights: &[13, 23],
1✔
760
            },
1✔
761
            TestCase {
1✔
762
                name: "request_nothing_during_reorg_2",
1✔
763
                chain: local_chain![
1✔
764
                    (0, blocks[&0]),
1✔
765
                    (21, blocks[&21]),
1✔
766
                    (22, h!("22")),
1✔
767
                    (23, h!("23"))
1✔
768
                ],
1✔
769
                request_heights: &[],
1✔
770
                exp_update_heights: &[21, 22, 23],
1✔
771
            },
1✔
772
            TestCase {
1✔
773
                name: "request_prev_blocks_during_reorg",
1✔
774
                chain: local_chain![
1✔
775
                    (0, blocks[&0]),
1✔
776
                    (21, blocks[&21]),
1✔
777
                    (22, h!("22")),
1✔
778
                    (23, h!("23"))
1✔
779
                ],
1✔
780
                request_heights: &[17, 20],
1✔
781
                exp_update_heights: &[17, 20, 21, 22, 23],
1✔
782
            },
1✔
783
            TestCase {
1✔
784
                name: "request_later_blocks_during_reorg",
1✔
785
                chain: local_chain![
1✔
786
                    (0, blocks[&0]),
1✔
787
                    (9, blocks[&9]),
1✔
788
                    (22, h!("22")),
1✔
789
                    (23, h!("23"))
1✔
790
                ],
1✔
791
                request_heights: &[25, 27],
1✔
792
                exp_update_heights: &[9, 22, 23, 25, 27],
1✔
793
            },
1✔
794
            TestCase {
1✔
795
                name: "request_later_blocks_during_reorg_2",
1✔
796
                chain: local_chain![(0, blocks[&0]), (9, h!("9"))],
1✔
797
                request_heights: &[10],
1✔
798
                exp_update_heights: &[0, 9, 10],
1✔
799
            },
1✔
800
            TestCase {
1✔
801
                name: "request_later_and_prev_blocks_during_reorg",
1✔
802
                chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (9, h!("9"))],
1✔
803
                request_heights: &[8, 11],
1✔
804
                exp_update_heights: &[1, 8, 9, 11],
1✔
805
            },
1✔
806
        ];
1✔
807

808
        for (i, t) in test_cases.into_iter().enumerate() {
12✔
809
            println!("Case {}: {}", i, t.name);
12✔
810
            let mut chain = t.chain;
12✔
811

12✔
812
            let mock_anchors = t
12✔
813
                .request_heights
12✔
814
                .iter()
12✔
815
                .map(|&h| {
17✔
816
                    let anchor_blockhash: BlockHash = bdk_chain::bitcoin::hashes::Hash::hash(
17✔
817
                        &format!("hash_at_height_{}", h).into_bytes(),
17✔
818
                    );
17✔
819
                    let txid: Txid = bdk_chain::bitcoin::hashes::Hash::hash(
17✔
820
                        &format!("txid_at_height_{}", h).into_bytes(),
17✔
821
                    );
17✔
822
                    let anchor = BlockId {
17✔
823
                        height: h,
17✔
824
                        hash: anchor_blockhash,
17✔
825
                    };
17✔
826
                    (anchor, txid)
17✔
827
                })
17✔
828
                .collect::<BTreeSet<_>>();
12✔
829
            let chain_update = chain_update(
12✔
830
                &client,
12✔
831
                &fetch_latest_blocks(&client)?,
12✔
832
                &chain.tip(),
12✔
833
                &mock_anchors,
12✔
UNCOV
834
            )?;
×
835

836
            let update_blocks = chain_update
12✔
837
                .iter()
12✔
838
                .map(|cp| cp.block_id())
172✔
839
                .collect::<BTreeSet<_>>();
12✔
840

12✔
841
            let exp_update_blocks = t
12✔
842
                .exp_update_heights
12✔
843
                .iter()
12✔
844
                .map(|&height| {
37✔
845
                    let hash = blocks[&height];
37✔
846
                    BlockId { height, hash }
37✔
847
                })
37✔
848
                .chain(
12✔
849
                    // Electrs Esplora `get_block` call fetches 10 blocks which is included in the
12✔
850
                    // update
12✔
851
                    blocks
12✔
852
                        .range(TIP_HEIGHT - 9..)
12✔
853
                        .map(|(&height, &hash)| BlockId { height, hash }),
120✔
854
                )
12✔
855
                .collect::<BTreeSet<_>>();
12✔
856

12✔
857
            assert!(
12✔
858
                update_blocks.is_superset(&exp_update_blocks),
12✔
UNCOV
859
                "[{}:{}] unexpected update",
×
860
                i,
861
                t.name
862
            );
863

864
            let _ = chain
12✔
865
                .apply_update(chain_update)
12✔
866
                .unwrap_or_else(|err| panic!("[{}:{}] update failed to apply: {}", i, t.name, err));
12✔
867

868
            // all requested heights must exist in the final chain
869
            for height in t.request_heights {
29✔
870
                let exp_blockhash = blocks.get(height).expect("block must exist in bitcoind");
17✔
871
                assert_eq!(
17✔
872
                    chain.get(*height).map(|cp| cp.hash()),
17✔
873
                    Some(*exp_blockhash),
17✔
UNCOV
874
                    "[{}:{}] block {}:{} must exist in final chain",
×
875
                    i,
876
                    t.name,
877
                    height,
878
                    exp_blockhash
879
                );
880
            }
881
        }
882

883
        Ok(())
1✔
884
    }
1✔
885
}
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