]> git.bitcoin.ninja Git - rust-lightning/blob - lightning-transaction-sync/src/esplora.rs
Make `confirmables` `Deref`
[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<C: Deref>(&self, confirmables: Vec<C>) -> Result<(), TxSyncError>
88                 where C::Target: Confirm
89         {
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;
95
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;
101
102                 let mut tip_hash = maybe_await!(self.client.get_tip_hash())?;
103
104                 loop {
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;
107
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 {
111                                 // Nothing to do.
112                                 break;
113                         } else {
114                                 // Update the known tip to the newest one.
115                                 if tip_is_new {
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;
125
126                                                                                 log_debug!(self.logger, "Encountered inconsistency during transaction sync, restarting.");
127                                                                                 sync_state.pending_sync = true;
128                                                                                 continue;
129                                                                         }
130                                                                         num_unconfirmed += unconfirmed_txs.len();
131                                                                         sync_state.sync_unconfirmed_transactions(
132                                                                                 &confirmables,
133                                                                                 unconfirmed_txs
134                                                                         );
135                                                                 }
136                                                                 Err(err) => {
137                                                                         // (Semi-)permanent failure, retry later.
138                                                                         log_error!(self.logger,
139                                                                                 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
140                                                                                 num_confirmed,
141                                                                                 num_unconfirmed
142                                                                                 );
143                                                                         sync_state.pending_sync = true;
144                                                                         return Err(TxSyncError::from(err));
145                                                                 }
146                                                         }
147                                                 },
148                                                 Err(err) => {
149                                                         // (Semi-)permanent failure, retry later.
150                                                         log_error!(self.logger,
151                                                                 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
152                                                                 num_confirmed,
153                                                                 num_unconfirmed
154                                                         );
155                                                         sync_state.pending_sync = true;
156                                                         return Err(TxSyncError::from(err));
157                                                 }
158                                         }
159
160                                         match maybe_await!(self.sync_best_block_updated(&confirmables, &mut sync_state, &tip_hash)) {
161                                                 Ok(()) => {}
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;
166                                                         continue;
167                                                 }
168                                                 Err(err) => {
169                                                         // (Semi-)permanent failure, retry later.
170                                                         log_error!(self.logger,
171                                                                 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
172                                                                 num_confirmed,
173                                                                 num_unconfirmed
174                                                         );
175                                                         sync_state.pending_sync = true;
176                                                         return Err(TxSyncError::from(err));
177                                                 }
178                                         }
179                                 }
180
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;
189
190                                                                         log_debug!(self.logger,
191                                                                                 "Encountered inconsistency during transaction sync, restarting.");
192                                                                         sync_state.pending_sync = true;
193                                                                         continue;
194                                                                 }
195                                                                 num_confirmed += confirmed_txs.len();
196                                                                 sync_state.sync_confirmed_transactions(
197                                                                         &confirmables,
198                                                                         confirmed_txs
199                                                                 );
200                                                         }
201                                                         Err(err) => {
202                                                                 // (Semi-)permanent failure, retry later.
203                                                                 log_error!(self.logger,
204                                                                         "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
205                                                                         num_confirmed,
206                                                                         num_unconfirmed
207                                                                 );
208                                                                 sync_state.pending_sync = true;
209                                                                 return Err(TxSyncError::from(err));
210                                                         }
211                                                 }
212                                         }
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;
217                                                 continue;
218                                         }
219                                         Err(err) => {
220                                                 // (Semi-)permanent failure, retry later.
221                                                 log_error!(self.logger,
222                                                         "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
223                                                         num_confirmed,
224                                                         num_unconfirmed
225                                                 );
226                                                 sync_state.pending_sync = true;
227                                                 return Err(TxSyncError::from(err));
228                                         }
229                                 }
230                                 sync_state.last_sync_hash = Some(tip_hash);
231                                 sync_state.pending_sync = false;
232                         }
233                 }
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);
240                 Ok(())
241         }
242
243         #[maybe_async]
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
248         {
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);
256                                 }
257
258                                 // Prune any sufficiently confirmed output spends
259                                 sync_state.prune_output_spends(tip_height);
260                         }
261                 } else {
262                         return Err(InternalError::Inconsistency);
263                 }
264                 Ok(())
265         }
266
267         #[maybe_async]
268         fn get_confirmed_transactions(
269                 &self, sync_state: &SyncState,
270         ) -> Result<Vec<ConfirmedTx>, InternalError> {
271
272                 // First, check the confirmation status of registered transactions as well as the
273                 // status of dependent transactions of registered outputs.
274
275                 let mut confirmed_txs: Vec<ConfirmedTx> = Vec::new();
276
277                 for txid in &sync_state.watched_transactions {
278                         if confirmed_txs.iter().any(|ctx| ctx.txid == *txid) {
279                                 continue;
280                         }
281                         if let Some(confirmed_tx) = maybe_await!(self.get_confirmed_tx(*txid, None, None))? {
282                                 confirmed_txs.push(confirmed_tx);
283                         }
284                 }
285
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))?
289                         {
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
295                                                                 continue;
296                                                         } else {
297                                                                 log_trace!(self.logger, "Inconsistency: Detected previously-confirmed Tx {} as unconfirmed", spending_txid);
298                                                                 return Err(InternalError::Inconsistency);
299                                                         }
300                                                 }
301
302                                                 if let Some(confirmed_tx) = maybe_await!(self
303                                                         .get_confirmed_tx(
304                                                                 spending_txid,
305                                                                 spending_tx_status.block_hash,
306                                                                 spending_tx_status.block_height,
307                                                         ))?
308                                                 {
309                                                         confirmed_txs.push(confirmed_tx);
310                                                 }
311                                         }
312                                 }
313                         }
314                 }
315
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))
320                 });
321
322                 Ok(confirmed_txs)
323         }
324
325         #[maybe_async]
326         fn get_confirmed_tx(
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);
336                                 }
337                         }
338
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);
345                         }
346
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);
353                                 }
354
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 }));
358                                 }
359
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 }));
363                                 } else {
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);
368                                 }
369                         }
370                 }
371                 Ok(None)
372         }
373
374         #[maybe_async]
375         fn get_unconfirmed_transactions<C: Deref>(
376                 &self, confirmables: &Vec<C>,
377         ) -> Result<Vec<Txid>, InternalError>
378                 where C::Target: Confirm
379         {
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
383                         .iter()
384                         .flat_map(|c| c.get_relevant_txids())
385                         .collect::<HashSet<(Txid, u32, Option<BlockHash>)>>();
386
387                 let mut unconfirmed_txs = Vec::new();
388
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.
394                                         continue;
395                                 }
396
397                                 unconfirmed_txs.push(txid);
398                         } else {
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!");
401                         }
402                 }
403                 Ok(unconfirmed_txs)
404         }
405
406         /// Returns a reference to the underlying esplora client.
407         ///
408         /// This is not exported to bindings users as the underlying client from BDK is not exported.
409         pub fn client(&self) -> &EsploraClientType {
410                 &self.client
411         }
412 }
413
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>;
418
419 // The underlying client type.
420 #[cfg(feature = "async-interface")]
421 type EsploraClientType = AsyncClient;
422 #[cfg(not(feature = "async-interface"))]
423 type EsploraClientType = BlockingClient;
424
425
426 impl<L: Deref> Filter for EsploraSyncClient<L>
427 where
428         L::Target: Logger,
429 {
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);
433         }
434
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);
438         }
439 }