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

bitcoindevkit / bdk / 10544103668

25 Aug 2024 04:26AM UTC coverage: 82.062% (+0.2%) from 81.848%
10544103668

push

github

web-flow
Merge pull request #1568 from evanlinjin/tx_graph_update

Introduce `tx_graph::Update` and simplify `TxGraph` update logic

315 of 348 new or added lines in 8 files covered. (90.52%)

4 existing lines in 3 files now uncovered.

11213 of 13664 relevant lines covered (82.06%)

13427.25 hits per line

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

91.69
/crates/esplora/src/blocking_ext.rs
1
use std::collections::{BTreeSet, HashSet};
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::{BlockHash, OutPoint, ScriptBuf, Txid},
8
    local_chain::CheckPoint,
9
    BlockId, ConfirmationBlockTime,
10
};
11
use bdk_chain::{tx_graph, Anchor, Indexed};
12
use esplora_client::{OutputStatus, Tx};
13

14
use crate::{insert_anchor_from_status, insert_prevouts};
15

16
/// [`esplora_client::Error`]
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, R: Into<FullScanRequest<K>>>(
33
        &self,
34
        request: R,
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<I: 'static, R: Into<SyncRequest<I>>>(
47
        &self,
48
        request: R,
49
        parallel_requests: usize,
50
    ) -> Result<SyncResult, Error>;
51
}
52

53
impl EsploraExt for esplora_client::BlockingClient {
54
    fn full_scan<K: Ord + Clone, R: Into<FullScanRequest<K>>>(
4✔
55
        &self,
4✔
56
        request: R,
4✔
57
        stop_gap: usize,
4✔
58
        parallel_requests: usize,
4✔
59
    ) -> Result<FullScanResult<K>, Error> {
4✔
60
        let mut request = request.into();
4✔
61

4✔
62
        let chain_tip = request.chain_tip();
4✔
63
        let latest_blocks = if chain_tip.is_some() {
4✔
64
            Some(fetch_latest_blocks(self)?)
4✔
65
        } else {
66
            None
×
67
        };
68

69
        let mut graph_update = tx_graph::Update::default();
4✔
70
        let mut inserted_txs = HashSet::<Txid>::new();
4✔
71
        let mut last_active_indices = BTreeMap::<K, u32>::new();
4✔
72
        for keychain in request.keychains() {
4✔
73
            let keychain_spks = request.iter_spks(keychain.clone());
4✔
74
            let (update, last_active_index) = fetch_txs_with_keychain_spks(
4✔
75
                self,
4✔
76
                &mut inserted_txs,
4✔
77
                keychain_spks,
4✔
78
                stop_gap,
4✔
79
                parallel_requests,
4✔
80
            )?;
4✔
81
            graph_update.extend(update);
4✔
82
            if let Some(last_active_index) = last_active_index {
4✔
83
                last_active_indices.insert(keychain, last_active_index);
3✔
84
            }
3✔
85
        }
86

87
        let chain_update = match (chain_tip, latest_blocks) {
4✔
88
            (Some(chain_tip), Some(latest_blocks)) => Some(chain_update(
4✔
89
                self,
4✔
90
                &latest_blocks,
4✔
91
                &chain_tip,
4✔
92
                &graph_update.anchors,
4✔
93
            )?),
4✔
94
            _ => None,
×
95
        };
96

97
        Ok(FullScanResult {
4✔
98
            chain_update,
4✔
99
            graph_update,
4✔
100
            last_active_indices,
4✔
101
        })
4✔
102
    }
4✔
103

104
    fn sync<I: 'static, R: Into<SyncRequest<I>>>(
1✔
105
        &self,
1✔
106
        request: R,
1✔
107
        parallel_requests: usize,
1✔
108
    ) -> Result<SyncResult, Error> {
1✔
109
        let mut request: SyncRequest<I> = request.into();
1✔
110

1✔
111
        let chain_tip = request.chain_tip();
1✔
112
        let latest_blocks = if chain_tip.is_some() {
1✔
113
            Some(fetch_latest_blocks(self)?)
1✔
114
        } else {
115
            None
×
116
        };
117

118
        let mut graph_update = tx_graph::Update::<ConfirmationBlockTime>::default();
1✔
119
        let mut inserted_txs = HashSet::<Txid>::new();
1✔
120
        graph_update.extend(fetch_txs_with_spks(
1✔
121
            self,
1✔
122
            &mut inserted_txs,
1✔
123
            request.iter_spks(),
1✔
124
            parallel_requests,
1✔
125
        )?);
1✔
126
        graph_update.extend(fetch_txs_with_txids(
1✔
127
            self,
1✔
128
            &mut inserted_txs,
1✔
129
            request.iter_txids(),
1✔
130
            parallel_requests,
1✔
131
        )?);
1✔
132
        graph_update.extend(fetch_txs_with_outpoints(
1✔
133
            self,
1✔
134
            &mut inserted_txs,
1✔
135
            request.iter_outpoints(),
1✔
136
            parallel_requests,
1✔
137
        )?);
1✔
138

139
        let chain_update = match (chain_tip, latest_blocks) {
1✔
140
            (Some(chain_tip), Some(latest_blocks)) => Some(chain_update(
1✔
141
                self,
1✔
142
                &latest_blocks,
1✔
143
                &chain_tip,
1✔
144
                &graph_update.anchors,
1✔
145
            )?),
1✔
146
            _ => None,
×
147
        };
148

149
        Ok(SyncResult {
1✔
150
            chain_update,
1✔
151
            graph_update,
1✔
152
        })
1✔
153
    }
