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