1 use crate::error::{TxSyncError, InternalError};
2 use crate::common::{SyncState, FilterQueue, ConfirmedTx};
4 use lightning::util::logger::Logger;
5 use lightning::{log_error, log_debug, log_trace};
6 use lightning::chain::WatchedOutput;
7 use lightning::chain::{Confirm, Filter};
9 use bitcoin::{BlockHash, Script, Txid};
11 use esplora_client::Builder;
12 #[cfg(feature = "async-interface")]
13 use esplora_client::r#async::AsyncClient;
14 #[cfg(not(feature = "async-interface"))]
15 use esplora_client::blocking::BlockingClient;
17 use std::collections::HashSet;
20 /// Synchronizes LDK with a given [`Esplora`] server.
22 /// Needs to be registered with a [`ChainMonitor`] via the [`Filter`] interface to be informed of
23 /// transactions and outputs to monitor for on-chain confirmation, unconfirmation, and
26 /// Note that registration via [`Filter`] needs to happen before any calls to
27 /// [`Watch::watch_channel`] to ensure we get notified of the items to monitor.
29 /// This uses and exposes either a blocking or async client variant dependent on whether the
30 /// `esplora-blocking` or the `esplora-async` feature is enabled.
32 /// [`Esplora`]: https://github.com/Blockstream/electrs
33 /// [`ChainMonitor`]: lightning::chain::chainmonitor::ChainMonitor
34 /// [`Watch::watch_channel`]: lightning::chain::Watch::watch_channel
35 /// [`Filter`]: lightning::chain::Filter
36 pub struct EsploraSyncClient<L: Deref>
40 sync_state: MutexType<SyncState>,
41 queue: std::sync::Mutex<FilterQueue>,
42 client: EsploraClientType,
46 impl<L: Deref> EsploraSyncClient<L>
50 /// Returns a new [`EsploraSyncClient`] object.
51 pub fn new(server_url: String, logger: L) -> Self {
52 let builder = Builder::new(&server_url);
53 #[cfg(not(feature = "async-interface"))]
54 let client = builder.build_blocking();
55 #[cfg(feature = "async-interface")]
56 let client = builder.build_async().unwrap();
58 EsploraSyncClient::from_client(client, logger)
61 /// Returns a new [`EsploraSyncClient`] object using the given Esplora client.
63 /// This is not exported to bindings users as the underlying client from BDK is not exported.
64 pub fn from_client(client: EsploraClientType, logger: L) -> Self {
65 let sync_state = MutexType::new(SyncState::new());
66 let queue = std::sync::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
87 pub fn sync<C: Deref>(&self, confirmables: Vec<C>) -> Result<(), TxSyncError>
88 where C::Target: Confirm
90 // This lock makes sure we're syncing once at a time.
91 #[cfg(not(feature = "async-interface"))]
92 let mut sync_state = self.sync_state.lock().unwrap();
93 #[cfg(feature = "async-interface")]
94 let mut sync_state = self.sync_state.lock().await;
96 log_trace!(self.logger, "Starting transaction sync.");
97 #[cfg(feature = "time")]
98 let start_time = std::time::Instant::now();
99 let mut num_confirmed = 0;
100 let mut num_unconfirmed = 0;
102 let mut tip_hash = maybe_await!(self.client.get_tip_hash())?;
105 let pending_registrations = self.queue.lock().unwrap().process_queues(&mut sync_state);
106 let tip_is_new = Some(tip_hash) != sync_state.last_sync_hash;
108 // We loop until any registered transactions have been processed at least once, or the
109 // tip hasn't been updated during the last iteration.
110 if !sync_state.pending_sync && !pending_registrations && !tip_is_new {
114 // Update the known tip to the newest one.
116 // First check for any unconfirmed transactions and act on it immediately.
117 match maybe_await!(self.get_unconfirmed_transactions(&confirmables)) {
118 Ok(unconfirmed_txs) => {
119 // Double-check the tip hash. If it changed, a reorg happened since
120 // we started syncing and we need to restart last-minute.
121 match maybe_await!(self.client.get_tip_hash()) {
122 Ok(check_tip_hash) => {
123 if check_tip_hash != tip_hash {
124 tip_hash = check_tip_hash;
126 log_debug!(self.logger, "Encountered inconsistency during transaction sync, restarting.");
127 sync_state.pending_sync = true;
130 num_unconfirmed += unconfirmed_txs.len();
131 sync_state.sync_unconfirmed_transactions(
137 // (Semi-)permanent failure, retry later.
138 log_error!(self.logger,
139 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
143 sync_state.pending_sync = true;
144 return Err(TxSyncError::from(err));
149 // (Semi-)permanent failure, retry later.
150 log_error!(self.logger,
151 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
155 sync_state.pending_sync = true;
156 return Err(TxSyncError::from(err));
160 match maybe_await!(self.sync_best_block_updated(&confirmables, &mut sync_state, &tip_hash)) {
162 Err(InternalError::Inconsistency) => {
163 // Immediately restart syncing when we encounter any inconsistencies.
164 log_debug!(self.logger, "Encountered inconsistency during transaction sync, restarting.");
165 sync_state.pending_sync = true;
169 // (Semi-)permanent failure, retry later.
170 log_error!(self.logger,
171 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
175 sync_state.pending_sync = true;
176 return Err(TxSyncError::from(err));
181 match maybe_await!(self.get_confirmed_transactions(&sync_state)) {
182 Ok(confirmed_txs) => {
183 // Double-check the tip hash. If it changed, a reorg happened since
184 // we started syncing and we need to restart last-minute.
185 match maybe_await!(self.client.get_tip_hash()) {
186 Ok(check_tip_hash) => {
187 if check_tip_hash != tip_hash {
188 tip_hash = check_tip_hash;
190 log_debug!(self.logger,
191 "Encountered inconsistency during transaction sync, restarting.");
192 sync_state.pending_sync = true;
195 num_confirmed += confirmed_txs.len();
196 sync_state.sync_confirmed_transactions(
202 // (Semi-)permanent failure, retry later.
203 log_error!(self.logger,
204 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
208 sync_state.pending_sync = true;
209 return Err(TxSyncError::from(err));
213 Err(InternalError::Inconsistency) => {
214 // Immediately restart syncing when we encounter any inconsistencies.
215 log_debug!(self.logger, "Encountered inconsistency during transaction sync, restarting.");
216 sync_state.pending_sync = true;
220 // (Semi-)permanent failure, retry later.
221 log_error!(self.logger,
222 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
226 sync_state.pending_sync = true;
227 return Err(TxSyncError::from(err));
230 sync_state.last_sync_hash = Some(tip_hash);
231 sync_state.pending_sync = false;
234 #[cfg(feature = "time")]
235 log_debug!(self.logger, "Finished transaction sync at tip {} in {}ms: {} confirmed, {} unconfirmed.",
236 tip_hash, start_time.elapsed().as_millis(), num_confirmed, num_unconfirmed);
237 #[cfg(not(feature = "time"))]
238 log_debug!(self.logger, "Finished transaction sync at tip {}: {} confirmed, {} unconfirmed.",
239 tip_hash, num_confirmed, num_unconfirmed);
244 fn sync_best_block_updated<C: Deref>(
245 &self, confirmables: &Vec<C>, sync_state: &mut SyncState, tip_hash: &BlockHash,
246 ) -> Result<(), InternalError>
247 where C::Target: Confirm
249 // Inform the interface of the new block.
250 let tip_header = maybe_await!(self.client.get_header_by_hash(tip_hash))?;
251 let tip_status = maybe_await!(self.client.get_block_status(&tip_hash))?;
252 if tip_status.in_best_chain {
253 if let Some(tip_height) = tip_status.height {
254 for c in confirmables {
255 c.best_block_updated(&tip_header, tip_height);
258 // Prune any sufficiently confirmed output spends
259 sync_state.prune_output_spends(tip_height);
262 return Err(InternalError::Inconsistency);
268 fn get_confirmed_transactions(
269 &self, sync_state: &SyncState,
270 ) -> Result<Vec<ConfirmedTx>, InternalError> {
272 // First, check the confirmation status of registered transactions as well as the
273 // status of dependent transactions of registered outputs.
275 let mut confirmed_txs: Vec<ConfirmedTx> = Vec::new();
277 for txid in &sync_state.watched_transactions {
278 if confirmed_txs.iter().any(|ctx| ctx.txid == *txid) {
281 if let Some(confirmed_tx) = maybe_await!(self.get_confirmed_tx(*txid, None, None))? {
282 confirmed_txs.push(confirmed_tx);
286 for (_, output) in &sync_state.watched_outputs {
287 if let Some(output_status) = maybe_await!(self.client
288 .get_output_status(&output.outpoint.txid, output.outpoint.index as u64))?
290 if let Some(spending_txid) = output_status.txid {
291 if let Some(spending_tx_status) = output_status.status {
292 if confirmed_txs.iter().any(|ctx| ctx.txid == spending_txid) {
293 if spending_tx_status.confirmed {
294 // Skip inserting duplicate ConfirmedTx entry
297 log_trace!(self.logger, "Inconsistency: Detected previously-confirmed Tx {} as unconfirmed", spending_txid);
298 return Err(InternalError::Inconsistency);
302 if let Some(confirmed_tx) = maybe_await!(self
305 spending_tx_status.block_hash,
306 spending_tx_status.block_height,
309 confirmed_txs.push(confirmed_tx);
316 // Sort all confirmed transactions first by block height, then by in-block
317 // position, and finally feed them to the interface in order.
318 confirmed_txs.sort_unstable_by(|tx1, tx2| {
319 tx1.block_height.cmp(&tx2.block_height).then_with(|| tx1.pos.cmp(&tx2.pos))
327 &self, txid: Txid, expected_block_hash: Option<BlockHash>, known_block_height: Option<u32>,
328 ) -> Result<Option<ConfirmedTx>, InternalError> {
329 if let Some(merkle_block) = maybe_await!(self.client.get_merkle_block(&txid))? {
330 let block_header = merkle_block.header;
331 let block_hash = block_header.block_hash();
332 if let Some(expected_block_hash) = expected_block_hash {
333 if expected_block_hash != block_hash {
334 log_trace!(self.logger, "Inconsistency: Tx {} expected in block {}, but is confirmed in {}", txid, expected_block_hash, block_hash);
335 return Err(InternalError::Inconsistency);
339 let mut matches = Vec::new();
340 let mut indexes = Vec::new();
341 let _ = merkle_block.txn.extract_matches(&mut matches, &mut indexes);
342 if indexes.len() != 1 || matches.len() != 1 || matches[0] != txid {
343 log_error!(self.logger, "Retrieved Merkle block for txid {} doesn't match expectations. This should not happen. Please verify server integrity.", txid);
344 return Err(InternalError::Failed);
347 // unwrap() safety: len() > 0 is checked above
348 let pos = *indexes.first().unwrap() as usize;
349 if let Some(tx) = maybe_await!(self.client.get_tx(&txid))? {
350 if tx.txid() != txid {
351 log_error!(self.logger, "Retrieved transaction for txid {} doesn't match expectations. This should not happen. Please verify server integrity.", txid);
352 return Err(InternalError::Failed);
355 if let Some(block_height) = known_block_height {
356 // We can take a shortcut here if a previous call already gave us the height.
357 return Ok(Some(ConfirmedTx { tx, txid, block_header, pos, block_height }));
360 let block_status = maybe_await!(self.client.get_block_status(&block_hash))?;
361 if let Some(block_height) = block_status.height {
362 return Ok(Some(ConfirmedTx { tx, txid, block_header, pos, block_height }));
364 // If any previously-confirmed block suddenly is no longer confirmed, we found
365 // an inconsistency and should start over.
366 log_trace!(self.logger, "Inconsistency: Tx {} was unconfirmed during syncing.", txid);
367 return Err(InternalError::Inconsistency);
375 fn get_unconfirmed_transactions<C: Deref>(
376 &self, confirmables: &Vec<C>,
377 ) -> Result<Vec<Txid>, InternalError>
378 where C::Target: Confirm
380 // Query the interface for relevant txids and check whether the relevant blocks are still
381 // in the best chain, mark them unconfirmed otherwise
382 let relevant_txids = confirmables
384 .flat_map(|c| c.get_relevant_txids())
385 .collect::<HashSet<(Txid, u32, Option<BlockHash>)>>();
387 let mut unconfirmed_txs = Vec::new();
389 for (txid, _conf_height, block_hash_opt) in relevant_txids {
390 if let Some(block_hash) = block_hash_opt {
391 let block_status = maybe_await!(self.client.get_block_status(&block_hash))?;
392 if block_status.in_best_chain {
393 // Skip if the block in question is still confirmed.
397 unconfirmed_txs.push(txid);
399 log_error!(self.logger, "Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!");
400 panic!("Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!");
406 /// Returns a reference to the underlying esplora client.
408 /// This is not exported to bindings users as the underlying client from BDK is not exported.
409 pub fn client(&self) -> &EsploraClientType {
414 #[cfg(feature = "async-interface")]
415 type MutexType<I> = futures::lock::Mutex<I>;
416 #[cfg(not(feature = "async-interface"))]
417 type MutexType<I> = std::sync::Mutex<I>;
419 // The underlying client type.
420 #[cfg(feature = "async-interface")]
421 type EsploraClientType = AsyncClient;
422 #[cfg(not(feature = "async-interface"))]
423 type EsploraClientType = BlockingClient;
426 impl<L: Deref> Filter for EsploraSyncClient<L>
430 fn register_tx(&self, txid: &Txid, _script_pubkey: &Script) {
431 let mut locked_queue = self.queue.lock().unwrap();
432 locked_queue.transactions.insert(*txid);
435 fn register_output(&self, output: WatchedOutput) {
436 let mut locked_queue = self.queue.lock().unwrap();
437 locked_queue.outputs.insert(output.outpoint.into_bitcoin_outpoint(), output);