1✔
154
}
155

156
/// Fetch latest blocks from Esplora in an atomic call.
157
///
158
/// We want to do this before fetching transactions and anchors as we cannot fetch latest blocks AND
159
/// transactions atomically, and the checkpoint tip is used to determine last-scanned block (for
160
/// block-based chain-sources). Therefore it's better to be conservative when setting the tip (use
161
/// an earlier tip rather than a later tip) otherwise the caller may accidentally skip blocks when
162
/// alternating between chain-sources.
163
fn fetch_latest_blocks(
28✔
164
    client: &esplora_client::BlockingClient,
28✔
165
) -> Result<BTreeMap<u32, BlockHash>, Error> {
28✔
166
    Ok(client
28✔
167
        .get_blocks(None)?
28✔
168
        .into_iter()
28✔
169
        .map(|b| (b.time.height, b.id))
280✔
170
        .collect())
28✔
171
}
28✔
172

173
/// Used instead of [`esplora_client::BlockingClient::get_block_hash`].
174
///
175
/// This first checks the previously fetched `latest_blocks` before fetching from Esplora again.
176
fn fetch_block(
66✔
177
    client: &esplora_client::BlockingClient,
66✔
178
    latest_blocks: &BTreeMap<u32, BlockHash>,
66✔
179
    height: u32,
66✔
180
) -> Result<Option<BlockHash>, Error> {
66✔
181
    if let Some(&hash) = latest_blocks.get(&height) {
66✔
182
        return Ok(Some(hash));
17✔
183
    }
49✔
184

49✔
185
    // We avoid fetching blocks higher than previously fetched `latest_blocks` as the local chain
49✔
186
    // tip is used to signal for the last-synced-up-to-height.
49✔
187
    let &tip_height = latest_blocks
49✔
188
        .keys()
49✔
189
        .last()
49✔
190
        .expect("must have atleast one entry");
49✔
191
    if height > tip_height {
49✔
192
        return Ok(None);
×
193
    }
49✔
194

49✔
195
    Ok(Some(client.get_block_hash(height)?))
49✔
196
}
66✔
197

198
/// Create the [`local_chain::Update`].
199
///
200
/// We want to have a corresponding checkpoint per anchor height. However, checkpoints fetched
201
/// should not surpass `latest_blocks`.
202
fn chain_update<A: Anchor>(
23✔
203
    client: &esplora_client::BlockingClient,
23✔
204
    latest_blocks: &BTreeMap<u32, BlockHash>,
23✔
205
    local_tip: &CheckPoint,
23✔
206
    anchors: &BTreeSet<(A, Txid)>,
23✔
207
) -> Result<CheckPoint, Error> {
23✔
208
    let mut point_of_agreement = None;
23✔
209
    let mut conflicts = vec![];
23✔
210
    for local_cp in local_tip.iter() {
32✔
211
        let remote_hash = match fetch_block(client, latest_blocks, local_cp.height())? {
32✔
212
            Some(hash) => hash,
32✔
213
            None => continue,
×
214
        };
215
        if remote_hash == local_cp.hash() {
32✔
216
            point_of_agreement = Some(local_cp.clone());
23✔
217
            break;
23✔
218
        } else {
9✔
219
            // it is not strictly necessary to include all the conflicted heights (we do need the
9✔
220
            // first one) but it seems prudent to make sure the updated chain's heights are a
9✔
221
            // superset of the existing chain after update.
9✔
222
            conflicts.push(BlockId {
9✔
223
                height: local_cp.height(),
9✔
224
                hash: remote_hash,
9✔
225
            });
9✔
226
        }
9✔
227
    }
228

229
    let mut tip = point_of_agreement.expect("remote esplora should have same genesis block");
23✔
230

23✔
231
    tip = tip
23✔
232
        .extend(conflicts.into_iter().rev())
23✔
233
        .expect("evicted are in order");
23✔
234

235
    for anchor in anchors {
56✔
236
        let height = anchor.0.anchor_block().height;
33✔
237
        if tip.get(height).is_none() {
33✔
238
            let hash = match fetch_block(client, latest_blocks, height)? {
28✔
239
                Some(hash) => hash,
28✔
240
                None => continue,
×
241
            };
242
            tip = tip.insert(BlockId { height, hash });
28✔
243
        }
5✔
244
    }
245

246
    // insert the most recent blocks at the tip to make sure we update the tip and make the update
247
    // robust.
248
    for (&height, &hash) in latest_blocks.iter() {
230✔
249
        tip = tip.insert(BlockId { height, hash });
230✔
250
    }
230✔
251

252
    Ok(tip)
23✔
253
}
23✔
254

