bdk_esplora/
blocking_ext.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
use bdk_core::collections::{BTreeMap, BTreeSet, HashSet};
use bdk_core::spk_client::{FullScanRequest, FullScanResponse, SyncRequest, SyncResponse};
use bdk_core::{
    bitcoin::{BlockHash, OutPoint, ScriptBuf, Txid},
    BlockId, CheckPoint, ConfirmationBlockTime, Indexed, TxUpdate,
};
use esplora_client::{OutputStatus, Tx};
use std::thread::JoinHandle;

use crate::{insert_anchor_from_status, insert_prevouts};

/// [`esplora_client::Error`]
pub type Error = Box<esplora_client::Error>;

/// Trait to extend the functionality of [`esplora_client::BlockingClient`].
///
/// Refer to [crate-level documentation](crate) for more.
pub trait EsploraExt {
    /// Scan keychain scripts for transactions against Esplora, returning an update that can be
    /// applied to the receiving structures.
    ///
    /// `request` provides the data required to perform a script-pubkey-based full scan
    /// (see [`FullScanRequest`]). The full scan for each keychain (`K`) stops after a gap of
    /// `stop_gap` script pubkeys with no associated transactions. `parallel_requests` specifies
    /// the maximum number of HTTP requests to make in parallel.
    ///
    /// Refer to [crate-level docs](crate) for more.
    fn full_scan<K: Ord + Clone, R: Into<FullScanRequest<K>>>(
        &self,
        request: R,
        stop_gap: usize,
        parallel_requests: usize,
    ) -> Result<FullScanResponse<K>, Error>;

    /// Sync a set of scripts, txids, and/or outpoints against Esplora.
    ///
    /// `request` provides the data required to perform a script-pubkey-based sync (see
    /// [`SyncRequest`]). `parallel_requests` specifies the maximum number of HTTP requests to make
    /// in parallel.
    ///
    /// Refer to [crate-level docs](crate) for more.
    fn sync<I: 'static, R: Into<SyncRequest<I>>>(
        &self,
        request: R,
        parallel_requests: usize,
    ) -> Result<SyncResponse, Error>;
}

impl EsploraExt for esplora_client::BlockingClient {
    fn full_scan<K: Ord + Clone, R: Into<FullScanRequest<K>>>(
        &self,
        request: R,
        stop_gap: usize,
        parallel_requests: usize,
    ) -> Result<FullScanResponse<K>, Error> {
        let mut request = request.into();

        let chain_tip = request.chain_tip();
        let latest_blocks = if chain_tip.is_some() {
            Some(fetch_latest_blocks(self)?)
        } else {
            None
        };

        let mut tx_update = TxUpdate::default();
        let mut inserted_txs = HashSet::<Txid>::new();
        let mut last_active_indices = BTreeMap::<K, u32>::new();
        for keychain in request.keychains() {
            let keychain_spks = request.iter_spks(keychain.clone());
            let (update, last_active_index) = fetch_txs_with_keychain_spks(
                self,
                &mut inserted_txs,
                keychain_spks,
                stop_gap,
                parallel_requests,
            )?;
            tx_update.extend(update);
            if let Some(last_active_index) = last_active_index {
                last_active_indices.insert(keychain, last_active_index);
            }
        }

        let chain_update = match (chain_tip, latest_blocks) {
            (Some(chain_tip), Some(latest_blocks)) => Some(chain_update(
                self,
                &latest_blocks,
                &chain_tip,
                &tx_update.anchors,
            )?),
            _ => None,
        };

        Ok(FullScanResponse {
            chain_update,
            tx_update,
            last_active_indices,
        })
    }

    fn sync<I: 'static, R: Into<SyncRequest<I>>>(
        &self,
        request: R,
        parallel_requests: usize,
    ) -> Result<SyncResponse, Error> {
        let mut request: SyncRequest<I> = request.into();

        let chain_tip = request.chain_tip();
        let latest_blocks = if chain_tip.is_some() {
            Some(fetch_latest_blocks(self)?)
        } else {
            None
        };

        let mut tx_update = TxUpdate::<ConfirmationBlockTime>::default();
        let mut inserted_txs = HashSet::<Txid>::new();
        tx_update.extend(fetch_txs_with_spks(
            self,
            &mut inserted_txs,
            request.iter_spks(),
            parallel_requests,
        )?);
        tx_update.extend(fetch_txs_with_txids(
            self,
            &mut inserted_txs,
            request.iter_txids(),
            parallel_requests,
        )?);
        tx_update.extend(fetch_txs_with_outpoints(
            self,
            &mut inserted_txs,
            request.iter_outpoints(),
            parallel_requests,
        )?);

        let chain_update = match (chain_tip, latest_blocks) {
            (Some(chain_tip), Some(latest_blocks)) => Some(chain_update(
                self,
                &latest_blocks,
                &chain_tip,
                &tx_update.anchors,
            )?),
            _ => None,
        };

        Ok(SyncResponse {
            chain_update,
            tx_update,
        })
    }
}

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

