|
1 | 1 | use std::io::{self, Write};
|
2 | 2 |
|
3 | 3 | use bdk_chain::{
|
4 |
| - bitcoin::Network, |
| 4 | + bitcoin::{BlockHash, Network, Txid}, |
5 | 5 | collections::BTreeSet,
|
6 | 6 | indexed_tx_graph,
|
7 | 7 | spk_client::{FullScanRequest, SyncRequest},
|
8 |
| - CanonicalizationParams, ConfirmationBlockTime, Merge, |
| 8 | + CanonicalizationParams, ConfirmationBlockTime, Merge, TxGraph, |
9 | 9 | };
|
10 | 10 | use bdk_electrum::{
|
11 | 11 | electrum_client::{self, Client, ElectrumApi},
|
@@ -94,6 +94,26 @@ pub struct ScanOptions {
|
94 | 94 | pub batch_size: usize,
|
95 | 95 | }
|
96 | 96 |
|
| 97 | +/// Extension trait to expose anchors in a public-friendly way |
| 98 | +trait TxGraphExt { |
| 99 | + fn iter_anchors_ext( |
| 100 | + &self, |
| 101 | + ) -> Box<dyn Iterator<Item = ((Txid, BlockHash), ConfirmationBlockTime)> + '_>; |
| 102 | +} |
| 103 | + |
| 104 | +impl TxGraphExt for TxGraph<ConfirmationBlockTime> { |
| 105 | + fn iter_anchors_ext( |
| 106 | + &self, |
| 107 | + ) -> Box<dyn Iterator<Item = ((Txid, BlockHash), ConfirmationBlockTime)> + '_> { |
| 108 | + Box::new(self.full_txs().flat_map(move |tx_node| { |
| 109 | + tx_node.anchors.iter().map(move |anchor| { |
| 110 | + let block_id = anchor.block_id; |
| 111 | + ((tx_node.txid, block_id.hash), *anchor) |
| 112 | + }) |
| 113 | + })) |
| 114 | + } |
| 115 | +} |
| 116 | + |
97 | 117 | fn main() -> anyhow::Result<()> {
|
98 | 118 | let example_cli::Init {
|
99 | 119 | args,
|
@@ -126,6 +146,13 @@ fn main() -> anyhow::Result<()> {
|
126 | 146 |
|
127 | 147 | let client = BdkElectrumClient::new(electrum_cmd.electrum_args().client(network)?);
|
128 | 148 |
|
| 149 | + // Lock the graph so we can safely borrow data from it, |
| 150 | + // and extract all anchor data in a public-friendly format using the extension trait. |
| 151 | + // This avoids re-fetching known anchor confirmations from Electrum. |
| 152 | + let g = graph.lock().unwrap(); |
| 153 | + let anchors = g.graph().iter_anchors_ext(); |
| 154 | + client.populate_anchor_cache(anchors); |
| 155 | + |
129 | 156 | // Tell the electrum client about the txs we've already got locally so it doesn't re-download
|
130 | 157 | // them
|
131 | 158 | client.populate_tx_cache(
|
|
0 commit comments