d2cb7256fd076fbfa7071d984da5a3e16351c389
[rust-lightning] / lightning-transaction-sync / src / electrum.rs
1 use crate::common::{ConfirmedTx, SyncState, FilterQueue};
2 use crate::error::{TxSyncError, InternalError};
3
4 use electrum_client::Client as ElectrumClient;
5 use electrum_client::ElectrumApi;
6 use electrum_client::GetMerkleRes;
7
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};
12
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;
18
19 use std::ops::Deref;
20 use std::sync::Mutex;
21 use std::collections::HashSet;
22 use std::time::Instant;
23
24 /// Synchronizes LDK with a given Electrum server.
25 ///
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
28 /// reconfirmation.
29 ///
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.
32 ///
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>
37 where
38         L::Target: Logger,
39 {
40         sync_state: Mutex<SyncState>,
41         queue: Mutex<FilterQueue>,
42         client: ElectrumClient,
43         logger: L,
44 }
45
46 impl<L: Deref> ElectrumSyncClient<L>
47 where
48         L::Target: Logger,
49 {
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);
54                         e
55                 })?;
56
57                 Self::from_client(client, logger)
58         }
59
60         /// Returns a new [`ElectrumSyncClient`] object using the given Electrum client.
61         ///
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());
66
67                 Ok(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         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();
89
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;
95
96                 // Clear any header notifications we might have gotten to keep the queue count low.
97                 while let Some(_) = self.client.block_headers_pop()? {}
98
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;
102
103                 loop {
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;
106
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 {
110                                 // Nothing to do.
111                                 break;
112                         } else {
113                                 // Update the known tip to the newest one.
114                                 if tip_is_new {
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) {
121                                                                 Ok(false) => {
122                                                                         num_unconfirmed += unconfirmed_txs.len();
123                                                                         sync_state.sync_unconfirmed_transactions(
124                                                                                 &confirmables,
125                                                                                 unconfirmed_txs
126                                                                         );
127                                                                 }
128                                                                 Ok(true) => {
129                                                                         log_debug!(self.logger,
130                                                                                 "Encountered inconsistency during transaction sync, restarting.");
131                                                                         sync_state.pending_sync = true;
132                                                                         continue;
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                                         // Update the best block.
159                                         for c in &confirmables {
160                                                 c.best_block_updated(&tip_header, tip_height);
161                                         }
162
163                                         // Prune any sufficiently confirmed output spends
164                                         sync_state.prune_output_spends(tip_height);
165                                 }
166
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) {
172                                                         Ok(false) => {
173                                                                 num_confirmed += confirmed_txs.len();
174                                                                 sync_state.sync_confirmed_transactions(
175                                                                         &confirmables,
176                                                                         confirmed_txs
177                                                                 );
178                                                         }
179                                                         Ok(true) => {
180                                                                 log_debug!(self.logger,
181                                                                         "Encountered inconsistency during transaction sync, restarting.");
182                                                                 sync_state.pending_sync = true;
183                                                                 continue;
184                                                         }
185                                                         Err(err) => {
186                                                                 // (Semi-)permanent failure, retry later.
187                                                                 log_error!(self.logger,
188                                                                         "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
189                                                                         num_confirmed,
190                                                                         num_unconfirmed
191                                                                 );
192                                                                 sync_state.pending_sync = true;
193                                                                 return Err(TxSyncError::from(err));
194                                                         }
195                                                 }
196                                         }
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;
202                                                 continue;
203                                         }
204                                         Err(err) => {
205                                                 // (Semi-)permanent failure, retry later.
206                                                 log_error!(self.logger,
207                                                         "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
208                                                         num_confirmed,
209                                                         num_unconfirmed
210                                                 );
211                                                 sync_state.pending_sync = true;
212                                                 return Err(TxSyncError::from(err));
213                                         }
214                                 }
215                                 sync_state.last_sync_hash = Some(tip_header.block_hash());
216                                 sync_state.pending_sync = false;
217                         }
218                 }
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,
223                         num_unconfirmed);
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);
228                 Ok(())
229         }
230
231         fn check_update_tip(&self, cur_tip_header: &mut Header, cur_tip_height: &mut u32)
232                 -> Result<bool, InternalError>
233         {
234                 let check_notification = self.client.block_headers_subscribe()?;
235                 let check_tip_hash = check_notification.header.block_hash();
236
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 {
243                                 restart_sync = true
244                         }
245                 }
246
247                 if restart_sync {
248                         *cur_tip_header = check_notification.header;
249                         *cur_tip_height = check_notification.height as u32;
250                         Ok(true)
251                 } else {
252                         Ok(false)
253                 }
254         }
255
256         fn get_confirmed_transactions(
257                 &self, sync_state: &SyncState,
258         ) -> Result<Vec<ConfirmedTx>, InternalError> {
259
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());
266
267                 for txid in &sync_state.watched_transactions {
268                         match self.client.transaction_get(&txid) {
269                                 Ok(tx) => {
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());
276                                         } else {
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);
280                                         }
281                                 }
282                                 Err(electrum_client::Error::Protocol(_)) => {
283                                         // We couldn't find the tx, do nothing.
284                                 }
285                                 Err(e) => {
286                                         log_error!(self.logger, "Failed to look up transaction {}: {}.", txid, e);
287                                         return Err(InternalError::Failed);
288                                 }
289                         }
290                 }
291
292                 let num_tx_lookups = watched_script_pubkeys.len();
293                 debug_assert_eq!(num_tx_lookups, watched_txs.len());
294
295                 for output in sync_state.watched_outputs.values() {
296                         watched_script_pubkeys.push(output.script_pubkey.clone());
297                 }
298
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());
301
302                 match self.client.batch_script_get_history(watched_script_pubkeys.iter().map(|s| s.deref()))
303                 {
304                         Ok(results) => {
305                                 let (tx_results, output_results) = results.split_at(num_tx_lookups);
306                                 debug_assert_eq!(num_output_spend_lookups, output_results.len());
307
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) {
311                                                 continue;
312                                         }
313                                         let mut filtered_history = script_history.iter().filter(|h| h.tx_hash == **txid);
314                                         if let Some(history) = filtered_history.next()
315                                         {
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);
319                                         }
320                                         debug_assert!(filtered_history.next().is_none());
321                                 }
322
323                                 for (watched_output, script_history) in sync_state.watched_outputs.values()
324                                         .zip(output_results)
325                                 {
326                                         for possible_output_spend in script_history {
327                                                 if possible_output_spend.height <= 0 {
328                                                         continue;
329                                                 }
330
331                                                 let txid = possible_output_spend.tx_hash;
332                                                 if confirmed_txs.iter().any(|ctx| ctx.txid == txid) {
333                                                         continue;
334                                                 }
335
336                                                 match self.client.transaction_get(&txid) {
337                                                         Ok(tx) => {
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 {
343                                                                                 is_spend = true;
344                                                                                 break;
345                                                                         }
346                                                                 }
347
348                                                                 if !is_spend {
349                                                                         continue;
350                                                                 }
351
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);
355                                                         }
356                                                         Err(e) => {
357                                                                 log_trace!(self.logger,
358                                                                         "Inconsistency: Tx {} was unconfirmed during syncing: {}",
359                                                                         txid, e);
360                                                                 return Err(InternalError::Inconsistency);
361                                                         }
362                                                 }
363                                         }
364                                 }
365                         }
366                         Err(e) => {
367                                 log_error!(self.logger, "Failed to look up script histories: {}.", e);
368                                 return Err(InternalError::Failed);
369                         }
370                 }
371
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))
376                 });
377
378                 Ok(confirmed_txs)
379         }
380
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
387                         .iter()
388                         .flat_map(|c| c.get_relevant_txids())
389                         .collect::<HashSet<(Txid, u32, Option<BlockHash>)>>();
390
391                 let mut unconfirmed_txs = Vec::new();
392
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.
398                                         continue;
399                                 }
400
401                                 unconfirmed_txs.push(txid);
402                         } else {
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!");
406                         }
407                 }
408                 Ok(unconfirmed_txs)
409         }
410
411         fn get_confirmed_tx(&self, tx: &Transaction, prob_conf_height: u32)
412                 -> Result<ConfirmedTx, InternalError>
413         {
414                 let txid = tx.txid();
415                 match self.client.transaction_get_merkle(&txid, prob_conf_height as usize) {
416                         Ok(merkle_res) => {
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)?
423                                                 {
424                                                         log_trace!(self.logger,
425                                                                 "Inconsistency: Block {} was unconfirmed during syncing.",
426                                                                 block_header.block_hash());
427                                                         return Err(InternalError::Inconsistency);
428                                                 }
429                                                 let confirmed_tx = ConfirmedTx {
430                                                         tx: tx.clone(),
431                                                         txid,
432                                                         block_header, block_height: prob_conf_height,
433                                                         pos,
434                                                 };
435                                                 Ok(confirmed_tx)
436                                         }
437                                         Err(e) => {
438                                                 log_error!(self.logger,
439                                                         "Failed to retrieve block header for height {}: {}.",
440                                                         prob_conf_height, e);
441                                                 Err(InternalError::Failed)
442                                         }
443                                 }
444                         }
445                         Err(e) => {
446                                 log_trace!(self.logger,
447                                         "Inconsistency: Tx {} was unconfirmed during syncing: {}",
448                                         txid, e);
449                                 Err(InternalError::Inconsistency)
450                         }
451                 }
452         }
453
454         /// Returns a reference to the underlying Electrum client.
455         ///
456         /// This is not exported to bindings users as the underlying client from BDK is not exported.
457         pub fn client(&self) -> &ElectrumClient {
458                 &self.client
459         }
460
461         fn validate_merkle_proof(&self, txid: &Txid, merkle_root: &TxMerkleNode,
462                 merkle_res: GetMerkleRes) -> Result<bool, InternalError>
463         {
464                 let mut index = merkle_res.pos;
465                 let mut cur = txid.to_raw_hash();
466                 for mut bytes in merkle_res.merkle {
467                         bytes.reverse();
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 {
471                                 (cur, next_hash)
472                         } else {
473                                 (next_hash, cur)
474                         };
475
476                         let data = [&left[..], &right[..]].concat();
477                         cur = Sha256d::hash(&data);
478                         index /= 2;
479                 }
480
481                 Ok(cur == merkle_root.to_raw_hash())
482         }
483 }
484
485 impl<L: Deref> Filter for ElectrumSyncClient<L>
486 where
487         L::Target: Logger,
488 {
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);
492         }
493
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);
497         }
498 }