/// Used instead of [`esplora_client::BlockingClient::get_block_hash`].
///
/// This first checks the previously fetched `latest_blocks` before fetching from Esplora again.
fn fetch_block(
    client: &esplora_client::BlockingClient,
    latest_blocks: &BTreeMap<u32, BlockHash>,
    height: u32,
) -> Result<Option<BlockHash>, Error> {
    if let Some(&hash) = latest_blocks.get(&height) {
        return Ok(Some(hash));
    }

    // We avoid fetching blocks higher than previously fetched `latest_blocks` as the local chain
    // tip is used to signal for the last-synced-up-to-height.
    let &tip_height = latest_blocks
        .keys()
        .last()
        .expect("must have atleast one entry");
    if height > tip_height {
        return Ok(None);
    }

    Ok(Some(client.get_block_hash(height)?))
}

/// Create the [`local_chain::Update`].
///
/// We want to have a corresponding checkpoint per anchor height. However, checkpoints fetched
/// should not surpass `latest_blocks`.
fn chain_update(
    client: &esplora_client::BlockingClient,
    latest_blocks: &BTreeMap<u32, BlockHash>,
    local_tip: &CheckPoint,
    anchors: &BTreeSet<(ConfirmationBlockTime, Txid)>,
) -> Result<CheckPoint, Error> {
    let mut point_of_agreement = None;
    let mut conflicts = vec![];
    for local_cp in local_tip.iter() {
        let remote_hash = match fetch_block(client, latest_blocks, local_cp.height())? {
            Some(hash) => hash,
            None => continue,
        };
        if remote_hash == local_cp.hash() {
            point_of_agreement = Some(local_cp.clone());
            break;
        } else {
            // it is not strictly necessary to include all the conflicted heights (we do need the
            // first one) but it seems prudent to make sure the updated chain's heights are a
            // superset of the existing chain after update.
            conflicts.push(BlockId {
                height: local_cp.height(),
                hash: remote_hash,
            });
        }
    }

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

    tip = tip
        .extend(conflicts.into_iter().rev())
        .expect("evicted are in order");

    for (anchor, _) in anchors {
        let height = anchor.block_id.height;
        if tip.get(height).is_none() {
            let hash = match fetch_block(client, latest_blocks, height)? {
                Some(hash) => hash,
                None => continue,
            };
            tip = tip.insert(BlockId { height, hash });
        }
    }

    // insert the most recent blocks at the tip to make sure we update the tip and make the update
    // robust.
    for (&height, &hash) in latest_blocks.iter() {
        tip = tip.insert(BlockId { height, hash });
    }

    Ok(tip)
}

fn fetch_txs_with_keychain_spks<I: Iterator<Item = Indexed<ScriptBuf>>>(
    client: &esplora_client::BlockingClient,
    inserted_txs: &mut HashSet<Txid>,
    mut keychain_spks: I,
    stop_gap: usize,
    parallel_requests: usize,
) -> Result<(TxUpdate<ConfirmationBlockTime>, Option<u32>), Error> {
    type TxsOfSpkIndex = (u32, Vec<esplora_client::Tx>);

    let mut update = TxUpdate::<ConfirmationBlockTime>::default();
    let mut last_index = Option::<u32>::None;
    let mut last_active_index = Option::<u32>::None;

    loop {
        let handles = keychain_spks
            .by_ref()
            .take(parallel_requests)
            .map(|(spk_index, spk)| {
                std::thread::spawn({
                    let client = client.clone();
                    move || -> Result<TxsOfSpkIndex, Error> {
                        let mut last_seen = None;
                        let mut spk_txs = Vec::new();
                        loop {
                            let txs = client.scripthash_txs(&spk, last_seen)?;
                            let tx_count = txs.len();
                            last_seen = txs.last().map(|tx| tx.txid);
                            spk_txs.extend(txs);
                            if tx_count < 25 {
                                break Ok((spk_index, spk_txs));
                            }
                        }
                    }
                })
            })
            .collect::<Vec<JoinHandle<Result<TxsOfSpkIndex, Error>>>>();

        if handles.is_empty() {
            break;
        }

        for handle in handles {
            let (index, txs) = handle.join().expect("thread must not panic")?;
            last_index = Some(index);
            if !txs.is_empty() {
                last_active_index = Some(index);
            }
            for tx in txs {
                if inserted_txs.insert(tx.txid) {
                    update.txs.push(tx.to_tx().into());
                }
                insert_anchor_from_status(&mut update, tx.txid, tx.status);
                insert_prevouts(&mut update, tx.vin);
            }
        }

        let last_index = last_index.expect("Must be set since handles wasn't empty.");
        let gap_limit_reached = if let Some(i) = last_active_index {
            last_index >= i.saturating_add(stop_gap as u32)
        } else {
            last_index + 1 >= stop_gap as u32
        };
        if gap_limit_reached {
            break;
        }
    }

    Ok((update, last_active_index))
}

