Skip to content

Commit 1511cf4

Browse files
author
+Sharon
committed
Add populate_anchor_cache method to bdk
1 parent 8d9df97 commit 1511cf4

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

crates/electrum/src/bdk_electrum_client.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use bdk_core::{
77
BlockId, CheckPoint, ConfirmationBlockTime, TxUpdate,
88
};
99
use electrum_client::{ElectrumApi, Error, HeaderNotification};
10+
use std::convert::TryInto;
1011
use std::sync::{Arc, Mutex};
1112

1213
/// We include a chain suffix of a certain length for the purpose of robustness.
@@ -37,6 +38,20 @@ impl<E: ElectrumApi> BdkElectrumClient<E> {
3738
}
3839
}
3940

41+
/// Insert anchors into the anchor cache so that they don’t have to be fetched again from
42+
/// Electrum. Typically used to pre-populate the cache from an existing `TxGraph`.
43+
pub fn populate_anchor_cache(
44+
&self,
45+
tx_anchors: impl IntoIterator<Item = (Txid, impl IntoIterator<Item = ConfirmationBlockTime>)>,
46+
) {
47+
let mut cache = self.anchor_cache.lock().unwrap();
48+
for (txid, anchors) in tx_anchors {
49+
for anchor in anchors {
50+
cache.insert((txid, anchor.block_id.hash), anchor);
51+
}
52+
}
53+
}
54+
4055
/// Inserts transactions into the transaction cache so that the client will not fetch these
4156
/// transactions.
4257
pub fn populate_tx_cache(&self, txs: impl IntoIterator<Item = impl Into<Arc<Transaction>>>) {

examples/example_electrum/src/main.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,12 @@ fn main() -> anyhow::Result<()> {
125125
};
126126

127127
let client = BdkElectrumClient::new(electrum_cmd.electrum_args().client(network)?);
128-
128+
{
129+
// Lock graph mutex - released automatically at scope end
130+
// Cache all anchors while holding the lock
131+
let graph = graph.lock().unwrap();
132+
client.populate_anchor_cache(graph.graph().all_anchors().clone());
133+
}
129134
// Tell the electrum client about the txs we've already got locally so it doesn't re-download
130135
// them
131136
client.populate_tx_cache(

0 commit comments

Comments
 (0)