255
fn fetch_txs_with_keychain_spks<I: Iterator<Item = Indexed<ScriptBuf>>>(
5✔
256
    client: &esplora_client::BlockingClient,
5✔
257
    inserted_txs: &mut HashSet<Txid>,
5✔
258
    mut keychain_spks: I,
5✔
259
    stop_gap: usize,
5✔
260
    parallel_requests: usize,
5✔
261
) -> Result<(tx_graph::Update<ConfirmationBlockTime>, Option<u32>), Error> {
5✔
262
    type TxsOfSpkIndex = (u32, Vec<esplora_client::Tx>);
5✔
263

5✔
264
    let mut update = tx_graph::Update::<ConfirmationBlockTime>::default();
5✔
265
    let mut last_index = Option::<u32>::None;
5✔
266
    let mut last_active_index = Option::<u32>::None;
5✔
267

268
    loop {
34✔
269
        let handles = keychain_spks
34✔
270
            .by_ref()
34✔
271
            .take(parallel_requests)
34✔
272
            .map(|(spk_index, spk)| {
34✔
273
                std::thread::spawn({
32✔
274
                    let client = client.clone();
32✔
275
                    move || -> Result<TxsOfSpkIndex, Error> {
32✔
276
                        let mut last_seen = None;
32✔
277
                        let mut spk_txs = Vec::new();
32✔
278
                        loop {
279
                            let txs = client.scripthash_txs(&spk, last_seen)?;
32✔
280
                            let tx_count = txs.len();
32✔
281
                            last_seen = txs.last().map(|tx| tx.txid);
32✔
282
                            spk_txs.extend(txs);
32✔
283
                            if tx_count < 25 {
32✔
284
                                break Ok((spk_index, spk_txs));
32✔
285
                            }
×
286
                        }
287
                    }
32✔
288
                })
32✔
289
            })
34✔
290
            .collect::<Vec<JoinHandle<Result<TxsOfSpkIndex, Error>>>>();
34✔
291

34✔
292
        if handles.is_empty() {
34✔
293
            break;
2✔
294
        }
32✔
295

296
        for handle in handles {
64✔
297
            let (index, txs) = handle.join().expect("thread must not panic")?;
32✔
298
            last_index = Some(index);
32✔
299
            if !txs.is_empty() {
32✔
300
                last_active_index = Some(index);
6✔
301
            }
26✔
302
            for tx in txs {
38✔
303
                if inserted_txs.insert(tx.txid) {
6✔
304
                    update.txs.push(tx.to_tx().into());
6✔
305
                }
6✔
306
                insert_anchor_from_status(&mut update, tx.txid, tx.status);
6✔
307
                insert_prevouts(&mut update, tx.vin);
6✔
308
            }
309
        }
310

311
        let last_index = last_index.expect("Must be set since handles wasn't empty.");
32✔
312
        let gap_limit_reached = if let Some(i) = last_active_index {
32✔
313
            last_index >= i.saturating_add(stop_gap as u32)
20✔
314
        } else {
315
            last_index + 1 >= stop_gap as u32
12✔
316
        };
317
        if gap_limit_reached {
32✔
318
            break;
3✔
319
        }
29✔
320
    }
321

322
    Ok((update, last_active_index))
5✔
323
}
5✔
324