/// Fetch transactions and associated [`ConfirmationBlockTime`]s by scanning `spks`
/// against Esplora.
///
/// Unlike with [`EsploraExt::fetch_txs_with_keychain_spks`], `spks` must be *bounded* as all
/// contained scripts will be scanned. `parallel_requests` specifies the maximum number of HTTP
/// requests to make in parallel.
///
/// Refer to [crate-level docs](crate) for more.
fn fetch_txs_with_spks<I: IntoIterator<Item = ScriptBuf>>(
    client: &esplora_client::BlockingClient,
    inserted_txs: &mut HashSet<Txid>,
    spks: I,
    parallel_requests: usize,
) -> Result<TxUpdate<ConfirmationBlockTime>, Error> {
    fetch_txs_with_keychain_spks(
        client,
        inserted_txs,
        spks.into_iter().enumerate().map(|(i, spk)| (i as u32, spk)),
        usize::MAX,
        parallel_requests,
    )
    .map(|(update, _)| update)
}

/// Fetch transactions and associated [`ConfirmationBlockTime`]s by scanning `txids`
/// against Esplora.
///
/// `parallel_requests` specifies the maximum number of HTTP requests to make in parallel.
///
/// Refer to [crate-level docs](crate) for more.
fn fetch_txs_with_txids<I: IntoIterator<Item = Txid>>(
    client: &esplora_client::BlockingClient,
    inserted_txs: &mut HashSet<Txid>,
    txids: I,
    parallel_requests: usize,
) -> Result<TxUpdate<ConfirmationBlockTime>, Error> {
    let mut update = TxUpdate::<ConfirmationBlockTime>::default();
    // Only fetch for non-inserted txs.
    let mut txids = txids
        .into_iter()
        .filter(|txid| !inserted_txs.contains(txid))
        .collect::<Vec<Txid>>()
        .into_iter();
    loop {
        let handles = txids
            .by_ref()
            .take(parallel_requests)
            .map(|txid| {
                let client = client.clone();
                std::thread::spawn(move || {
                    client
                        .get_tx_info(&txid)
                        .map_err(Box::new)
                        .map(|t| (txid, t))
                })
            })
            .collect::<Vec<JoinHandle<Result<(Txid, Option<Tx>), Error>>>>();

        if handles.is_empty() {
            break;
        }

        for handle in handles {
            let (txid, tx_info) = handle.join().expect("thread must not panic")?;
            if let Some(tx_info) = tx_info {
                if inserted_txs.insert(txid) {
                    update.txs.push(tx_info.to_tx().into());
                }
                insert_anchor_from_status(&mut update, txid, tx_info.status);
                insert_prevouts(&mut update, tx_info.vin);
            }
        }
    }
    Ok(update)
}

