diff --git a/crates/electrum/src/bdk_electrum_client.rs b/crates/electrum/src/bdk_electrum_client.rs index 5962a5ec7..57e919aa9 100644 --- a/crates/electrum/src/bdk_electrum_client.rs +++ b/crates/electrum/src/bdk_electrum_client.rs @@ -7,6 +7,7 @@ use bdk_core::{ BlockId, CheckPoint, ConfirmationBlockTime, TxUpdate, }; use electrum_client::{ElectrumApi, Error, HeaderNotification}; +use std::convert::TryInto; use std::sync::{Arc, Mutex}; /// We include a chain suffix of a certain length for the purpose of robustness. @@ -37,6 +38,20 @@ impl BdkElectrumClient { } } + /// Insert anchors into the anchor cache so that they don’t have to be fetched again from + /// Electrum. Typically used to pre-populate the cache from an existing `TxGraph`. + pub fn populate_anchor_cache( + &self, + tx_anchors: impl IntoIterator)>, + ) { + let mut cache = self.anchor_cache.lock().unwrap(); + for (txid, anchors) in tx_anchors { + for anchor in anchors { + cache.insert((txid, anchor.block_id.hash), anchor); + } + } + } + /// Inserts transactions into the transaction cache so that the client will not fetch these /// transactions. pub fn populate_tx_cache(&self, txs: impl IntoIterator>>) { diff --git a/examples/example_electrum/src/main.rs b/examples/example_electrum/src/main.rs index 01d11e78b..78ccfe961 100644 --- a/examples/example_electrum/src/main.rs +++ b/examples/example_electrum/src/main.rs @@ -125,7 +125,12 @@ fn main() -> anyhow::Result<()> { }; let client = BdkElectrumClient::new(electrum_cmd.electrum_args().client(network)?); - + { + // Lock graph mutex - released automatically at scope end + // Cache all anchors while holding the lock + let graph = graph.lock().unwrap(); + client.populate_anchor_cache(graph.graph().all_anchors().clone()); + } // Tell the electrum client about the txs we've already got locally so it doesn't re-download // them client.populate_tx_cache(