1 use crate::common::{ConfirmedTx, SyncState, FilterQueue};
2 use crate::error::{TxSyncError, InternalError};
4 use electrum_client::Client as ElectrumClient;
5 use electrum_client::ElectrumApi;
6 use electrum_client::GetMerkleRes;
8 use lightning::util::logger::Logger;
9 use lightning::{log_error, log_debug, log_trace};
10 use lightning::chain::WatchedOutput;
11 use lightning::chain::{Confirm, Filter};
13 use bitcoin::{BlockHash, Script, Transaction, Txid};
14 use bitcoin::block::Header;
15 use bitcoin::hash_types::TxMerkleNode;
16 use bitcoin::hashes::Hash;
17 use bitcoin::hashes::sha256d::Hash as Sha256d;
21 use std::collections::HashSet;
22 use std::time::Instant;
24 /// Synchronizes LDK with a given Electrum server.
26 /// Needs to be registered with a [`ChainMonitor`] via the [`Filter`] interface to be informed of
27 /// transactions and outputs to monitor for on-chain confirmation, unconfirmation, and
30 /// Note that registration via [`Filter`] needs to happen before any calls to
31 /// [`Watch::watch_channel`] to ensure we get notified of the items to monitor.
33 /// [`ChainMonitor`]: lightning::chain::chainmonitor::ChainMonitor
34 /// [`Watch::watch_channel`]: lightning::chain::Watch::watch_channel
35 /// [`Filter`]: lightning::chain::Filter
36 pub struct ElectrumSyncClient<L: Deref>
40 sync_state: Mutex<SyncState>,
41 queue: Mutex<FilterQueue>,
42 client: ElectrumClient,
46 impl<L: Deref> ElectrumSyncClient<L>
50 /// Returns a new [`ElectrumSyncClient`] object.
51 pub fn new(server_url: String, logger: L) -> Result<Self, TxSyncError> {
52 let client = ElectrumClient::new(&server_url).map_err(|e| {
53 log_error!(logger, "Failed to connect to electrum server '{}': {}", server_url, e);
57 Self::from_client(client, logger)
60 /// Returns a new [`ElectrumSyncClient`] object using the given Electrum client.
62 /// This is not exported to bindings users as the underlying client from BDK is not exported.
63 pub fn from_client(client: ElectrumClient, logger: L) -> Result<Self, TxSyncError> {
64 let sync_state = Mutex::new(SyncState::new());
65 let queue = Mutex::new(FilterQueue::new());
75 /// Synchronizes the given `confirmables` via their [`Confirm`] interface implementations. This
76 /// method should be called regularly to keep LDK up-to-date with current chain data.
78 /// For example, instances of [`ChannelManager`] and [`ChainMonitor`] can be informed about the
79 /// newest on-chain activity related to the items previously registered via the [`Filter`]
82 /// [`Confirm`]: lightning::chain::Confirm
83 /// [`ChainMonitor`]: lightning::chain::chainmonitor::ChainMonitor
84 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
85 /// [`Filter`]: lightning::chain::Filter
86 pub fn sync(&self, confirmables: Vec<&(dyn Confirm + Sync + Send)>) -> Result<(), TxSyncError> {
87 // This lock makes sure we're syncing once at a time.
88 let mut sync_state = self.sync_state.lock().unwrap();
90 log_trace!(self.logger, "Starting transaction sync.");
91 #[cfg(feature = "time")]
92 let start_time = Instant::now();
93 let mut num_confirmed = 0;
94 let mut num_unconfirmed = 0;
96 // Clear any header notifications we might have gotten to keep the queue count low.
97 while let Some(_) = self.client.block_headers_pop()? {}
99 let tip_notification = self.client.block_headers_subscribe()?;
100 let mut tip_header = tip_notification.header;
101 let mut tip_height = tip_notification.height as u32;
104 let pending_registrations = self.queue.lock().unwrap().process_queues(&mut sync_state);
105 let tip_is_new = Some(tip_header.block_hash()) != sync_state.last_sync_hash;
107 // We loop until any registered transactions have been processed at least once, or the
108 // tip hasn't been updated during the last iteration.
109 if !sync_state.pending_sync && !pending_registrations && !tip_is_new {
113 // Update the known tip to the newest one.
115 // First check for any unconfirmed transactions and act on it immediately.
116 match self.get_unconfirmed_transactions(&confirmables) {
117 Ok(unconfirmed_txs) => {
118 // Double-check the tip hash. If it changed, a reorg happened since
119 // we started syncing and we need to restart last-minute.
120 match self.check_update_tip(&mut tip_header, &mut tip_height) {
122 num_unconfirmed += unconfirmed_txs.len();
123 sync_state.sync_unconfirmed_transactions(
129 log_debug!(self.logger,
130 "Encountered inconsistency during transaction sync, restarting.");
131 sync_state.pending_sync = true;
135 // (Semi-)permanent failure, retry later.
136 log_error!(self.logger,
137 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
141 sync_state.pending_sync = true;
142 return Err(TxSyncError::from(err));
147 // (Semi-)permanent failure, retry later.
148 log_error!(self.logger,
149 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
153 sync_state.pending_sync = true;
154 return Err(TxSyncError::from(err));
158 // Update the best block.
159 for c in &confirmables {
160 c.best_block_updated(&tip_header, tip_height);
163 // Prune any sufficiently confirmed output spends
164 sync_state.prune_output_spends(tip_height);
167 match self.get_confirmed_transactions(&sync_state) {
168 Ok(confirmed_txs) => {
169 // Double-check the tip hash. If it changed, a reorg happened since
170 // we started syncing and we need to restart last-minute.
171 match self.check_update_tip(&mut tip_header, &mut tip_height) {
173 num_confirmed += confirmed_txs.len();
174 sync_state.sync_confirmed_transactions(
180 log_debug!(self.logger,
181 "Encountered inconsistency during transaction sync, restarting.");
182 sync_state.pending_sync = true;
186 // (Semi-)permanent failure, retry later.
187 log_error!(self.logger,
188 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
192 sync_state.pending_sync = true;
193 return Err(TxSyncError::from(err));
197 Err(InternalError::Inconsistency) => {
198 // Immediately restart syncing when we encounter any inconsistencies.
199 log_debug!(self.logger,
200 "Encountered inconsistency during transaction sync, restarting.");
201 sync_state.pending_sync = true;
205 // (Semi-)permanent failure, retry later.
206 log_error!(self.logger,
207 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
211 sync_state.pending_sync = true;
212 return Err(TxSyncError::from(err));
215 sync_state.last_sync_hash = Some(tip_header.block_hash());
216 sync_state.pending_sync = false;
219 #[cfg(feature = "time")]
220 log_debug!(self.logger,
221 "Finished transaction sync at tip {} in {}ms: {} confirmed, {} unconfirmed.",
222 tip_header.block_hash(), start_time.elapsed().as_millis(), num_confirmed,
224 #[cfg(not(feature = "time"))]
225 log_debug!(self.logger,
226 "Finished transaction sync at tip {}: {} confirmed, {} unconfirmed.",
227 tip_header.block_hash(), num_confirmed, num_unconfirmed);
231 fn check_update_tip(&self, cur_tip_header: &mut Header, cur_tip_height: &mut u32)
232 -> Result<bool, InternalError>
234 let check_notification = self.client.block_headers_subscribe()?;
235 let check_tip_hash = check_notification.header.block_hash();
237 // Restart if either the tip changed or we got some divergent tip
238 // change notification since we started. In the latter case we
239 // make sure we clear the queue before continuing.
240 let mut restart_sync = check_tip_hash != cur_tip_header.block_hash();
241 while let Some(queued_notif) = self.client.block_headers_pop()? {
242 if queued_notif.header.block_hash() != check_tip_hash {
248 *cur_tip_header = check_notification.header;
249 *cur_tip_height = check_notification.height as u32;
256 fn get_confirmed_transactions(
257 &self, sync_state: &SyncState,
258 ) -> Result<Vec<ConfirmedTx>, InternalError> {
260 // First, check the confirmation status of registered transactions as well as the
261 // status of dependent transactions of registered outputs.
262 let mut confirmed_txs: Vec<ConfirmedTx> = Vec::new();
263 let mut watched_script_pubkeys = Vec::with_capacity(
264 sync_state.watched_transactions.len() + sync_state.watched_outputs.len());
265 let mut watched_txs = Vec::with_capacity(sync_state.watched_transactions.len());
267 for txid in &sync_state.watched_transactions {
268 match self.client.transaction_get(&txid) {
270 watched_txs.push((txid, tx.clone()));
271 if let Some(tx_out) = tx.output.first() {
272 // We watch an arbitrary output of the transaction of interest in order to
273 // retrieve the associated script history, before narrowing down our search
274 // through `filter`ing by `txid` below.
275 watched_script_pubkeys.push(tx_out.script_pubkey.clone());
277 debug_assert!(false, "Failed due to retrieving invalid tx data.");
278 log_error!(self.logger, "Failed due to retrieving invalid tx data.");
279 return Err(InternalError::Failed);
282 Err(electrum_client::Error::Protocol(_)) => {
283 // We couldn't find the tx, do nothing.
286 log_error!(self.logger, "Failed to look up transaction {}: {}.", txid, e);
287 return Err(InternalError::Failed);
292 let num_tx_lookups = watched_script_pubkeys.len();
293 debug_assert_eq!(num_tx_lookups, watched_txs.len());
295 for output in sync_state.watched_outputs.values() {
296 watched_script_pubkeys.push(output.script_pubkey.clone());
299 let num_output_spend_lookups = watched_script_pubkeys.len() - num_tx_lookups;
300 debug_assert_eq!(num_output_spend_lookups, sync_state.watched_outputs.len());
302 match self.client.batch_script_get_history(watched_script_pubkeys.iter().map(|s| s.deref()))
305 let (tx_results, output_results) = results.split_at(num_tx_lookups);
306 debug_assert_eq!(num_output_spend_lookups, output_results.len());
308 for (i, script_history) in tx_results.iter().enumerate() {
309 let (txid, tx) = &watched_txs[i];
310 if confirmed_txs.iter().any(|ctx| ctx.txid == **txid) {
313 let mut filtered_history = script_history.iter().filter(|h| h.tx_hash == **txid);
314 if let Some(history) = filtered_history.next()
316 let prob_conf_height = history.height as u32;
317 let confirmed_tx = self.get_confirmed_tx(tx, prob_conf_height)?;
318 confirmed_txs.push(confirmed_tx);
320 debug_assert!(filtered_history.next().is_none());
323 for (watched_output, script_history) in sync_state.watched_outputs.values()
326 for possible_output_spend in script_history {
327 if possible_output_spend.height <= 0 {
331 let txid = possible_output_spend.tx_hash;
332 if confirmed_txs.iter().any(|ctx| ctx.txid == txid) {
336 match self.client.transaction_get(&txid) {
338 let mut is_spend = false;
339 for txin in &tx.input {
340 let watched_outpoint = watched_output.outpoint
341 .into_bitcoin_outpoint();
342 if txin.previous_output == watched_outpoint {
352 let prob_conf_height = possible_output_spend.height as u32;
353 let confirmed_tx = self.get_confirmed_tx(&tx, prob_conf_height)?;
354 confirmed_txs.push(confirmed_tx);
357 log_trace!(self.logger,
358 "Inconsistency: Tx {} was unconfirmed during syncing: {}",
360 return Err(InternalError::Inconsistency);
367 log_error!(self.logger, "Failed to look up script histories: {}.", e);
368 return Err(InternalError::Failed);
372 // Sort all confirmed transactions first by block height, then by in-block
373 // position, and finally feed them to the interface in order.
374 confirmed_txs.sort_unstable_by(|tx1, tx2| {
375 tx1.block_height.cmp(&tx2.block_height).then_with(|| tx1.pos.cmp(&tx2.pos))
381 fn get_unconfirmed_transactions(
382 &self, confirmables: &Vec<&(dyn Confirm + Sync + Send)>,
383 ) -> Result<Vec<Txid>, InternalError> {
384 // Query the interface for relevant txids and check whether the relevant blocks are still
385 // in the best chain, mark them unconfirmed otherwise
386 let relevant_txids = confirmables
388 .flat_map(|c| c.get_relevant_txids())
389 .collect::<HashSet<(Txid, u32, Option<BlockHash>)>>();
391 let mut unconfirmed_txs = Vec::new();
393 for (txid, conf_height, block_hash_opt) in relevant_txids {
394 if let Some(block_hash) = block_hash_opt {
395 let block_header = self.client.block_header(conf_height as usize)?;
396 if block_header.block_hash() == block_hash {
397 // Skip if the tx is still confirmed in the block in question.
401 unconfirmed_txs.push(txid);
403 log_error!(self.logger,
404 "Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!");
405 panic!("Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!");
411 fn get_confirmed_tx(&self, tx: &Transaction, prob_conf_height: u32)
412 -> Result<ConfirmedTx, InternalError>
414 let txid = tx.txid();
415 match self.client.transaction_get_merkle(&txid, prob_conf_height as usize) {
417 debug_assert_eq!(prob_conf_height, merkle_res.block_height as u32);
418 match self.client.block_header(prob_conf_height as usize) {
419 Ok(block_header) => {
420 let pos = merkle_res.pos;
421 if !self.validate_merkle_proof(&txid,
422 &block_header.merkle_root, merkle_res)?
424 log_trace!(self.logger,
425 "Inconsistency: Block {} was unconfirmed during syncing.",
426 block_header.block_hash());
427 return Err(InternalError::Inconsistency);
429 let confirmed_tx = ConfirmedTx {
432 block_header, block_height: prob_conf_height,
438 log_error!(self.logger,
439 "Failed to retrieve block header for height {}: {}.",
440 prob_conf_height, e);
441 Err(InternalError::Failed)
446 log_trace!(self.logger,
447 "Inconsistency: Tx {} was unconfirmed during syncing: {}",
449 Err(InternalError::Inconsistency)
454 /// Returns a reference to the underlying Electrum client.
456 /// This is not exported to bindings users as the underlying client from BDK is not exported.
457 pub fn client(&self) -> &ElectrumClient {
461 fn validate_merkle_proof(&self, txid: &Txid, merkle_root: &TxMerkleNode,
462 merkle_res: GetMerkleRes) -> Result<bool, InternalError>
464 let mut index = merkle_res.pos;
465 let mut cur = txid.to_raw_hash();
466 for mut bytes in merkle_res.merkle {
468 // unwrap() safety: `bytes` has len 32 so `from_slice` can never fail.
469 let next_hash = Sha256d::from_slice(&bytes).unwrap();
470 let (left, right) = if index % 2 == 0 {
476 let data = [&left[..], &right[..]].concat();
477 cur = Sha256d::hash(&data);
481 Ok(cur == merkle_root.to_raw_hash())
485 impl<L: Deref> Filter for ElectrumSyncClient<L>
489 fn register_tx(&self, txid: &Txid, _script_pubkey: &Script) {
490 let mut locked_queue = self.queue.lock().unwrap();
491 locked_queue.transactions.insert(*txid);
494 fn register_output(&self, output: WatchedOutput) {
495 let mut locked_queue = self.queue.lock().unwrap();
496 locked_queue.outputs.insert(output.outpoint.into_bitcoin_outpoint(), output);