/// Fetch transactions and [`ConfirmationBlockTime`]s that contain and spend the provided
/// `outpoints`.
///
/// `parallel_requests` specifies the maximum number of HTTP requests to make in parallel.
///
/// Refer to [crate-level docs](crate) for more.
fn fetch_txs_with_outpoints<I: IntoIterator<Item = OutPoint>>(
    client: &esplora_client::BlockingClient,
    inserted_txs: &mut HashSet<Txid>,
    outpoints: I,
    parallel_requests: usize,
) -> Result<TxUpdate<ConfirmationBlockTime>, Error> {
    let outpoints = outpoints.into_iter().collect::<Vec<_>>();
    let mut update = TxUpdate::<ConfirmationBlockTime>::default();

    // make sure txs exists in graph and tx statuses are updated
    // TODO: We should maintain a tx cache (like we do with Electrum).
    update.extend(fetch_txs_with_txids(
        client,
        inserted_txs,
        outpoints.iter().map(|op| op.txid),
        parallel_requests,
    )?);

    // get outpoint spend-statuses
    let mut outpoints = outpoints.into_iter();
    let mut missing_txs = Vec::<Txid>::with_capacity(outpoints.len());
    loop {
        let handles = outpoints
            .by_ref()
            .take(parallel_requests)
            .map(|op| {
                let client = client.clone();
                std::thread::spawn(move || {
                    client
                        .get_output_status(&op.txid, op.vout as _)
                        .map_err(Box::new)
                })
            })
            .collect::<Vec<JoinHandle<Result<Option<OutputStatus>, Error>>>>();

        if handles.is_empty() {
            break;
        }

        for handle in handles {
            if let Some(op_status) = handle.join().expect("thread must not panic")? {
                let spend_txid = match op_status.txid {
                    Some(txid) => txid,
                    None => continue,
                };
                if !inserted_txs.contains(&spend_txid) {
                    missing_txs.push(spend_txid);
                }
                if let Some(spend_status) = op_status.status {
                    insert_anchor_from_status(&mut update, spend_txid, spend_status);
                }
            }
        }
    }

    update.extend(fetch_txs_with_txids(
        client,
        inserted_txs,
        missing_txs,
        parallel_requests,
    )?);
    Ok(update)
}

#[cfg(test)]
mod test {
    use crate::blocking_ext::{chain_update, fetch_latest_blocks};
    use bdk_chain::bitcoin::hashes::Hash;
    use bdk_chain::bitcoin::Txid;
    use bdk_chain::local_chain::LocalChain;
    use bdk_chain::BlockId;
    use bdk_core::ConfirmationBlockTime;
    use bdk_testenv::{anyhow, bitcoincore_rpc::RpcApi, TestEnv};
    use esplora_client::{BlockHash, Builder};
    use std::collections::{BTreeMap, BTreeSet};
    use std::time::Duration;

    macro_rules! h {
        ($index:literal) => {{
            bdk_chain::bitcoin::hashes::Hash::hash($index.as_bytes())
        }};
    }

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

    /// Ensure that update does not remove heights (from original), and all anchor heights are included.
    #[test]
    pub fn test_finalize_chain_update() -> anyhow::Result<()> {
        struct TestCase<'a> {
            #[allow(dead_code)]
            name: &'a str,
            /// Initial blockchain height to start the env with.
            initial_env_height: u32,
            /// Initial checkpoint heights to start with in the local chain.
            initial_cps: &'a [u32],
            /// The final blockchain height of the env.
            final_env_height: u32,
            /// The anchors to test with: `(height, txid)`. Only the height is provided as we can fetch
            /// the blockhash from the env.
            anchors: &'a [(u32, Txid)],
        }

        let test_cases = [
            TestCase {
                name: "chain_extends",
                initial_env_height: 60,
                initial_cps: &[59, 60],
                final_env_height: 90,
                anchors: &[],
            },
            TestCase {
                name: "introduce_older_heights",
                initial_env_height: 50,
                initial_cps: &[10, 15],
                final_env_height: 50,
                anchors: &[(11, h!("A")), (14, h!("B"))],
            },
            TestCase {
                name: "introduce_older_heights_after_chain_extends",
                initial_env_height: 50,
                initial_cps: &[10, 15],
                final_env_height: 100,
                anchors: &[(11, h!("A")), (14, h!("B"))],
            },
        ];