325
/// Fetch transactions and associated [`ConfirmationBlockTime`]s by scanning `spks`
326
/// against Esplora.
327
///
328
/// Unlike with [`EsploraExt::fetch_txs_with_keychain_spks`], `spks` must be *bounded* as all
329
/// contained scripts will be scanned. `parallel_requests` specifies the maximum number of HTTP
330
/// requests to make in parallel.
331
///
332
/// Refer to [crate-level docs](crate) for more.
333
fn fetch_txs_with_spks<I: IntoIterator<Item = ScriptBuf>>(
1✔
334
    client: &esplora_client::BlockingClient,
1✔
335
    inserted_txs: &mut HashSet<Txid>,
1✔
336
    spks: I,
1✔
337
    parallel_requests: usize,
1✔
338
) -> Result<tx_graph::Update<ConfirmationBlockTime>, Error> {
1✔
339
    fetch_txs_with_keychain_spks(
1✔
340
        client,
1✔
341
        inserted_txs,
1✔
342
        spks.into_iter().enumerate().map(|(i, spk)| (i as u32, spk)),
2✔
343
        usize::MAX,
1✔
344
        parallel_requests,
1✔
345
    )
1✔
346
    .map(|(update, _)| update)
1✔
347
}
1✔
348

349
/// Fetch transactions and associated [`ConfirmationBlockTime`]s by scanning `txids`
350
/// against Esplora.
351
///
352
/// `parallel_requests` specifies the maximum number of HTTP requests to make in parallel.
353
///
354
/// Refer to [crate-level docs](crate) for more.
355
fn fetch_txs_with_txids<I: IntoIterator<Item = Txid>>(
3✔
356
    client: &esplora_client::BlockingClient,
3✔
357
    inserted_txs: &mut HashSet<Txid>,
3✔
358
    txids: I,
3✔
359
    parallel_requests: usize,
3✔
360
) -> Result<tx_graph::Update<ConfirmationBlockTime>, Error> {
3✔
361
    let mut update = tx_graph::Update::<ConfirmationBlockTime>::default();
3✔
362
    // Only fetch for non-inserted txs.
3✔
363
    let mut txids = txids
3✔
364
        .into_iter()
3✔
365
        .filter(|txid| !inserted_txs.contains(txid))
3✔
366
        .collect::<Vec<Txid>>()
3✔
367
        .into_iter();
3✔
368
    loop {
3✔
369
        let handles = txids
3✔
370
            .by_ref()
3✔
371
            .take(parallel_requests)
3✔
372
            .map(|txid| {
3✔
373
                let client = client.clone();
×
374
                std::thread::spawn(move || {
×
NEW
375
                    client
×
NEW
376
                        .get_tx_info(&txid)
×
NEW
377
                        .map_err(Box::new)
×
NEW
378
                        .map(|t| (txid, t))
×
UNCOV
379
                })
×
380
            })
3✔
381
            .collect::<Vec<JoinHandle<Result<(Txid, Option<Tx>), Error>>>>();
3✔
382

3✔
383
        if handles.is_empty() {
3✔
384
            break;
3✔
385
        }
×
386

387
        for handle in handles {
×
NEW
388
            let (txid, tx_info) = handle.join().expect("thread must not panic")?;
×
NEW
389
            if let Some(tx_info) = tx_info {
×
NEW
390
                if inserted_txs.insert(txid) {
×
NEW
391
                    update.txs.push(tx_info.to_tx().into());
×
392
                }
×
NEW
393
                insert_anchor_from_status(&mut update, txid, tx_info.status);
×
NEW
394
                insert_prevouts(&mut update, tx_info.vin);
×
UNCOV
395
            }
×
396
        }
397
    }
398
    Ok(update)
3✔
399
}
3✔
400

401
/// Fetch transactions and [`ConfirmationBlockTime`]s that contain and spend the provided
402
/// `outpoints`.
403
///
404
/// `parallel_requests` specifies the maximum number of HTTP requests to make in parallel.
405
///
406
/// Refer to [crate-level docs](crate) for more.
407
fn fetch_txs_with_outpoints<I: IntoIterator<Item = OutPoint>>(
1✔
408
    client: &esplora_client::BlockingClient,
1✔
409
    inserted_txs: &mut HashSet<Txid>,
1✔
410
    outpoints: I,
1✔
411
    parallel_requests: usize,
1✔
412
) -> Result<tx_graph::Update<ConfirmationBlockTime>, Error> {
1✔
413
    let outpoints = outpoints.into_iter().collect::<Vec<_>>();
1✔
414
    let mut update = tx_graph::Update::<ConfirmationBlockTime>::default();
1✔
415

1✔
416
    // make sure txs exists in graph and tx statuses are updated
1✔
417
    // TODO: We should maintain a tx cache (like we do with Electrum).
1✔
418
    update.extend(fetch_txs_with_txids(
1✔
419
        client,
1✔
420
        inserted_txs,
1✔
421
        outpoints.iter().map(|op| op.txid),
1✔
422
        parallel_requests,
1✔
423
    )?);
1✔
424

425
    // get outpoint spend-statuses
426
    let mut outpoints = outpoints.into_iter();
1✔
427
    let mut missing_txs = Vec::<Txid>::with_capacity(outpoints.len());
1✔
428
    loop {
1✔
429
        let handles = outpoints
1✔
430
            .by_ref()
1✔
431
            .take(parallel_requests)
1✔
432
            .map(|op| {
1✔
433
                let client = client.clone();
×
434
                std::thread::spawn(move || {
×
435
                    client
×
436
                        .get_output_status(&op.txid, op.vout as _)
×
437
                        .map_err(Box::new)
×
438
                })
×
439
            })
1✔
440
            .collect::<Vec<JoinHandle<Result<Option<OutputStatus>, Error>>>>();
1✔
441

1✔
442
        if handles.is_empty() {
1✔
443
            break;
1✔
444
        }
×
445

446
        for handle in handles {
×
447
            if let Some(op_status) = handle.join().expect("thread must not panic")? {
×
448
                let spend_txid = match op_status.txid {
×
449
                    Some(txid) => txid,
×
450
                    None => continue,
×
451
                };
NEW
452
                if !inserted_txs.contains(&spend_txid) {
×
453
                    missing_txs.push(spend_txid);
×
454
                }
×
455
                if let Some(spend_status) = op_status.status {
×
NEW
456
                    insert_anchor_from_status(&mut update, spend_txid, spend_status);
×
457
                }
×
458
            }
×
459
        }
460
    }
461

462
    update.extend(fetch_txs_with_txids(
1✔
463
        client,
1✔
464
        inserted_txs,
1✔
465
        missing_txs,
1✔
466
        parallel_requests,
1✔
467
    )?);
1✔
468
    Ok(update)
1✔
469
}
1✔
470

