d0c8afef77e3161ec191f41a0ceae4aa5eb8efe0
[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         pub fn from_client(client: ElectrumClient, logger: L) -> Result<Self, TxSyncError> {
62                 let sync_state = Mutex::new(SyncState::new());
63                 let queue = Mutex::new(FilterQueue::new());
64
65                 Ok(Self {
66                         sync_state,
67                         queue,
68                         client,
69                         logger,
70                 })
71         }
72
73         /// Synchronizes the given `confirmables` via their [`Confirm`] interface implementations. This
74         /// method should be called regularly to keep LDK up-to-date with current chain data.
75         ///
76         /// For example, instances of [`ChannelManager`] and [`ChainMonitor`] can be informed about the
77         /// newest on-chain activity related to the items previously registered via the [`Filter`]
78         /// interface.
79         ///
80         /// [`Confirm`]: lightning::chain::Confirm
81         /// [`ChainMonitor`]: lightning::chain::chainmonitor::ChainMonitor
82         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
83         /// [`Filter`]: lightning::chain::Filter
84         pub fn sync(&self, confirmables: Vec<&(dyn Confirm + Sync + Send)>) -> Result<(), TxSyncError> {
85                 // This lock makes sure we're syncing once at a time.
86                 let mut sync_state = self.sync_state.lock().unwrap();
87
88                 log_trace!(self.logger, "Starting transaction sync.");
89                 #[cfg(feature = "time")]
90                 let start_time = Instant::now();
91                 let mut num_confirmed = 0;
92                 let mut num_unconfirmed = 0;
93
94                 // Clear any header notifications we might have gotten to keep the queue count low.
95                 while let Some(_) = self.client.block_headers_pop()? {}
96
97                 let tip_notification = self.client.block_headers_subscribe()?;
98                 let mut tip_header = tip_notification.header;
99                 let mut tip_height = tip_notification.height as u32;
100
101                 loop {
102                         let pending_registrations = self.queue.lock().unwrap().process_queues(&mut sync_state);
103                         let tip_is_new = Some(tip_header.block_hash()) != sync_state.last_sync_hash;
104
105                         // We loop until any registered transactions have been processed at least once, or the
106                         // tip hasn't been updated during the last iteration.
107                         if !sync_state.pending_sync && !pending_registrations && !tip_is_new {
108                                 // Nothing to do.
109                                 break;
110                         } else {
111                                 // Update the known tip to the newest one.
112                                 if tip_is_new {
113                                         // First check for any unconfirmed transactions and act on it immediately.
114                                         match self.get_unconfirmed_transactions(&confirmables) {
115                                                 Ok(unconfirmed_txs) => {
116                                                         // Double-check the tip hash. If it changed, a reorg happened since
117                                                         // we started syncing and we need to restart last-minute.
118                                                         match self.check_update_tip(&mut tip_header, &mut tip_height) {
119                                                                 Ok(false) => {
120                                                                         num_unconfirmed += unconfirmed_txs.len();
121                                                                         sync_state.sync_unconfirmed_transactions(
122                                                                                 &confirmables,
123                                                                                 unconfirmed_txs
124                                                                         );
125                                                                 }
126                                                                 Ok(true) => {
127                                                                         log_debug!(self.logger,
128                                                                                 "Encountered inconsistency during transaction sync, restarting.");
129                                                                         sync_state.pending_sync = true;
130                                                                         continue;
131                                                                 }
132                                                                 Err(err) => {
133                                                                         // (Semi-)permanent failure, retry later.
134                                                                         log_error!(self.logger,
135                                                                                 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
136                                                                                 num_confirmed,
137                                                                                 num_unconfirmed
138                                                                         );
139                                                                         sync_state.pending_sync = true;
140                                                                         return Err(TxSyncError::from(err));
141                                                                 }
142                                                         }
143                                                 },
144                                                 Err(err) => {
145                                                         // (Semi-)permanent failure, retry later.
146                                                         log_error!(self.logger,
147                                                                 "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
148                                                                 num_confirmed,
149                                                                 num_unconfirmed
150                                                         );
151                                                         sync_state.pending_sync = true;
152                                                         return Err(TxSyncError::from(err));
153                                                 }
154                                         }
155
156                                         // Update the best block.
157                                         for c in &confirmables {
158                                                 c.best_block_updated(&tip_header, tip_height);
159                                         }
160                                 }
161
162                                 match self.get_confirmed_transactions(&sync_state) {
163                                         Ok(confirmed_txs) => {
164                                                 // Double-check the tip hash. If it changed, a reorg happened since
165                                                 // we started syncing and we need to restart last-minute.
166                                                 match self.check_update_tip(&mut tip_header, &mut tip_height) {
167                                                         Ok(false) => {
168                                                                 num_confirmed += confirmed_txs.len();
169                                                                 sync_state.sync_confirmed_transactions(
170                                                                         &confirmables,
171                                                                         confirmed_txs
172                                                                 );
173                                                         }
174                                                         Ok(true) => {
175                                                                 log_debug!(self.logger,
176                                                                         "Encountered inconsistency during transaction sync, restarting.");
177                                                                 sync_state.pending_sync = true;
178                                                                 continue;
179                                                         }
180                                                         Err(err) => {
181                                                                 // (Semi-)permanent failure, retry later.
182                                                                 log_error!(self.logger,
183                                                                         "Failed during transaction sync, aborting. Synced so far: {} confirmed, {} unconfirmed.",
184                                                                         num_confirmed,
185                                                                         num_unconfirmed
186                                                                 );
187                                                                 sync_state.pending_sync = true;
188                                                                 return Err(TxSyncError::from(err));
189                                                         }
190                                                 }
191                                         }
192                                         Err(InternalError::Inconsistency) => {
193                                                 // Immediately restart syncing when we encounter any inconsistencies.
194                                                 log_debug!(self.logger,
195                                                         "Encountered inconsistency during transaction sync, restarting.");
196                                                 sync_state.pending_sync = true;
197                                                 continue;
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                                 sync_state.last_sync_hash = Some(tip_header.block_hash());
211                                 sync_state.pending_sync = false;
212                         }
213                 }
214                 #[cfg(feature = "time")]
215                 log_debug!(self.logger,
216                         "Finished transaction sync at tip {} in {}ms: {} confirmed, {} unconfirmed.",
217                         tip_header.block_hash(), start_time.elapsed().as_millis(), num_confirmed,
218                         num_unconfirmed);
219                 #[cfg(not(feature = "time"))]
220                 log_debug!(self.logger,
221                         "Finished transaction sync at tip {}: {} confirmed, {} unconfirmed.",
222                         tip_header.block_hash(), num_confirmed, num_unconfirmed);
223                 Ok(())
224         }
225
226         fn check_update_tip(&self, cur_tip_header: &mut Header, cur_tip_height: &mut u32)
227                 -> Result<bool, InternalError>
228         {
229                 let check_notification = self.client.block_headers_subscribe()?;
230                 let check_tip_hash = check_notification.header.block_hash();
231
232                 // Restart if either the tip changed or we got some divergent tip
233                 // change notification since we started. In the latter case we
234                 // make sure we clear the queue before continuing.
235                 let mut restart_sync = check_tip_hash != cur_tip_header.block_hash();
236                 while let Some(queued_notif) = self.client.block_headers_pop()? {
237                         if queued_notif.header.block_hash() != check_tip_hash {
238                                 restart_sync = true
239                         }
240                 }
241
242                 if restart_sync {
243                         *cur_tip_header = check_notification.header;
244                         *cur_tip_height = check_notification.height as u32;
245                         Ok(true)
246                 } else {
247                         Ok(false)
248                 }
249         }
250
251         fn get_confirmed_transactions(
252                 &self, sync_state: &SyncState,
253         ) -> Result<Vec<ConfirmedTx>, InternalError> {
254
255                 // First, check the confirmation status of registered transactions as well as the
256                 // status of dependent transactions of registered outputs.
257                 let mut confirmed_txs = Vec::new();
258                 let mut watched_script_pubkeys = Vec::with_capacity(
259                         sync_state.watched_transactions.len() + sync_state.watched_outputs.len());
260                 let mut watched_txs = Vec::with_capacity(sync_state.watched_transactions.len());
261
262                 for txid in &sync_state.watched_transactions {
263                         match self.client.transaction_get(&txid) {
264                                 Ok(tx) => {
265                                         watched_txs.push((txid, tx.clone()));
266                                         if let Some(tx_out) = tx.output.first() {
267                                                 // We watch an arbitrary output of the transaction of interest in order to
268                                                 // retrieve the associated script history, before narrowing down our search
269                                                 // through `filter`ing by `txid` below.
270                                                 watched_script_pubkeys.push(tx_out.script_pubkey.clone());
271                                         } else {
272                                                 debug_assert!(false, "Failed due to retrieving invalid tx data.");
273                                                 log_error!(self.logger, "Failed due to retrieving invalid tx data.");
274                                                 return Err(InternalError::Failed);
275                                         }
276                                 }
277                                 Err(electrum_client::Error::Protocol(_)) => {
278                                         // We couldn't find the tx, do nothing.
279                                 }
280                                 Err(e) => {
281                                         log_error!(self.logger, "Failed to look up transaction {}: {}.", txid, e);
282                                         return Err(InternalError::Failed);
283                                 }
284                         }
285                 }
286
287                 let num_tx_lookups = watched_script_pubkeys.len();
288                 debug_assert_eq!(num_tx_lookups, watched_txs.len());
289
290                 for output in sync_state.watched_outputs.values() {
291                         watched_script_pubkeys.push(output.script_pubkey.clone());
292                 }
293
294                 let num_output_spend_lookups = watched_script_pubkeys.len() - num_tx_lookups;
295                 debug_assert_eq!(num_output_spend_lookups, sync_state.watched_outputs.len());
296
297                 match self.client.batch_script_get_history(watched_script_pubkeys.iter().map(|s| s.deref()))
298                 {
299                         Ok(results) => {
300                                 let (tx_results, output_results) = results.split_at(num_tx_lookups);
301                                 debug_assert_eq!(num_output_spend_lookups, output_results.len());
302
303                                 for (i, script_history) in tx_results.iter().enumerate() {
304                                         let (txid, tx) = &watched_txs[i];
305                                         let mut filtered_history = script_history.iter().filter(|h| h.tx_hash == **txid);
306                                         if let Some(history) = filtered_history.next()
307                                         {
308                                                 let prob_conf_height = history.height as u32;
309                                                 let confirmed_tx = self.get_confirmed_tx(tx, prob_conf_height)?;
310                                                 confirmed_txs.push(confirmed_tx);
311                                         }
312                                         debug_assert!(filtered_history.next().is_none());
313                                 }
314
315                                 for (watched_output, script_history) in sync_state.watched_outputs.values()
316                                         .zip(output_results)
317                                 {
318                                         for possible_output_spend in script_history {
319                                                 if possible_output_spend.height <= 0 {
320                                                         continue;
321                                                 }
322
323                                                 let txid = possible_output_spend.tx_hash;
324                                                 match self.client.transaction_get(&txid) {
325                                                         Ok(tx) => {
326                                                                 let mut is_spend = false;
327                                                                 for txin in &tx.input {
328                                                                         let watched_outpoint = watched_output.outpoint
329                                                                                 .into_bitcoin_outpoint();
330                                                                         if txin.previous_output == watched_outpoint {
331                                                                                 is_spend = true;
332                                                                                 break;
333                                                                         }
334                                                                 }
335
336                                                                 if !is_spend {
337                                                                         continue;
338                                                                 }
339
340                                                                 let prob_conf_height = possible_output_spend.height as u32;
341                                                                 let confirmed_tx = self.get_confirmed_tx(&tx, prob_conf_height)?;
342                                                                 confirmed_txs.push(confirmed_tx);
343                                                         }
344                                                         Err(e) => {
345                                                                 log_trace!(self.logger,
346                                                                         "Inconsistency: Tx {} was unconfirmed during syncing: {}",
347                                                                         txid, e);
348                                                                 return Err(InternalError::Inconsistency);
349                                                         }
350                                                 }
351                                         }
352                                 }
353                         }
354                         Err(e) => {
355                                 log_error!(self.logger, "Failed to look up script histories: {}.", e);
356                                 return Err(InternalError::Failed);
357                         }
358                 }
359
360                 // Sort all confirmed transactions first by block height, then by in-block
361                 // position, and finally feed them to the interface in order.
362                 confirmed_txs.sort_unstable_by(|tx1, tx2| {
363                         tx1.block_height.cmp(&tx2.block_height).then_with(|| tx1.pos.cmp(&tx2.pos))
364                 });
365
366                 Ok(confirmed_txs)
367         }
368
369         fn get_unconfirmed_transactions(
370                 &self, confirmables: &Vec<&(dyn Confirm + Sync + Send)>,
371         ) -> Result<Vec<Txid>, InternalError> {
372                 // Query the interface for relevant txids and check whether the relevant blocks are still
373                 // in the best chain, mark them unconfirmed otherwise
374                 let relevant_txids = confirmables
375                         .iter()
376                         .flat_map(|c| c.get_relevant_txids())
377                         .collect::<HashSet<(Txid, u32, Option<BlockHash>)>>();
378
379                 let mut unconfirmed_txs = Vec::new();
380
381                 for (txid, conf_height, block_hash_opt) in relevant_txids {
382                         if let Some(block_hash) = block_hash_opt {
383                                 let block_header = self.client.block_header(conf_height as usize)?;
384                                 if block_header.block_hash() == block_hash {
385                                         // Skip if the tx is still confirmed in the block in question.
386                                         continue;
387                                 }
388
389                                 unconfirmed_txs.push(txid);
390                         } else {
391                                 log_error!(self.logger,
392                                         "Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!");
393                                 panic!("Untracked confirmation of funding transaction. Please ensure none of your channels had been created with LDK prior to version 0.0.113!");
394                         }
395                 }
396                 Ok(unconfirmed_txs)
397         }
398
399         fn get_confirmed_tx(&self, tx: &Transaction, prob_conf_height: u32)
400                 -> Result<ConfirmedTx, InternalError>
401         {
402                 let txid = tx.txid();
403                 match self.client.transaction_get_merkle(&txid, prob_conf_height as usize) {
404                         Ok(merkle_res) => {
405                                 debug_assert_eq!(prob_conf_height, merkle_res.block_height as u32);
406                                 match self.client.block_header(prob_conf_height as usize) {
407                                         Ok(block_header) => {
408                                                 let pos = merkle_res.pos;
409                                                 if !self.validate_merkle_proof(&txid,
410                                                         &block_header.merkle_root, merkle_res)?
411                                                 {
412                                                         log_trace!(self.logger,
413                                                                 "Inconsistency: Block {} was unconfirmed during syncing.",
414                                                                 block_header.block_hash());
415                                                         return Err(InternalError::Inconsistency);
416                                                 }
417                                                 let confirmed_tx = ConfirmedTx {
418                                                         tx: tx.clone(),
419                                                         block_header, block_height: prob_conf_height,
420                                                         pos,
421                                                 };
422                                                 Ok(confirmed_tx)
423                                         }
424                                         Err(e) => {
425                                                 log_error!(self.logger,
426                                                         "Failed to retrieve block header for height {}: {}.",
427                                                         prob_conf_height, e);
428                                                 Err(InternalError::Failed)
429                                         }
430                                 }
431                         }
432                         Err(e) => {
433                                 log_trace!(self.logger,
434                                         "Inconsistency: Tx {} was unconfirmed during syncing: {}",
435                                         txid, e);
436                                 Err(InternalError::Inconsistency)
437                         }
438                 }
439         }
440
441         /// Returns a reference to the underlying Electrum client.
442         pub fn client(&self) -> &ElectrumClient {
443                 &self.client
444         }
445
446         fn validate_merkle_proof(&self, txid: &Txid, merkle_root: &TxMerkleNode,
447                 merkle_res: GetMerkleRes) -> Result<bool, InternalError>
448         {
449                 let mut index = merkle_res.pos;
450                 let mut cur = txid.to_raw_hash();
451                 for mut bytes in merkle_res.merkle {
452                         bytes.reverse();
453                         // unwrap() safety: `bytes` has len 32 so `from_slice` can never fail.
454                         let next_hash = Sha256d::from_slice(&bytes).unwrap();
455                         let (left, right) = if index % 2 == 0 {
456                                 (cur, next_hash)
457                         } else {
458                                 (next_hash, cur)
459                         };
460
461                         let data = [&left[..], &right[..]].concat();
462                         cur = Sha256d::hash(&data);
463                         index /= 2;
464                 }
465
466                 Ok(cur == merkle_root.to_raw_hash())
467         }
468 }
469
470 impl<L: Deref> Filter for ElectrumSyncClient<L>
471 where
472         L::Target: Logger,
473 {
474         fn register_tx(&self, txid: &Txid, _script_pubkey: &Script) {
475                 let mut locked_queue = self.queue.lock().unwrap();
476                 locked_queue.transactions.insert(*txid);
477         }
478
479         fn register_output(&self, output: WatchedOutput) {
480                 let mut locked_queue = self.queue.lock().unwrap();
481                 locked_queue.outputs.insert(output.outpoint.into_bitcoin_outpoint(), output);
482         }
483 }