        for t in test_cases.into_iter() {
            let env = TestEnv::new()?;
            let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
            let client = Builder::new(base_url.as_str()).build_blocking();

            // set env to `initial_env_height`
            if let Some(to_mine) = t
                .initial_env_height
                .checked_sub(env.make_checkpoint_tip().height())
            {
                env.mine_blocks(to_mine as _, None)?;
            }
            while client.get_height()? < t.initial_env_height {
                std::thread::sleep(Duration::from_millis(10));
            }

            // craft initial `local_chain`
            let local_chain = {
                let (mut chain, _) = LocalChain::from_genesis_hash(env.genesis_hash()?);
                // force `chain_update_blocking` to add all checkpoints in `t.initial_cps`
                let anchors = t
                    .initial_cps
                    .iter()
                    .map(|&height| -> anyhow::Result<_> {
                        Ok((
                            ConfirmationBlockTime {
                                block_id: BlockId {
                                    height,
                                    hash: env.bitcoind.client.get_block_hash(height as _)?,
                                },
                                confirmation_time: height as _,
                            },
                            Txid::all_zeros(),
                        ))
                    })
                    .collect::<anyhow::Result<BTreeSet<_>>>()?;
                let update = chain_update(
                    &client,
                    &fetch_latest_blocks(&client)?,
                    &chain.tip(),
                    &anchors,
                )?;
                chain.apply_update(update)?;
                chain
            };

            // extend env chain
            if let Some(to_mine) = t
                .final_env_height
                .checked_sub(env.make_checkpoint_tip().height())
            {
                env.mine_blocks(to_mine as _, None)?;
            }
            while client.get_height()? < t.final_env_height {
                std::thread::sleep(Duration::from_millis(10));
            }

            // craft update
            let update = {
                let anchors = t
                    .anchors
                    .iter()
                    .map(|&(height, txid)| -> anyhow::Result<_> {
                        Ok((
                            ConfirmationBlockTime {
                                block_id: BlockId {
                                    height,
                                    hash: env.bitcoind.client.get_block_hash(height as _)?,
                                },
                                confirmation_time: height as _,
                            },
                            txid,
                        ))
                    })
                    .collect::<anyhow::Result<_>>()?;
                chain_update(
                    &client,
                    &fetch_latest_blocks(&client)?,
                    &local_chain.tip(),
                    &anchors,
                )?
            };

            // apply update
            let mut updated_local_chain = local_chain.clone();
            updated_local_chain.apply_update(update)?;

            assert!(
                {
                    let initial_heights = local_chain
                        .iter_checkpoints()
                        .map(|cp| cp.height())
                        .collect::<BTreeSet<_>>();
                    let updated_heights = updated_local_chain
                        .iter_checkpoints()
                        .map(|cp| cp.height())
                        .collect::<BTreeSet<_>>();
                    updated_heights.is_superset(&initial_heights)
                },
                "heights from the initial chain must all be in the updated chain",
            );

            assert!(
                {
                    let exp_anchor_heights = t
                        .anchors
                        .iter()
                        .map(|(h, _)| *h)
                        .chain(t.initial_cps.iter().copied())
                        .collect::<BTreeSet<_>>();
                    let anchor_heights = updated_local_chain
                        .iter_checkpoints()
                        .map(|cp| cp.height())
                        .collect::<BTreeSet<_>>();
                    anchor_heights.is_superset(&exp_anchor_heights)
                },
                "anchor heights must all be in updated chain",
            );
        }