471
#[cfg(test)]
472
mod test {
473
    use crate::blocking_ext::{chain_update, fetch_latest_blocks};
474
    use bdk_chain::bitcoin::hashes::Hash;
475
    use bdk_chain::bitcoin::Txid;
476
    use bdk_chain::local_chain::LocalChain;
477
    use bdk_chain::BlockId;
478
    use bdk_testenv::{anyhow, bitcoincore_rpc::RpcApi, TestEnv};
479
    use esplora_client::{BlockHash, Builder};
480
    use std::collections::{BTreeMap, BTreeSet};
481
    use std::time::Duration;
482

483
    macro_rules! h {
484
        ($index:literal) => {{
485
            bdk_chain::bitcoin::hashes::Hash::hash($index.as_bytes())
486
        }};
487
    }
488

489
    macro_rules! local_chain {
490
        [ $(($height:expr, $block_hash:expr)), * ] => {{
491
            #[allow(unused_mut)]
492
            bdk_chain::local_chain::LocalChain::from_blocks([$(($height, $block_hash).into()),*].into_iter().collect())
493
                .expect("chain must have genesis block")
494
        }};
495
    }
496

497
    /// Ensure that update does not remove heights (from original), and all anchor heights are included.
498
    #[test]
499
    pub fn test_finalize_chain_update() -> anyhow::Result<()> {
1✔
500
        struct TestCase<'a> {
1✔
501
            name: &'a str,
1✔
502
            /// Initial blockchain height to start the env with.
1✔
503
            initial_env_height: u32,
1✔
504
            /// Initial checkpoint heights to start with in the local chain.
1✔
505
            initial_cps: &'a [u32],
1✔
506
            /// The final blockchain height of the env.
1✔
507
            final_env_height: u32,
1✔
508
            /// The anchors to test with: `(height, txid)`. Only the height is provided as we can fetch
1✔
509
            /// the blockhash from the env.
1✔
510
            anchors: &'a [(u32, Txid)],
1✔
511
        }
1✔
512

1✔
513
        let test_cases = [
1✔
514
            TestCase {
1✔
515
                name: "chain_extends",
1✔
516
                initial_env_height: 60,
1✔
517
                initial_cps: &[59, 60],
1✔
518
                final_env_height: 90,
1✔
519
                anchors: &[],
1✔
520
            },
1✔
521
            TestCase {
1✔
522
                name: "introduce_older_heights",
1✔
523
                initial_env_height: 50,
1✔
524
                initial_cps: &[10, 15],
1✔
525
                final_env_height: 50,
1✔
526
                anchors: &[(11, h!("A")), (14, h!("B"))],
1✔
527
            },
1✔
528
            TestCase {
1✔
529
                name: "introduce_older_heights_after_chain_extends",
1✔
530
                initial_env_height: 50,
1✔
531
                initial_cps: &[10, 15],
1✔
532
                final_env_height: 100,
1✔
533
                anchors: &[(11, h!("A")), (14, h!("B"))],
1✔
534
            },
1✔
535
        ];
1✔
536

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

540
            let env = TestEnv::new()?;
3✔
541
            let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
3✔
542
            let client = Builder::new(base_url.as_str()).build_blocking();
3✔
543

544
            // set env to `initial_env_height`
545
            if let Some(to_mine) = t
3✔
546
                .initial_env_height
3✔
547
                .checked_sub(env.make_checkpoint_tip().height())
3✔
548
            {
549
                env.mine_blocks(to_mine as _, None)?;
3✔
550
            }
×
551
            while client.get_height()? < t.initial_env_height {
1,303✔
552
                std::thread::sleep(Duration::from_millis(10));
1,300✔
553
            }
1,300✔
554

555
            // craft initial `local_chain`
556
            let local_chain = {
3✔
557
                let (mut chain, _) = LocalChain::from_genesis_hash(env.genesis_hash()?);
3✔
558
                // force `chain_update_blocking` to add all checkpoints in `t.initial_cps`
559
                let anchors = t
3✔
560
                    .initial_cps
3✔
561
                    .iter()
3✔
562
                    .map(|&height| -> anyhow::Result<_> {
6✔
563
                        Ok((
6✔
564
                            BlockId {
6✔
565
                                height,
6✔
566
                                hash: env.bitcoind.client.get_block_hash(height as _)?,
6✔
567
                            },
568
                            Txid::all_zeros(),
6✔
569
                        ))
570
                    })
6✔
571
                    .collect::<anyhow::Result<BTreeSet<_>>>()?;
3✔
572
                let update = chain_update(
3✔
573
                    &client,
3✔
574
                    &fetch_latest_blocks(&client)?,
3✔
575
                    &chain.tip(),
3✔
576
                    &anchors,
3✔
577
                )?;
×
578
                chain.apply_update(update)?;
3✔
579
                chain
3✔
580
            };
3✔
581
            println!("local chain height: {}", local_chain.tip().height());
3✔
582

583
            // extend env chain
584
            if let Some(to_mine) = t
3✔
585
                .final_env_height
3✔
586
                .checked_sub(env.make_checkpoint_tip().height())
3✔
587
            {
588
                env.mine_blocks(to_mine as _, None)?;
3✔
589
            }
×
590
            while client.get_height()? < t.final_env_height {
963✔
591
                std::thread::sleep(Duration::from_millis(10));
960✔
592
            }
960✔
593

594
            // craft update
595
            let update = {
3✔
596
                let anchors = t
3✔
597
                    .anchors
3✔
598
                    .iter()
3✔
599
                    .map(|&(height, txid)| -> anyhow::Result<_> {
4✔
600
                        Ok((
4✔
601
                            BlockId {
4✔
602
                                height,
4✔
603
                                hash: env.bitcoind.client.get_block_hash(height as _)?,
4✔
604
                            },
605
                            txid,
4✔
606
                        ))
607
                    })
4✔
608
                    .collect::<anyhow::Result<_>>()?;
3✔
609
                chain_update(
610
                    &client,
3✔
611
                    &fetch_latest_blocks(&client)?,
3✔
612
                    &local_chain.tip(),
3✔
613
                    &anchors,
3✔
614
                )?
×
615
            };
616

617
            // apply update
618
            let mut updated_local_chain = local_chain.clone();
3✔
619
            updated_local_chain.apply_update(update)?;
3✔
620
            println!(
3✔
621
                "updated local chain height: {}",
3✔
622
                updated_local_chain.tip().height()
3✔
623
            );
3✔
624

3✔
625
            assert!(
3✔
626
                {
3✔
627
                    let initial_heights = local_chain
3✔
628
                        .iter_checkpoints()
3✔
629
                        .map(|cp| cp.height())
37✔
630
                        .collect::<BTreeSet<_>>();
3✔
631
                    let updated_heights = updated_local_chain
3✔
632
                        .iter_checkpoints()
3✔
633
                        .map(|cp| cp.height())
61✔
634
                        .collect::<BTreeSet<_>>();
3✔
635
                    updated_heights.is_superset(&initial_heights)
3✔
636
                },
637
                "heights from the initial chain must all be in the updated chain",
×
638
            );
639

640
            assert!(
3✔
641
                {
3✔
642
                    let exp_anchor_heights = t
3✔
643
                        .anchors
3✔
644
                        .iter()
3✔
645
                        .map(|(h, _)| *h)
4✔
646
                        .chain(t.initial_cps.iter().copied())
3✔
647
                        .collect::<BTreeSet<_>>();
3✔
648
                    let anchor_heights = updated_local_chain
3✔
649
                        .iter_checkpoints()
3✔
650
                        .map(|cp| cp.height())
61✔
651
                        .collect::<BTreeSet<_>>();
3✔
652
                    anchor_heights.is_superset(&exp_anchor_heights)
3✔
653
                },
654
                "anchor heights must all be in updated chain",
×
655
            );
656
        }
