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(&self, confirmables: Vec<&(dyn Confirm + Sync + Send)>) -> Result<(), TxSyncError> {
88 // This lock makes sure we're syncing once at a time.
89 #[cfg(not(feature = "async-interface"))]
90 let mut sync_state = self.sync_state.lock().unwrap();
91 #[cfg(feature = "async-interface")]
92 let mut sync_state = self.sync_state.lock().await;
94 log_trace!(self.logger, "Starting transaction sync.");
95 #[cfg(feature = "time")]
96 let start_time = std::time::Instant::now();
97 let mut num_confirmed = 0;
98 let mut num_unconfirmed = 0;
100 let mut tip_hash = maybe_await!(self.client.get_tip_hash())?;
103 let pending_registrations = self.queue.lock().unwrap().process_queues(&mut sync_state);
104 let tip_is_new = Some(tip_hash) != sync_state.last_sync_hash;
106 // We loop until any registered transactions have been processed at least once, or the
107 // tip hasn't been updated during the last iteration.
108 if !sync_state.pending_sync && !pending_registrations && !tip_is_new {
112 // Update the known tip to the newest one.
114 // First check for any unconfirmed transactions and act on it immediately.
115 match maybe_await!(self.get_unconfirmed_transactions(&confirmables)) {
116 Ok(unconfirmed_txs) => {
117 // Double-check the tip hash. If it changed, a reorg happened since
118 // we started syncing and we need to restart last-minute.
119 match maybe_await!(self.client.get_tip_hash()) {
120 Ok(check_tip_hash) => {
121 if check_tip_hash != tip_hash {
122 tip_hash = check_tip_hash;
124 log_debug!(self.logger, "Encountered inconsistency during transaction sync, restarting.");
125 sync_state.pending_sync = true;
128 num_unconfirmed += unconfirmed_txs.len();
129 sync_state.sync_unconfirmed_transactions(
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 match maybe_await!(self.sync_best_block_updated(&confirmables, &mut sync_state, &tip_hash)) {
160 Err(InternalError::Inconsistency) => {
161 // Immediately restart syncing when we encounter any inconsistencies.
162 log_debug!(self.logger, "Encountered inconsistency during transaction sync, restarting.");
163 sync_state.pending_sync = true;
167 // (Semi-)permanent failure, retry later.
168 log_error!(self.logger,
169 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
173 sync_state.pending_sync = true;
174 return Err(TxSyncError::from(err));
179 match maybe_await!(self.get_confirmed_transactions(&sync_state)) {
180 Ok(confirmed_txs) => {
181 // Double-check the tip hash. If it changed, a reorg happened since
182 // we started syncing and we need to restart last-minute.
183 match maybe_await!(self.client.get_tip_hash()) {
184 Ok(check_tip_hash) => {
185 if check_tip_hash != tip_hash {
186 tip_hash = check_tip_hash;
188 log_debug!(self.logger,
189 "Encountered inconsistency during transaction sync, restarting.");
190 sync_state.pending_sync = true;
193 num_confirmed += confirmed_txs.len();
194 sync_state.sync_confirmed_transactions(
200 // (Semi-)permanent failure, retry later.
201 log_error!(self.logger,
202 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
206 sync_state.pending_sync = true;
207 return Err(TxSyncError::from(err));
211 Err(InternalError::Inconsistency) => {
212 // Immediately restart syncing when we encounter any inconsistencies.
213 log_debug!(self.logger, "Encountered inconsistency during transaction sync, restarting.");
214 sync_state.pending_sync = true;
218 // (Semi-)permanent failure, retry later.
219 log_error!(self.logger,
220 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
224 sync_state.pending_sync = true;
225 return Err(TxSyncError::from(err));
228 sync_state.last_sync_hash = Some(tip_hash);
229 sync_state.pending_sync = false;
232 #[cfg(feature = "time")]
233 log_debug!(self.logger, "Finished transaction sync at tip {} in {}ms: {} confirmed, {} unconfirmed.",
234 tip_hash, start_time.elapsed().as_millis(), num_confirmed, num_unconfirmed);
235 #[cfg(not(feature = "time"))]
236 log_debug!(self.logger, "Finished transaction sync at tip {}: {} confirmed, {} unconfirmed.",
237 tip_hash, num_confirmed, num_unconfirmed);
242 fn sync_best_block_updated(
243 &self, confirmables: &Vec<&(dyn Confirm + Sync + Send)>, sync_state: &mut SyncState, tip_hash: &BlockHash,
244 ) -> Result<(), InternalError> {
246 // Inform the interface of the new block.
247 let tip_header = maybe_await!(self.client.get_header_by_hash(tip_hash))?;
248 let tip_status = maybe_await!(self.client.get_block_status(&tip_hash))?;
249 if tip_status.in_best_chain {
250 if let Some(tip_height) = tip_status.height {
251 for c in confirmables {
252 c.best_block_updated(&tip_header, tip_height);
255 // Prune any sufficiently confirmed output spends
256 sync_state.prune_output_spends(tip_height);
259 return Err(InternalError::Inconsistency);
265 fn get_confirmed_transactions(
266 &self, sync_state: &SyncState,
267 ) -> Result<Vec<ConfirmedTx>, InternalError> {
269 // First, check the confirmation status of registered transactions as well as the
270 // status of dependent transactions of registered outputs.
272 let mut confirmed_txs: Vec<ConfirmedTx> = Vec::new();
274 for txid in &sync_state.watched_transactions {
275 if confirmed_txs.iter().any(|ctx| ctx.txid == *txid) {
278 if let Some(confirmed_tx) = maybe_await!(self.get_confirmed_tx(*txid, None, None))? {
279 confirmed_txs.push(confirmed_tx);
283 for (_, output) in &sync_state.watched_outputs {
284 if let Some(output_status) = maybe_await!(self.client
285 .get_output_status(&output.outpoint.txid, output.outpoint.index as u64))?
287 if let Some(spending_txid) = output_status.txid {
288 if let Some(spending_tx_status) = output_status.status {
289 if confirmed_txs.iter().any(|ctx| ctx.txid == spending_txid) {
290 if spending_tx_status.confirmed {
291 // Skip inserting duplicate ConfirmedTx entry
294 log_trace!(self.logger, "Inconsistency: Detected previously-confirmed Tx {} as unconfirmed", spending_txid);
295 return Err(InternalError::Inconsistency);
299 if let Some(confirmed_tx) = maybe_await!(self
302 spending_tx_status.block_hash,
303 spending_tx_status.block_height,
306 confirmed_txs.push(confirmed_tx);
313 // Sort all confirmed transactions first by block height, then by in-block
314 // position, and finally feed them to the interface in order.
315 confirmed_txs.sort_unstable_by(|tx1, tx2| {
316 tx1.block_height.cmp(&tx2.block_height).then_with(|| tx1.pos.cmp(&tx2.pos))
324 &self, txid: Txid, expected_block_hash: Option<BlockHash>, known_block_height: Option<u32>,
325 ) -> Result<Option<ConfirmedTx>, InternalError> {
326 if let Some(merkle_block) = maybe_await!(self.client.get_merkle_block(&txid))? {
327 let block_header = merkle_block.header;
328 let block_hash = block_header.block_hash();
329 if let Some(expected_block_hash) = expected_block_hash {
330 if expected_block_hash != block_hash {
331 log_trace!(self.logger, "Inconsistency: Tx {} expected in block {}, but is confirmed in {}", txid, expected_block_hash, block_hash);
332 return Err(InternalError::Inconsistency);
336 let mut matches = Vec::new();
337 let mut indexes = Vec::new();
338 let _ = merkle_block.txn.extract_matches(&mut matches, &mut indexes);
339 if indexes.len() != 1 || matches.len() != 1 || matches[0] != txid {
340 log_error!(self.logger, "Retrieved Merkle block for txid {} doesn't match expectations. This should not happen. Please verify server integrity.", txid);
341 return Err(InternalError::Failed);
344 // unwrap() safety: len() > 0 is checked above
345 let pos = *indexes.first().unwrap() as usize;
346 if let Some(tx) = maybe_await!(self.client.get_tx(&txid))? {
347 if tx.txid() != txid {
348 log_error!(self.logger, "Retrieved transaction for txid {} doesn't match expectations. This should not happen. Please verify server integrity.", txid);
349 return Err(InternalError::Failed);
352 if let Some(block_height) = known_block_height {
353 // We can take a shortcut here if a previous call already gave us the height.
354 return Ok(Some(ConfirmedTx { tx, txid, block_header, pos, block_height }));
357 let block_status = maybe_await!(self.client.get_block_status(&block_hash))?;
358 if let Some(block_height) = block_status.height {
359 return Ok(Some(ConfirmedTx { tx, txid, block_header, pos, block_height }));
361 // If any previously-confirmed block suddenly is no longer confirmed, we found
362 // an inconsistency and should start over.
363 log_trace!(self.logger, "Inconsistency: Tx {} was unconfirmed during syncing.", txid);
364 return Err(InternalError::Inconsistency);
372 fn get_unconfirmed_transactions(
373 &self, confirmables: &Vec<&(dyn Confirm + Sync + Send)>,
374 ) -> Result<Vec<Txid>, InternalError> {
375 // Query the interface for relevant txids and check whether the relevant blocks are still
376 // in the best chain, mark them unconfirmed otherwise
377 let relevant_txids = confirmables
379 .flat_map(|c| c.get_relevant_txids())
380 .collect::<HashSet<(Txid, u32, Option<BlockHash>)>>();
382 let mut unconfirmed_txs = Vec::new();
384 for (txid, _conf_height, block_hash_opt) in relevant_txids {
385 if let Some(block_hash) = block_hash_opt {
386 let block_status = maybe_await!(self.client.get_block_status(&block_hash))?;
387 if block_status.in_best_chain {
388 // Skip if the block in question is still confirmed.
392 unconfirmed_txs.push(txid);
394 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!");
395 panic!("Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!");
401 /// Returns a reference to the underlying esplora client.
403 /// This is not exported to bindings users as the underlying client from BDK is not exported.
404 pub fn client(&self) -> &EsploraClientType {
409 #[cfg(feature = "async-interface")]
410 type MutexType<I> = futures::lock::Mutex<I>;
411 #[cfg(not(feature = "async-interface"))]
412 type MutexType<I> = std::sync::Mutex<I>;
414 // The underlying client type.
415 #[cfg(feature = "async-interface")]
416 type EsploraClientType = AsyncClient;
417 #[cfg(not(feature = "async-interface"))]
418 type EsploraClientType = BlockingClient;
421 impl<L: Deref> Filter for EsploraSyncClient<L>
425 fn register_tx(&self, txid: &Txid, _script_pubkey: &Script) {
426 let mut locked_queue = self.queue.lock().unwrap();
427 locked_queue.transactions.insert(*txid);
430 fn register_output(&self, output: WatchedOutput) {
431 let mut locked_queue = self.queue.lock().unwrap();
432 locked_queue.outputs.insert(output.outpoint.into_bitcoin_outpoint(), output);