        Ok(())
    }

    #[test]
    fn update_local_chain() -> anyhow::Result<()> {
        const TIP_HEIGHT: u32 = 50;

        let env = TestEnv::new()?;
        let blocks = {
            let bitcoind_client = &env.bitcoind.client;
            assert_eq!(bitcoind_client.get_block_count()?, 1);
            [
                (0, bitcoind_client.get_block_hash(0)?),
                (1, bitcoind_client.get_block_hash(1)?),
            ]
            .into_iter()
            .chain((2..).zip(env.mine_blocks((TIP_HEIGHT - 1) as usize, None)?))
            .collect::<BTreeMap<_, _>>()
        };
        // so new blocks can be seen by Electrs
        let env = env.reset_electrsd()?;
        let base_url = format!("http://{}", &env.electrsd.esplora_url.clone().unwrap());
        let client = Builder::new(base_url.as_str()).build_blocking();

        struct TestCase {
            name: &'static str,
            /// Original local chain to start off with.
            chain: LocalChain,
            /// Heights of floating anchors. [`chain_update_blocking`] will request for checkpoints
            /// of these heights.
            request_heights: &'static [u32],
            /// The expected local chain result (heights only).
            exp_update_heights: &'static [u32],
        }

        let test_cases = [
            TestCase {
                name: "request_later_blocks",
                chain: local_chain![(0, blocks[&0]), (21, blocks[&21])],
                request_heights: &[22, 25, 28],
                exp_update_heights: &[21, 22, 25, 28],
            },
            TestCase {
                name: "request_prev_blocks",
                chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (5, blocks[&5])],
                request_heights: &[4],
                exp_update_heights: &[4, 5],
            },
            TestCase {
                name: "request_prev_blocks_2",
                chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (10, blocks[&10])],
                request_heights: &[4, 6],
                exp_update_heights: &[4, 6, 10],
            },
            TestCase {
                name: "request_later_and_prev_blocks",
                chain: local_chain![(0, blocks[&0]), (7, blocks[&7]), (11, blocks[&11])],
                request_heights: &[8, 9, 15],
                exp_update_heights: &[8, 9, 11, 15],
            },
            TestCase {
                name: "request_tip_only",
                chain: local_chain![(0, blocks[&0]), (5, blocks[&5]), (49, blocks[&49])],
                request_heights: &[TIP_HEIGHT],
                exp_update_heights: &[49],
            },
            TestCase {
                name: "request_nothing",
                chain: local_chain![(0, blocks[&0]), (13, blocks[&13]), (23, blocks[&23])],
                request_heights: &[],
                exp_update_heights: &[23],
            },
            TestCase {
                name: "request_nothing_during_reorg",
                chain: local_chain![(0, blocks[&0]), (13, blocks[&13]), (23, h!("23"))],
                request_heights: &[],
                exp_update_heights: &[13, 23],
            },
            TestCase {
                name: "request_nothing_during_reorg_2",
                chain: local_chain![
                    (0, blocks[&0]),
                    (21, blocks[&21]),
                    (22, h!("22")),
                    (23, h!("23"))
                ],
                request_heights: &[],
                exp_update_heights: &[21, 22, 23],
            },
            TestCase {
                name: "request_prev_blocks_during_reorg",
                chain: local_chain![
                    (0, blocks[&0]),
                    (21, blocks[&21]),
                    (22, h!("22")),
                    (23, h!("23"))
                ],
                request_heights: &[17, 20],
                exp_update_heights: &[17, 20, 21, 22, 23],
            },
            TestCase {
                name: "request_later_blocks_during_reorg",
                chain: local_chain![
                    (0, blocks[&0]),
                    (9, blocks[&9]),
                    (22, h!("22")),
                    (23, h!("23"))
                ],
                request_heights: &[25, 27],
                exp_update_heights: &[9, 22, 23, 25, 27],
            },
            TestCase {
                name: "request_later_blocks_during_reorg_2",
                chain: local_chain![(0, blocks[&0]), (9, h!("9"))],
                request_heights: &[10],
                exp_update_heights: &[0, 9, 10],
            },
            TestCase {
                name: "request_later_and_prev_blocks_during_reorg",
                chain: local_chain![(0, blocks[&0]), (1, blocks[&1]), (9, h!("9"))],
                request_heights: &[8, 11],
                exp_update_heights: &[1, 8, 9, 11],
            },
        ];

        for (i, t) in test_cases.into_iter().enumerate() {
            let mut chain = t.chain;

            let mock_anchors = t
                .request_heights
                .iter()
                .map(|&h| {
                    let anchor_blockhash: BlockHash = bdk_chain::bitcoin::hashes::Hash::hash(
                        &format!("hash_at_height_{}", h).into_bytes(),
                    );
                    let txid: Txid = bdk_chain::bitcoin::hashes::Hash::hash(
                        &format!("txid_at_height_{}", h).into_bytes(),
                    );
                    let anchor = ConfirmationBlockTime {
                        block_id: BlockId {
                            height: h,
                            hash: anchor_blockhash,
                        },
                        confirmation_time: h as _,
                    };
                    (anchor, txid)
                })
                .collect::<BTreeSet<_>>();
            let chain_update = chain_update(
                &client,
                &fetch_latest_blocks(&client)?,
                &chain.tip(),
                &mock_anchors,
            )?;

            let update_blocks = chain_update
                .iter()
                .map(|cp| cp.block_id())
                .collect::<BTreeSet<_>>();

            let exp_update_blocks = t
                .exp_update_heights
                .iter()
                .map(|&height| {
                    let hash = blocks[&height];
                    BlockId { height, hash }
                })
                .chain(
                    // Electrs Esplora `get_block` call fetches 10 blocks which is included in the
                    // update
                    blocks
                        .range(TIP_HEIGHT - 9..)
                        .map(|(&height, &hash)| BlockId { height, hash }),
                )
                .collect::<BTreeSet<_>>();

            assert!(
                update_blocks.is_superset(&exp_update_blocks),
                "[{}:{}] unexpected update",
                i,
                t.name
            );

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

            // all requested heights must exist in the final chain
            for height in t.request_heights {
                let exp_blockhash = blocks.get(height).expect("block must exist in bitcoind");
                assert_eq!(
                    chain.get(*height).map(|cp| cp.hash()),
                    Some(*exp_blockhash),
                    "[{}:{}] block {}:{} must exist in final chain",
                    i,
                    t.name,
                    height,
                    exp_blockhash
                );
            }
        }

        Ok(())
    }
}