657

658
        Ok(())
1✔
659
    }
1✔
660

661
    #[test]
662
    fn update_local_chain() -> anyhow::Result<()> {
1✔
663
        const TIP_HEIGHT: u32 = 50;
664

665
        let env = TestEnv::new()?;
1✔
666
        let blocks = {
1✔
667
            let bitcoind_client = &env.bitcoind.client;
1✔
668
            assert_eq!(bitcoind_client.get_block_count()?, 1);
1✔
669
            [
670
                (0, bitcoind_client.get_block_hash(0)?),
1✔
671
                (1, bitcoind_client.get_block_hash(1)?),
1✔
672
            ]
673
            .into_iter()
1✔
674
            .chain((2..).zip(env.mine_blocks((TIP_HEIGHT - 1) as usize, None)?))
1✔
675
            .collect::<BTreeMap<_, _>>()
1✔
676
        };
677
        // so new blocks can be seen by Electrs
678
        let env = env.reset_electrsd()?;
1✔
679
        let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
1✔
680
        let client = Builder::new(base_url.as_str()).build_blocking();
1✔
681

1✔
682
        struct TestCase {
1✔
683
            name: &'static str,
1✔
684
            /// Original local chain to start off with.
1✔
685
            chain: LocalChain,
1✔
686
            /// Heights of floating anchors. [`chain_update_blocking`] will request for checkpoints
1✔
687
            /// of these heights.
1✔
688
            request_heights: &'static [u32],
1✔
689
            /// The expected local chain result (heights only).
1✔
690
            exp_update_heights: &'static [u32],
1✔
691
        }
1✔
692

1✔
693
        let test_cases = [
1✔
694
            TestCase {
1✔
695
                name: "request_later_blocks",
1✔
696
                chain: local_chain![(0, blocks[&0]), (21, blocks[&21])],
1✔
697
                request_heights: &[22, 25, 28],
1✔
698
                exp_update_heights: &[21, 22, 25, 28],
1✔
699
            },
1✔
700
            TestCase {
1✔
701
                name: "request_prev_blocks",
1✔
702
                chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (5, blocks[&5])],
1✔
703
                request_heights: &[4],
1✔
704
                exp_update_heights: &[4, 5],
1✔
705
            },
1✔
706
            TestCase {
1✔
707
                name: "request_prev_blocks_2",
1✔
708
                chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (10, blocks[&10])],
1✔
709
                request_heights: &[4, 6],
1✔
710
                exp_update_heights: &[4, 6, 10],
1✔
711
            },
