2e35a150c558a2123706ca06af7b56c4952ff85e
[rust-lightning] / lightning-transaction-sync / src / esplora.rs
1 use crate::error::{TxSyncError, InternalError};
2 use crate::common::{SyncState, FilterQueue, ConfirmedTx};
3
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};
8
9 use bitcoin::{BlockHash, Script, Txid};
10
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;
16
17 use std::collections::HashSet;
18 use core::ops::Deref;
19
20 /// Synchronizes LDK with a given [`Esplora`] server.
21 ///
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
24 /// reconfirmation.
25 ///
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.
28 ///
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.
31 ///
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>
37 where
38         L::Target: Logger,
39 {
40         sync_state: MutexType<SyncState>,
41         queue: std::sync::Mutex<FilterQueue>,
42         client: EsploraClientType,
43         logger: L,
44 }
45
46 impl<L: Deref> EsploraSyncClient<L>
47 where
48         L::Target: Logger,
49 {
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();
57
58                 EsploraSyncClient::from_client(client, logger)
59         }
60
61         /// Returns a new [`EsploraSyncClient`] object using the given Esplora client.
62         ///
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());
67                 Self {
68                         sync_state,
69                         queue,
70                         client,
71                         logger,
72                 }
73         }
74
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.
77         ///
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`]
80         /// interface.
81         ///
82         /// [`Confirm`]: lightning::chain::Confirm
83         /// [`ChainMonitor`]: lightning::chain::chainmonitor::ChainMonitor
84         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
85         /// [`Filter`]: lightning::chain::Filter
86         #[maybe_async]
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;
93
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;
99
100                 let mut tip_hash = maybe_await!(self.client.get_tip_hash())?;
101
102                 loop {
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;
105
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 {
109                                 // Nothing to do.
110                                 break;
111                         } else {
112                                 // Update the known tip to the newest one.
113                                 if tip_is_new {
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;
123
124                                                                                 log_debug!(self.logger, "Encountered inconsistency during transaction sync, restarting.");
125                                                                                 sync_state.pending_sync = true;
126                                                                                 continue;
127                                                                         }
128                                                                         num_unconfirmed += unconfirmed_txs.len();
129                                                                         sync_state.sync_unconfirmed_transactions(
130                                                                                 &confirmables,
131                                                                                 unconfirmed_txs
132                                                                         );
133                                                                 }
134                                                                 Err(err) => {
135                                                                         // (Semi-)permanent failure, retry later.
136                                                                         log_error!(self.logger,
137                                                                                 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
138                                                                                 num_confirmed,
139                                                                                 num_unconfirmed
140                                                                                 );
141                                                                         sync_state.pending_sync = true;
142                                                                         return Err(TxSyncError::from(err));
143                                                                 }
144                                                         }
145                                                 },
146                                                 Err(err) => {
147                                                         // (Semi-)permanent failure, retry later.
148                                                         log_error!(self.logger,
149                                                                 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
150                                                                 num_confirmed,
151                                                                 num_unconfirmed
152                                                         );
153                                                         sync_state.pending_sync = true;
154                                                         return Err(TxSyncError::from(err));
155                                                 }
156                                         }
157
158                                         match maybe_await!(self.sync_best_block_updated(&confirmables, &mut sync_state, &tip_hash)) {
159                                                 Ok(()) => {}
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;
164                                                         continue;
165                                                 }
166                                                 Err(err) => {
167                                                         // (Semi-)permanent failure, retry later.
168                                                         log_error!(self.logger,
169                                                                 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
170                                                                 num_confirmed,
171                                                                 num_unconfirmed
172                                                         );
173                                                         sync_state.pending_sync = true;
174                                                         return Err(TxSyncError::from(err));
175                                                 }
176                                         }
177                                 }
178
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;
187
188                                                                         log_debug!(self.logger,
189                                                                                 "Encountered inconsistency during transaction sync, restarting.");
190                                                                         sync_state.pending_sync = true;
191                                                                         continue;
192                                                                 }
193                                                                 num_confirmed += confirmed_txs.len();
194                                                                 sync_state.sync_confirmed_transactions(
195                                                                         &confirmables,
196                                                                         confirmed_txs
197                                                                 );
198                                                         }
199                                                         Err(err) => {
200                                                                 // (Semi-)permanent failure, retry later.
201                                                                 log_error!(self.logger,
202                                                                         "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
203                                                                         num_confirmed,
204                                                                         num_unconfirmed
205                                                                 );
206                                                                 sync_state.pending_sync = true;
207                                                                 return Err(TxSyncError::from(err));
208                                                         }
209                                                 }
210                                         }
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;
215                                                 continue;
216                                         }
217                                         Err(err) => {
218                                                 // (Semi-)permanent failure, retry later.
219                                                 log_error!(self.logger,
220                                                         "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
221                                                         num_confirmed,
222                                                         num_unconfirmed
223                                                 );
224                                                 sync_state.pending_sync = true;
225                                                 return Err(TxSyncError::from(err));
226                                         }
227                                 }
228                                 sync_state.last_sync_hash = Some(tip_hash);
229                                 sync_state.pending_sync = false;
230                         }
231                 }
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);
238                 Ok(())
239         }
240
241         #[maybe_async]
242         fn sync_best_block_updated(
243                 &self, confirmables: &Vec<&(dyn Confirm + Sync + Send)>, sync_state: &mut SyncState, tip_hash: &BlockHash,
244         ) -> Result<(), InternalError> {
245
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);
253                                 }
254
255                                 // Prune any sufficiently confirmed output spends
256                                 sync_state.prune_output_spends(tip_height);
257                         }
258                 } else {
259                         return Err(InternalError::Inconsistency);
260                 }
261                 Ok(())
262         }
263
264         #[maybe_async]
265         fn get_confirmed_transactions(
266                 &self, sync_state: &SyncState,
267         ) -> Result<Vec<ConfirmedTx>, InternalError> {
268
269                 // First, check the confirmation status of registered transactions as well as the
270                 // status of dependent transactions of registered outputs.
271
272                 let mut confirmed_txs: Vec<ConfirmedTx> = Vec::new();
273
274                 for txid in &sync_state.watched_transactions {
275                         if confirmed_txs.iter().any(|ctx| ctx.txid == *txid) {
276                                 continue;
277                         }
278                         if let Some(confirmed_tx) = maybe_await!(self.get_confirmed_tx(*txid, None, None))? {
279                                 confirmed_txs.push(confirmed_tx);
280                         }
281                 }
282
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))?
286                         {
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
292                                                                 continue;
293                                                         } else {
294                                                                 log_trace!(self.logger, "Inconsistency: Detected previously-confirmed Tx {} as unconfirmed", spending_txid);
295                                                                 return Err(InternalError::Inconsistency);
296                                                         }
297                                                 }
298
299                                                 if let Some(confirmed_tx) = maybe_await!(self
300                                                         .get_confirmed_tx(
301                                                                 spending_txid,
302                                                                 spending_tx_status.block_hash,
303                                                                 spending_tx_status.block_height,
304                                                         ))?
305                                                 {
306                                                         confirmed_txs.push(confirmed_tx);
307                                                 }
308                                         }
309                                 }
310                         }
311                 }
312
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))
317                 });
318
319                 Ok(confirmed_txs)
320         }
321
322         #[maybe_async]
323         fn get_confirmed_tx(
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);
333                                 }
334                         }
335
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);
342                         }
343
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);
350                                 }
351
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 }));
355                                 }
356
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 }));
360                                 } else {
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);
365                                 }
366                         }
367                 }
368                 Ok(None)
369         }
370
371         #[maybe_async]
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
378                         .iter()
379                         .flat_map(|c| c.get_relevant_txids())
380                         .collect::<HashSet<(Txid, u32, Option<BlockHash>)>>();
381
382                 let mut unconfirmed_txs = Vec::new();
383
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.
389                                         continue;
390                                 }
391
392                                 unconfirmed_txs.push(txid);
393                         } else {
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!");
396                         }
397                 }
398                 Ok(unconfirmed_txs)
399         }
400
401         /// Returns a reference to the underlying esplora client.
402         ///
403         /// This is not exported to bindings users as the underlying client from BDK is not exported.
404         pub fn client(&self) -> &EsploraClientType {
405                 &self.client
406         }
407 }
408
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>;
413
414 // The underlying client type.
415 #[cfg(feature = "async-interface")]
416 type EsploraClientType = AsyncClient;
417 #[cfg(not(feature = "async-interface"))]
418 type EsploraClientType = BlockingClient;
419
420
421 impl<L: Deref> Filter for EsploraSyncClient<L>
422 where
423         L::Target: Logger,
424 {
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);
428         }
429
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);
433         }
434 }