1✔
712
            TestCase {
1✔
713
                name: "request_later_and_prev_blocks",
1✔
714
                chain: local_chain![(0, blocks[&0]), (7, blocks[&7]), (11, blocks[&11])],
1✔
715
                request_heights: &[8, 9, 15],
1✔
716
                exp_update_heights: &[8, 9, 11, 15],
1✔
717
            },
1✔
718
            TestCase {
1✔
719
                name: "request_tip_only",
1✔
720
                chain: local_chain![(0, blocks[&0]), (5, blocks[&5]), (49, blocks[&49])],
1✔
721
                request_heights: &[TIP_HEIGHT],
1✔
722
                exp_update_heights: &[49],
1✔
723
            },
1✔
724
            TestCase {
1✔
725
                name: "request_nothing",
1✔
726
                chain: local_chain![(0, blocks[&0]), (13, blocks[&13]), (23, blocks[&23])],
1✔
727
                request_heights: &[],
1✔
728
                exp_update_heights: &[23],
1✔
729
            },
1✔
730
            TestCase {
1✔
731
                name: "request_nothing_during_reorg",
1✔
732
                chain: local_chain![(0, blocks[&0]), (13, blocks[&13]), (23, h!("23"))],
1✔
733
                request_heights: &[],
1✔
734
                exp_update_heights: &[13, 23],
1✔
735
            },
1✔
736
            TestCase {
1✔
737
                name: "request_nothing_during_reorg_2",
1✔
738
                chain: local_chain![
1✔
739
                    (0, blocks[&0]),
1✔
740
                    (21, blocks[&21]),
1✔
741
                    (22, h!("22")),
1✔
742
                    (23, h!("23"))
1✔
743
                ],
1✔
744
                request_heights: &[],
1✔
745
                exp_update_heights: &[21, 22, 23],
1✔
746
            },
1✔
747
            TestCase {
1✔
748
                name: "request_prev_blocks_during_reorg",
1✔
749
                chain: local_chain![
1✔
750
                    (0, blocks[&0]),
1✔
751
                    (21, blocks[&21]),
1✔
752
                    (22, h!("22")),
1✔
753
                    (23, h!("23"))
1✔
754
                ],
1✔
755
                request_heights: &[17, 20],
1✔
756
                exp_update_heights: &[17, 20, 21, 22, 23],
1✔
757
            },
1✔
758
            TestCase {
1✔
759
                name: "request_later_blocks_during_reorg",
1✔
760
                chain: local_chain![
1✔
761
                    (0, blocks[&0]),
1✔
762
                    (9, blocks[&9]),
1✔
763
                    (22, h!("22")),
1✔
764
                    (23, h!("23"))
1✔
765
                ],
1✔
766
                request_heights: &[25, 27],
1✔
767
                exp_update_heights: &[9, 22, 23, 25, 27],
1✔
768
            },
1✔
769
            TestCase {
1✔
770
                name: "request_later_blocks_during_reorg_2",
1✔
771
                chain: local_chain![(0, blocks[&0]), (9, h!("9"))],
1✔
772
                request_heights: &[10],
1✔
773
                exp_update_heights: &[0, 9, 10],
1✔
774
            },
1✔
775
            TestCase {
1✔
776
                name: "request_later_and_prev_blocks_during_reorg",
1✔
777
                chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (9, h!("9"))],
1✔
778
                request_heights: &[8, 11],
1✔
779
                exp_update_heights: &[1, 8, 9, 11],
1✔
780
            },
1✔
781
        ];
1✔
782

783
        for (i, t) in test_cases.into_iter().enumerate() {
12✔
784
            println!("Case {}: {}", i, t.name);
12✔
785
            let mut chain = t.chain;
12✔
786

12✔
787
            let mock_anchors = t
12✔
788
                .request_heights
12✔
789
                .iter()
12✔
790
                .map(|&h| {
17✔
791
                    let anchor_blockhash: BlockHash = bdk_chain::bitcoin::hashes::Hash::hash(
17✔
792
                        &format!("hash_at_height_{}", h).into_bytes(),
17✔
793
                    );
17✔
794
                    let txid: Txid = bdk_chain::bitcoin::hashes::Hash::hash(
17✔
795
                        &format!("txid_at_height_{}", h).into_bytes(),
17✔
796
                    );
17✔
797
                    let anchor = BlockId {
17✔
798
                        height: h,
17✔
799
                        hash: anchor_blockhash,
17✔
800
                    };
17✔
801
                    (anchor, txid)
17✔
802
                })
17✔
803
                .collect::<BTreeSet<_>>();
12✔
804
            let chain_update = chain_update(
12✔
805
                &client,
12✔
806
                &fetch_latest_blocks(&client)?,
12✔
807
                &chain.tip(),
12✔
808
                &mock_anchors,
12✔
809
            )?;
×
810

811
            let update_blocks = chain_update
12✔
812
                .iter()
12✔
813
                .map(|cp| cp.block_id())
172✔
814
                .collect::<BTreeSet<_>>();
12✔
815

12✔
816
            let exp_update_blocks = t
12✔
817
                .exp_update_heights
12✔
818
                .iter()
12✔
819
                .map(|&height| {
37✔
820
                    let hash = blocks[&height];
37✔
821
                    BlockId { height, hash }
37✔
822
                })
37✔
823
                .chain(
12✔
824
                    // Electrs Esplora `get_block` call fetches 10 blocks which is included in the
12✔
825
                    // update
12✔
826
                    blocks
12✔
827
                        .range(TIP_HEIGHT - 9..)
12✔
828
                        .map(|(&height, &hash)| BlockId { height, hash }),
120✔
829
                )
12✔
830
                .collect::<BTreeSet<_>>();
12✔
831

12✔
832
            assert!(
12✔
833
                update_blocks.is_superset(&exp_update_blocks),
12✔
834
                "[{}:{}] unexpected update",
×
835
                i,
836
                t.name
837
            );
838

839
            let _ = chain
12✔
840
                .apply_update(chain_update)
12✔
841
                .unwrap_or_else(|err| panic!("[{}:{}] update failed to apply: {}", i, t.name, err));
12✔
842

843
            // all requested heights must exist in the final chain
844
            for height in t.request_heights {
29✔
845
                let exp_blockhash = blocks.get(height).expect("block must exist in bitcoind");
17✔
846
                assert_eq!(
17✔
847
                    chain.get(*height).map(|cp| cp.hash()),
17✔
848
                    Some(*exp_blockhash),
17✔
849
                    "[{}:{}] block {}:{} must exist in final chain",
×
850
                    i,
851
                    t.name,
852
                    height,
853
                    exp_blockhash
854
                );
855
            }
856
        }
857

858
        Ok(())
1✔
859
    }
1✔
860
}
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