]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/chain/chainmonitor.rs
Merge pull request #3011 from jkczyz/2024-04-compact-blinded-path-creation
[rust-lightning] / lightning / src / chain / chainmonitor.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Logic to connect off-chain channel management with on-chain transaction monitoring.
11 //!
12 //! [`ChainMonitor`] is an implementation of [`chain::Watch`] used both to process blocks and to
13 //! update [`ChannelMonitor`]s accordingly. If any on-chain events need further processing, it will
14 //! make those available as [`MonitorEvent`]s to be consumed.
15 //!
16 //! [`ChainMonitor`] is parameterized by an optional chain source, which must implement the
17 //! [`chain::Filter`] trait. This provides a mechanism to signal new relevant outputs back to light
18 //! clients, such that transactions spending those outputs are included in block data.
19 //!
20 //! [`ChainMonitor`] may be used directly to monitor channels locally or as a part of a distributed
21 //! setup to monitor channels remotely. In the latter case, a custom [`chain::Watch`] implementation
22 //! would be responsible for routing each update to a remote server and for retrieving monitor
23 //! events. The remote server would make use of [`ChainMonitor`] for block processing and for
24 //! servicing [`ChannelMonitor`] updates from the client.
25
26 use bitcoin::blockdata::block::Header;
27 use bitcoin::hash_types::{Txid, BlockHash};
28
29 use crate::chain;
30 use crate::chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput};
31 use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
32 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, Balance, MonitorEvent, TransactionOutputs, WithChannelMonitor};
33 use crate::chain::transaction::{OutPoint, TransactionData};
34 use crate::ln::types::ChannelId;
35 use crate::sign::ecdsa::EcdsaChannelSigner;
36 use crate::events;
37 use crate::events::{Event, EventHandler};
38 use crate::util::logger::{Logger, WithContext};
39 use crate::util::errors::APIError;
40 use crate::util::wakers::{Future, Notifier};
41 use crate::ln::channelmanager::ChannelDetails;
42
43 use crate::prelude::*;
44 use crate::sync::{RwLock, RwLockReadGuard, Mutex, MutexGuard};
45 use core::ops::Deref;
46 use core::sync::atomic::{AtomicUsize, Ordering};
47 use bitcoin::secp256k1::PublicKey;
48
49 /// `Persist` defines behavior for persisting channel monitors: this could mean
50 /// writing once to disk, and/or uploading to one or more backup services.
51 ///
52 /// Persistence can happen in one of two ways - synchronously completing before the trait method
53 /// calls return or asynchronously in the background.
54 ///
55 /// # For those implementing synchronous persistence
56 ///
57 ///  * If persistence completes fully (including any relevant `fsync()` calls), the implementation
58 ///    should return [`ChannelMonitorUpdateStatus::Completed`], indicating normal channel operation
59 ///    should continue.
60 ///
61 ///  * If persistence fails for some reason, implementations should consider returning
62 ///    [`ChannelMonitorUpdateStatus::InProgress`] and retry all pending persistence operations in
63 ///    the background with [`ChainMonitor::list_pending_monitor_updates`] and
64 ///    [`ChainMonitor::get_monitor`].
65 ///
66 ///    Once a full [`ChannelMonitor`] has been persisted, all pending updates for that channel can
67 ///    be marked as complete via [`ChainMonitor::channel_monitor_updated`].
68 ///
69 ///    If at some point no further progress can be made towards persisting the pending updates, the
70 ///    node should simply shut down.
71 ///
72 ///  * If the persistence has failed and cannot be retried further (e.g. because of an outage),
73 ///    [`ChannelMonitorUpdateStatus::UnrecoverableError`] can be used, though this will result in
74 ///    an immediate panic and future operations in LDK generally failing.
75 ///
76 /// # For those implementing asynchronous persistence
77 ///
78 ///  All calls should generally spawn a background task and immediately return
79 ///  [`ChannelMonitorUpdateStatus::InProgress`]. Once the update completes,
80 ///  [`ChainMonitor::channel_monitor_updated`] should be called with the corresponding
81 ///  [`ChannelMonitor::get_latest_update_id`] or [`ChannelMonitorUpdate::update_id`].
82 ///
83 ///  Note that unlike the direct [`chain::Watch`] interface,
84 ///  [`ChainMonitor::channel_monitor_updated`] must be called once for *each* update which occurs.
85 ///
86 ///  If at some point no further progress can be made towards persisting a pending update, the node
87 ///  should simply shut down. Until then, the background task should either loop indefinitely, or
88 ///  persistence should be regularly retried with [`ChainMonitor::list_pending_monitor_updates`]
89 ///  and [`ChainMonitor::get_monitor`] (note that if a full monitor is persisted all pending
90 ///  monitor updates may be marked completed).
91 ///
92 /// # Using remote watchtowers
93 ///
94 /// Watchtowers may be updated as a part of an implementation of this trait, utilizing the async
95 /// update process described above while the watchtower is being updated. The following methods are
96 /// provided for bulding transactions for a watchtower:
97 /// [`ChannelMonitor::initial_counterparty_commitment_tx`],
98 /// [`ChannelMonitor::counterparty_commitment_txs_from_update`],
99 /// [`ChannelMonitor::sign_to_local_justice_tx`], [`TrustedCommitmentTransaction::revokeable_output_index`],
100 /// [`TrustedCommitmentTransaction::build_to_local_justice_tx`].
101 ///
102 /// [`TrustedCommitmentTransaction::revokeable_output_index`]: crate::ln::chan_utils::TrustedCommitmentTransaction::revokeable_output_index
103 /// [`TrustedCommitmentTransaction::build_to_local_justice_tx`]: crate::ln::chan_utils::TrustedCommitmentTransaction::build_to_local_justice_tx
104 pub trait Persist<ChannelSigner: EcdsaChannelSigner> {
105         /// Persist a new channel's data in response to a [`chain::Watch::watch_channel`] call. This is
106         /// called by [`ChannelManager`] for new channels, or may be called directly, e.g. on startup.
107         ///
108         /// The data can be stored any way you want, but the identifier provided by LDK is the
109         /// channel's outpoint (and it is up to you to maintain a correct mapping between the outpoint
110         /// and the stored channel data). Note that you **must** persist every new monitor to disk.
111         ///
112         /// The [`ChannelMonitor::get_latest_update_id`] uniquely links this call to [`ChainMonitor::channel_monitor_updated`].
113         /// For [`Persist::persist_new_channel`], it is only necessary to call [`ChainMonitor::channel_monitor_updated`]
114         /// when you return [`ChannelMonitorUpdateStatus::InProgress`].
115         ///
116         /// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`
117         /// and [`ChannelMonitorUpdateStatus`] for requirements when returning errors.
118         ///
119         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
120         /// [`Writeable::write`]: crate::util::ser::Writeable::write
121         fn persist_new_channel(&self, channel_funding_outpoint: OutPoint, monitor: &ChannelMonitor<ChannelSigner>) -> ChannelMonitorUpdateStatus;
122
123         /// Update one channel's data. The provided [`ChannelMonitor`] has already applied the given
124         /// update.
125         ///
126         /// Note that on every update, you **must** persist either the [`ChannelMonitorUpdate`] or the
127         /// updated monitor itself to disk/backups. See the [`Persist`] trait documentation for more
128         /// details.
129         ///
130         /// During blockchain synchronization operations, and in some rare cases, this may be called with
131         /// no [`ChannelMonitorUpdate`], in which case the full [`ChannelMonitor`] needs to be persisted.
132         /// Note that after the full [`ChannelMonitor`] is persisted any previous
133         /// [`ChannelMonitorUpdate`]s which were persisted should be discarded - they can no longer be
134         /// applied to the persisted [`ChannelMonitor`] as they were already applied.
135         ///
136         /// If an implementer chooses to persist the updates only, they need to make
137         /// sure that all the updates are applied to the `ChannelMonitors` *before*
138         /// the set of channel monitors is given to the `ChannelManager`
139         /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
140         /// applying a monitor update to a monitor. If full `ChannelMonitors` are
141         /// persisted, then there is no need to persist individual updates.
142         ///
143         /// Note that there could be a performance tradeoff between persisting complete
144         /// channel monitors on every update vs. persisting only updates and applying
145         /// them in batches. The size of each monitor grows `O(number of state updates)`
146         /// whereas updates are small and `O(1)`.
147         ///
148         /// The [`ChannelMonitorUpdate::update_id`] or [`ChannelMonitor::get_latest_update_id`] uniquely
149         /// links this call to [`ChainMonitor::channel_monitor_updated`].
150         /// For [`Persist::update_persisted_channel`], it is only necessary to call [`ChainMonitor::channel_monitor_updated`]
151         /// when a [`ChannelMonitorUpdate`] is provided and when you return [`ChannelMonitorUpdateStatus::InProgress`].
152         ///
153         /// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`,
154         /// [`Writeable::write`] on [`ChannelMonitorUpdate`] for writing out an update, and
155         /// [`ChannelMonitorUpdateStatus`] for requirements when returning errors.
156         ///
157         /// [`Writeable::write`]: crate::util::ser::Writeable::write
158         fn update_persisted_channel(&self, channel_funding_outpoint: OutPoint, monitor_update: Option<&ChannelMonitorUpdate>, monitor: &ChannelMonitor<ChannelSigner>) -> ChannelMonitorUpdateStatus;
159         /// Prevents the channel monitor from being loaded on startup.
160         ///
161         /// Archiving the data in a backup location (rather than deleting it fully) is useful for
162         /// hedging against data loss in case of unexpected failure.
163         fn archive_persisted_channel(&self, channel_funding_outpoint: OutPoint);
164 }
165
166 struct MonitorHolder<ChannelSigner: EcdsaChannelSigner> {
167         monitor: ChannelMonitor<ChannelSigner>,
168         /// The full set of pending monitor updates for this Channel.
169         ///
170         /// Note that this lock must be held during updates to prevent a race where we call
171         /// update_persisted_channel, the user returns a
172         /// [`ChannelMonitorUpdateStatus::InProgress`], and then calls channel_monitor_updated
173         /// immediately, racing our insertion of the pending update into the contained Vec.
174         pending_monitor_updates: Mutex<Vec<u64>>,
175 }
176
177 impl<ChannelSigner: EcdsaChannelSigner> MonitorHolder<ChannelSigner> {
178         fn has_pending_updates(&self, pending_monitor_updates_lock: &MutexGuard<Vec<u64>>) -> bool {
179                 !pending_monitor_updates_lock.is_empty()
180         }
181 }
182
183 /// A read-only reference to a current ChannelMonitor.
184 ///
185 /// Note that this holds a mutex in [`ChainMonitor`] and may block other events until it is
186 /// released.
187 pub struct LockedChannelMonitor<'a, ChannelSigner: EcdsaChannelSigner> {
188         lock: RwLockReadGuard<'a, HashMap<OutPoint, MonitorHolder<ChannelSigner>>>,
189         funding_txo: OutPoint,
190 }
191
192 impl<ChannelSigner: EcdsaChannelSigner> Deref for LockedChannelMonitor<'_, ChannelSigner> {
193         type Target = ChannelMonitor<ChannelSigner>;
194         fn deref(&self) -> &ChannelMonitor<ChannelSigner> {
195                 &self.lock.get(&self.funding_txo).expect("Checked at construction").monitor
196         }
197 }
198
199 /// An implementation of [`chain::Watch`] for monitoring channels.
200 ///
201 /// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
202 /// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
203 /// or used independently to monitor channels remotely. See the [module-level documentation] for
204 /// details.
205 ///
206 /// Note that `ChainMonitor` should regularly trigger rebroadcasts/fee bumps of pending claims from
207 /// a force-closed channel. This is crucial in preventing certain classes of pinning attacks,
208 /// detecting substantial mempool feerate changes between blocks, and ensuring reliability if
209 /// broadcasting fails. We recommend invoking this every 30 seconds, or lower if running in an
210 /// environment with spotty connections, like on mobile.
211 ///
212 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
213 /// [module-level documentation]: crate::chain::chainmonitor
214 /// [`rebroadcast_pending_claims`]: Self::rebroadcast_pending_claims
215 pub struct ChainMonitor<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
216         where C::Target: chain::Filter,
217         T::Target: BroadcasterInterface,
218         F::Target: FeeEstimator,
219         L::Target: Logger,
220         P::Target: Persist<ChannelSigner>,
221 {
222         monitors: RwLock<HashMap<OutPoint, MonitorHolder<ChannelSigner>>>,
223         chain_source: Option<C>,
224         broadcaster: T,
225         logger: L,
226         fee_estimator: F,
227         persister: P,
228         /// "User-provided" (ie persistence-completion/-failed) [`MonitorEvent`]s. These came directly
229         /// from the user and not from a [`ChannelMonitor`].
230         pending_monitor_events: Mutex<Vec<(OutPoint, ChannelId, Vec<MonitorEvent>, Option<PublicKey>)>>,
231         /// The best block height seen, used as a proxy for the passage of time.
232         highest_chain_height: AtomicUsize,
233
234         /// A [`Notifier`] used to wake up the background processor in case we have any [`Event`]s for
235         /// it to give to users (or [`MonitorEvent`]s for `ChannelManager` to process).
236         event_notifier: Notifier,
237 }
238
239 impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P>
240 where C::Target: chain::Filter,
241             T::Target: BroadcasterInterface,
242             F::Target: FeeEstimator,
243             L::Target: Logger,
244             P::Target: Persist<ChannelSigner>,
245 {
246         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
247         /// of a channel and reacting accordingly based on transactions in the given chain data. See
248         /// [`ChannelMonitor::block_connected`] for details. Any HTLCs that were resolved on chain will
249         /// be returned by [`chain::Watch::release_pending_monitor_events`].
250         ///
251         /// Calls back to [`chain::Filter`] if any monitor indicated new outputs to watch. Subsequent
252         /// calls must not exclude any transactions matching the new outputs nor any in-block
253         /// descendants of such transactions. It is not necessary to re-fetch the block to obtain
254         /// updated `txdata`.
255         ///
256         /// Calls which represent a new blockchain tip height should set `best_height`.
257         fn process_chain_data<FN>(&self, header: &Header, best_height: Option<u32>, txdata: &TransactionData, process: FN)
258         where
259                 FN: Fn(&ChannelMonitor<ChannelSigner>, &TransactionData) -> Vec<TransactionOutputs>
260         {
261                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
262                 let funding_outpoints = hash_set_from_iter(self.monitors.read().unwrap().keys().cloned());
263                 for funding_outpoint in funding_outpoints.iter() {
264                         let monitor_lock = self.monitors.read().unwrap();
265                         if let Some(monitor_state) = monitor_lock.get(funding_outpoint) {
266                                 if self.update_monitor_with_chain_data(header, txdata, &process, funding_outpoint, &monitor_state).is_err() {
267                                         // Take the monitors lock for writing so that we poison it and any future
268                                         // operations going forward fail immediately.
269                                         core::mem::drop(monitor_lock);
270                                         let _poison = self.monitors.write().unwrap();
271                                         log_error!(self.logger, "{}", err_str);
272                                         panic!("{}", err_str);
273                                 }
274                         }
275                 }
276
277                 // do some followup cleanup if any funding outpoints were added in between iterations
278                 let monitor_states = self.monitors.write().unwrap();
279                 for (funding_outpoint, monitor_state) in monitor_states.iter() {
280                         if !funding_outpoints.contains(funding_outpoint) {
281                                 if self.update_monitor_with_chain_data(header, txdata, &process, funding_outpoint, &monitor_state).is_err() {
282                                         log_error!(self.logger, "{}", err_str);
283                                         panic!("{}", err_str);
284                                 }
285                         }
286                 }
287
288                 if let Some(height) = best_height {
289                         // If the best block height is being updated, update highest_chain_height under the
290                         // monitors write lock.
291                         let old_height = self.highest_chain_height.load(Ordering::Acquire);
292                         let new_height = height as usize;
293                         if new_height > old_height {
294                                 self.highest_chain_height.store(new_height, Ordering::Release);
295                         }
296                 }
297         }
298
299         fn update_monitor_with_chain_data<FN>(
300                 &self, header: &Header, txdata: &TransactionData, process: FN, funding_outpoint: &OutPoint,
301                 monitor_state: &MonitorHolder<ChannelSigner>
302         ) -> Result<(), ()> where FN: Fn(&ChannelMonitor<ChannelSigner>, &TransactionData) -> Vec<TransactionOutputs> {
303                 let monitor = &monitor_state.monitor;
304                 let logger = WithChannelMonitor::from(&self.logger, &monitor, None);
305                 let mut txn_outputs;
306                 {
307                         txn_outputs = process(monitor, txdata);
308                         log_trace!(logger, "Syncing Channel Monitor for channel {}", log_funding_info!(monitor));
309                         match self.persister.update_persisted_channel(*funding_outpoint, None, monitor) {
310                                 ChannelMonitorUpdateStatus::Completed =>
311                                         log_trace!(logger, "Finished syncing Channel Monitor for channel {} for block-data",
312                                                 log_funding_info!(monitor)
313                                         ),
314                                 ChannelMonitorUpdateStatus::InProgress => {
315                                         log_trace!(logger, "Channel Monitor sync for channel {} in progress.", log_funding_info!(monitor));
316                                 },
317                                 ChannelMonitorUpdateStatus::UnrecoverableError => {
318                                         return Err(());
319                                 },
320                         }
321                 }
322
323                 // Register any new outputs with the chain source for filtering, storing any dependent
324                 // transactions from within the block that previously had not been included in txdata.
325                 if let Some(ref chain_source) = self.chain_source {
326                         let block_hash = header.block_hash();
327                         for (txid, mut outputs) in txn_outputs.drain(..) {
328                                 for (idx, output) in outputs.drain(..) {
329                                         // Register any new outputs with the chain source for filtering
330                                         let output = WatchedOutput {
331                                                 block_hash: Some(block_hash),
332                                                 outpoint: OutPoint { txid, index: idx as u16 },
333                                                 script_pubkey: output.script_pubkey,
334                                         };
335                                         log_trace!(logger, "Adding monitoring for spends of outpoint {} to the filter", output.outpoint);
336                                         chain_source.register_output(output);
337                                 }
338                         }
339                 }
340                 Ok(())
341         }
342
343         /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
344         ///
345         /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
346         /// will call back to it indicating transactions and outputs of interest. This allows clients to
347         /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
348         /// always need to fetch full blocks absent another means for determining which blocks contain
349         /// transactions relevant to the watched channels.
350         pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
351                 Self {
352                         monitors: RwLock::new(new_hash_map()),
353                         chain_source,
354                         broadcaster,
355                         logger,
356                         fee_estimator: feeest,
357                         persister,
358                         pending_monitor_events: Mutex::new(Vec::new()),
359                         highest_chain_height: AtomicUsize::new(0),
360                         event_notifier: Notifier::new(),
361                 }
362         }
363
364         /// Gets the balances in the contained [`ChannelMonitor`]s which are claimable on-chain or
365         /// claims which are awaiting confirmation.
366         ///
367         /// Includes the balances from each [`ChannelMonitor`] *except* those included in
368         /// `ignored_channels`, allowing you to filter out balances from channels which are still open
369         /// (and whose balance should likely be pulled from the [`ChannelDetails`]).
370         ///
371         /// See [`ChannelMonitor::get_claimable_balances`] for more details on the exact criteria for
372         /// inclusion in the return value.
373         pub fn get_claimable_balances(&self, ignored_channels: &[&ChannelDetails]) -> Vec<Balance> {
374                 let mut ret = Vec::new();
375                 let monitor_states = self.monitors.read().unwrap();
376                 for (_, monitor_state) in monitor_states.iter().filter(|(funding_outpoint, _)| {
377                         for chan in ignored_channels {
378                                 if chan.funding_txo.as_ref() == Some(funding_outpoint) {
379                                         return false;
380                                 }
381                         }
382                         true
383                 }) {
384                         ret.append(&mut monitor_state.monitor.get_claimable_balances());
385                 }
386                 ret
387         }
388
389         /// Gets the [`LockedChannelMonitor`] for a given funding outpoint, returning an `Err` if no
390         /// such [`ChannelMonitor`] is currently being monitored for.
391         ///
392         /// Note that the result holds a mutex over our monitor set, and should not be held
393         /// indefinitely.
394         pub fn get_monitor(&self, funding_txo: OutPoint) -> Result<LockedChannelMonitor<'_, ChannelSigner>, ()> {
395                 let lock = self.monitors.read().unwrap();
396                 if lock.get(&funding_txo).is_some() {
397                         Ok(LockedChannelMonitor { lock, funding_txo })
398                 } else {
399                         Err(())
400                 }
401         }
402
403         /// Lists the funding outpoint and channel ID of each [`ChannelMonitor`] being monitored.
404         ///
405         /// Note that [`ChannelMonitor`]s are not removed when a channel is closed as they are always
406         /// monitoring for on-chain state resolutions.
407         pub fn list_monitors(&self) -> Vec<(OutPoint, ChannelId)> {
408                 self.monitors.read().unwrap().iter().map(|(outpoint, monitor_holder)| {
409                         let channel_id = monitor_holder.monitor.channel_id();
410                         (*outpoint, channel_id)
411                 }).collect()
412         }
413
414         #[cfg(not(c_bindings))]
415         /// Lists the pending updates for each [`ChannelMonitor`] (by `OutPoint` being monitored).
416         /// Each `Vec<u64>` contains `update_id`s from [`ChannelMonitor::get_latest_update_id`] for updates
417         /// that have not yet been fully persisted. Note that if a full monitor is persisted all the pending
418         /// monitor updates must be individually marked completed by calling [`ChainMonitor::channel_monitor_updated`].
419         pub fn list_pending_monitor_updates(&self) -> HashMap<OutPoint, Vec<u64>> {
420                 hash_map_from_iter(self.monitors.read().unwrap().iter().map(|(outpoint, holder)| {
421                         (*outpoint, holder.pending_monitor_updates.lock().unwrap().clone())
422                 }))
423         }
424
425         #[cfg(c_bindings)]
426         /// Lists the pending updates for each [`ChannelMonitor`] (by `OutPoint` being monitored).
427         /// Each `Vec<u64>` contains `update_id`s from [`ChannelMonitor::get_latest_update_id`] for updates
428         /// that have not yet been fully persisted. Note that if a full monitor is persisted all the pending
429         /// monitor updates must be individually marked completed by calling [`ChainMonitor::channel_monitor_updated`].
430         pub fn list_pending_monitor_updates(&self) -> Vec<(OutPoint, Vec<u64>)> {
431                 self.monitors.read().unwrap().iter().map(|(outpoint, holder)| {
432                         (*outpoint, holder.pending_monitor_updates.lock().unwrap().clone())
433                 }).collect()
434         }
435
436
437         #[cfg(test)]
438         pub fn remove_monitor(&self, funding_txo: &OutPoint) -> ChannelMonitor<ChannelSigner> {
439                 self.monitors.write().unwrap().remove(funding_txo).unwrap().monitor
440         }
441
442         /// Indicates the persistence of a [`ChannelMonitor`] has completed after
443         /// [`ChannelMonitorUpdateStatus::InProgress`] was returned from an update operation.
444         ///
445         /// Thus, the anticipated use is, at a high level:
446         ///  1) This [`ChainMonitor`] calls [`Persist::update_persisted_channel`] which stores the
447         ///     update to disk and begins updating any remote (e.g. watchtower/backup) copies,
448         ///     returning [`ChannelMonitorUpdateStatus::InProgress`],
449         ///  2) once all remote copies are updated, you call this function with [`ChannelMonitor::get_latest_update_id`]
450         ///     or [`ChannelMonitorUpdate::update_id`] as the `completed_update_id`, and once all pending
451         ///     updates have completed the channel will be re-enabled.
452         ///
453         /// It is only necessary to call [`ChainMonitor::channel_monitor_updated`] when you return [`ChannelMonitorUpdateStatus::InProgress`]
454         /// from [`Persist`] and either:
455         ///   1. A new [`ChannelMonitor`] was added in [`Persist::persist_new_channel`], or
456         ///   2. A [`ChannelMonitorUpdate`] was provided as part of [`Persist::update_persisted_channel`].
457         /// Note that we don't care about calls to [`Persist::update_persisted_channel`] where no
458         /// [`ChannelMonitorUpdate`] was provided.
459         ///
460         /// Returns an [`APIError::APIMisuseError`] if `funding_txo` does not match any currently
461         /// registered [`ChannelMonitor`]s.
462         pub fn channel_monitor_updated(&self, funding_txo: OutPoint, completed_update_id: u64) -> Result<(), APIError> {
463                 let monitors = self.monitors.read().unwrap();
464                 let monitor_data = if let Some(mon) = monitors.get(&funding_txo) { mon } else {
465                         return Err(APIError::APIMisuseError { err: format!("No ChannelMonitor matching funding outpoint {:?} found", funding_txo) });
466                 };
467                 let mut pending_monitor_updates = monitor_data.pending_monitor_updates.lock().unwrap();
468                 pending_monitor_updates.retain(|update_id| *update_id != completed_update_id);
469
470                 // Note that we only check for pending non-chainsync monitor updates and we don't track monitor
471                 // updates resulting from chainsync in `pending_monitor_updates`.
472                 let monitor_is_pending_updates = monitor_data.has_pending_updates(&pending_monitor_updates);
473                 log_debug!(self.logger, "Completed off-chain monitor update {} for channel with funding outpoint {:?}, {}",
474                         completed_update_id,
475                         funding_txo,
476                         if monitor_is_pending_updates {
477                                 "still have pending off-chain updates"
478                         } else {
479                                 "all off-chain updates complete, returning a MonitorEvent"
480                         });
481                 if monitor_is_pending_updates {
482                         // If there are still monitor updates pending, we cannot yet construct a
483                         // Completed event.
484                         return Ok(());
485                 }
486                 let channel_id = monitor_data.monitor.channel_id();
487                 self.pending_monitor_events.lock().unwrap().push((funding_txo, channel_id, vec![MonitorEvent::Completed {
488                         funding_txo, channel_id,
489                         monitor_update_id: monitor_data.monitor.get_latest_update_id(),
490                 }], monitor_data.monitor.get_counterparty_node_id()));
491
492                 self.event_notifier.notify();
493                 Ok(())
494         }
495
496         /// This wrapper avoids having to update some of our tests for now as they assume the direct
497         /// chain::Watch API wherein we mark a monitor fully-updated by just calling
498         /// channel_monitor_updated once with the highest ID.
499         #[cfg(any(test, fuzzing))]
500         pub fn force_channel_monitor_updated(&self, funding_txo: OutPoint, monitor_update_id: u64) {
501                 let monitors = self.monitors.read().unwrap();
502                 let (counterparty_node_id, channel_id) = if let Some(m) = monitors.get(&funding_txo) {
503                         (m.monitor.get_counterparty_node_id(), m.monitor.channel_id())
504                 } else {
505                         (None, ChannelId::v1_from_funding_outpoint(funding_txo))
506                 };
507                 self.pending_monitor_events.lock().unwrap().push((funding_txo, channel_id, vec![MonitorEvent::Completed {
508                         funding_txo,
509                         channel_id,
510                         monitor_update_id,
511                 }], counterparty_node_id));
512                 self.event_notifier.notify();
513         }
514
515         #[cfg(any(test, feature = "_test_utils"))]
516         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
517                 use crate::events::EventsProvider;
518                 let events = core::cell::RefCell::new(Vec::new());
519                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
520                 self.process_pending_events(&event_handler);
521                 events.into_inner()
522         }
523
524         /// Processes any events asynchronously in the order they were generated since the last call
525         /// using the given event handler.
526         ///
527         /// See the trait-level documentation of [`EventsProvider`] for requirements.
528         ///
529         /// [`EventsProvider`]: crate::events::EventsProvider
530         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
531                 &self, handler: H
532         ) {
533                 // Sadly we can't hold the monitors read lock through an async call. Thus we have to do a
534                 // crazy dance to process a monitor's events then only remove them once we've done so.
535                 let mons_to_process = self.monitors.read().unwrap().keys().cloned().collect::<Vec<_>>();
536                 for funding_txo in mons_to_process {
537                         let mut ev;
538                         super::channelmonitor::process_events_body!(
539                                 self.monitors.read().unwrap().get(&funding_txo).map(|m| &m.monitor), ev, handler(ev).await);
540                 }
541         }
542
543         /// Gets a [`Future`] that completes when an event is available either via
544         /// [`chain::Watch::release_pending_monitor_events`] or
545         /// [`EventsProvider::process_pending_events`].
546         ///
547         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
548         /// [`ChainMonitor`] and should instead register actions to be taken later.
549         ///
550         /// [`EventsProvider::process_pending_events`]: crate::events::EventsProvider::process_pending_events
551         pub fn get_update_future(&self) -> Future {
552                 self.event_notifier.get_future()
553         }
554
555         /// Triggers rebroadcasts/fee-bumps of pending claims from a force-closed channel. This is
556         /// crucial in preventing certain classes of pinning attacks, detecting substantial mempool
557         /// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend
558         /// invoking this every 30 seconds, or lower if running in an environment with spotty
559         /// connections, like on mobile.
560         pub fn rebroadcast_pending_claims(&self) {
561                 let monitors = self.monitors.read().unwrap();
562                 for (_, monitor_holder) in &*monitors {
563                         monitor_holder.monitor.rebroadcast_pending_claims(
564                                 &*self.broadcaster, &*self.fee_estimator, &self.logger
565                         )
566                 }
567         }
568
569         /// Triggers rebroadcasts of pending claims from force-closed channels after a transaction
570         /// signature generation failure.
571         ///
572         /// `monitor_opt` can be used as a filter to only trigger them for a specific channel monitor.
573         pub fn signer_unblocked(&self, monitor_opt: Option<OutPoint>) {
574                 let monitors = self.monitors.read().unwrap();
575                 if let Some(funding_txo) = monitor_opt {
576                         if let Some(monitor_holder) = monitors.get(&funding_txo) {
577                                 monitor_holder.monitor.signer_unblocked(
578                                         &*self.broadcaster, &*self.fee_estimator, &self.logger
579                                 )
580                         }
581                 } else {
582                         for (_, monitor_holder) in &*monitors {
583                                 monitor_holder.monitor.signer_unblocked(
584                                         &*self.broadcaster, &*self.fee_estimator, &self.logger
585                                 )
586                         }
587                 }
588         }
589
590         /// Archives fully resolved channel monitors by calling [`Persist::archive_persisted_channel`].
591         ///
592         /// This is useful for pruning fully resolved monitors from the monitor set and primary
593         /// storage so they are not kept in memory and reloaded on restart.
594         ///
595         /// Should be called occasionally (once every handful of blocks or on startup).
596         ///
597         /// Depending on the implementation of [`Persist::archive_persisted_channel`] the monitor
598         /// data could be moved to an archive location or removed entirely.
599         pub fn archive_fully_resolved_channel_monitors(&self) {
600                 let mut have_monitors_to_prune = false;
601                 for (_, monitor_holder) in self.monitors.read().unwrap().iter() {
602                         let logger = WithChannelMonitor::from(&self.logger, &monitor_holder.monitor, None);
603                         if monitor_holder.monitor.is_fully_resolved(&logger) {
604                                 have_monitors_to_prune = true;
605                         }
606                 }
607                 if have_monitors_to_prune {
608                         let mut monitors = self.monitors.write().unwrap();
609                         monitors.retain(|funding_txo, monitor_holder| {
610                                 let logger = WithChannelMonitor::from(&self.logger, &monitor_holder.monitor, None);
611                                 if monitor_holder.monitor.is_fully_resolved(&logger) {
612                                         log_info!(logger,
613                                                 "Archiving fully resolved ChannelMonitor for funding txo {}",
614                                                 funding_txo
615                                         );
616                                         self.persister.archive_persisted_channel(*funding_txo);
617                                         false
618                                 } else {
619                                         true
620                                 }
621                         });
622                 }
623         }
624 }
625
626 impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
627 chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P>
628 where
629         C::Target: chain::Filter,
630         T::Target: BroadcasterInterface,
631         F::Target: FeeEstimator,
632         L::Target: Logger,
633         P::Target: Persist<ChannelSigner>,
634 {
635         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
636                 log_debug!(self.logger, "New best block {} at height {} provided via block_connected", header.block_hash(), height);
637                 self.process_chain_data(header, Some(height), &txdata, |monitor, txdata| {
638                         monitor.block_connected(
639                                 header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &self.logger)
640                 });
641                 // Assume we may have some new events and wake the event processor
642                 self.event_notifier.notify();
643         }
644
645         fn block_disconnected(&self, header: &Header, height: u32) {
646                 let monitor_states = self.monitors.read().unwrap();
647                 log_debug!(self.logger, "Latest block {} at height {} removed via block_disconnected", header.block_hash(), height);
648                 for monitor_state in monitor_states.values() {
649                         monitor_state.monitor.block_disconnected(
650                                 header, height, &*self.broadcaster, &*self.fee_estimator, &self.logger);
651                 }
652         }
653 }
654
655 impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
656 chain::Confirm for ChainMonitor<ChannelSigner, C, T, F, L, P>
657 where
658         C::Target: chain::Filter,
659         T::Target: BroadcasterInterface,
660         F::Target: FeeEstimator,
661         L::Target: Logger,
662         P::Target: Persist<ChannelSigner>,
663 {
664         fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
665                 log_debug!(self.logger, "{} provided transactions confirmed at height {} in block {}", txdata.len(), height, header.block_hash());
666                 self.process_chain_data(header, None, txdata, |monitor, txdata| {
667                         monitor.transactions_confirmed(
668                                 header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &self.logger)
669                 });
670                 // Assume we may have some new events and wake the event processor
671                 self.event_notifier.notify();
672         }
673
674         fn transaction_unconfirmed(&self, txid: &Txid) {
675                 log_debug!(self.logger, "Transaction {} reorganized out of chain", txid);
676                 let monitor_states = self.monitors.read().unwrap();
677                 for monitor_state in monitor_states.values() {
678                         monitor_state.monitor.transaction_unconfirmed(txid, &*self.broadcaster, &*self.fee_estimator, &self.logger);
679                 }
680         }
681
682         fn best_block_updated(&self, header: &Header, height: u32) {
683                 log_debug!(self.logger, "New best block {} at height {} provided via best_block_updated", header.block_hash(), height);
684                 self.process_chain_data(header, Some(height), &[], |monitor, txdata| {
685                         // While in practice there shouldn't be any recursive calls when given empty txdata,
686                         // it's still possible if a chain::Filter implementation returns a transaction.
687                         debug_assert!(txdata.is_empty());
688                         monitor.best_block_updated(
689                                 header, height, &*self.broadcaster, &*self.fee_estimator, &self.logger
690                         )
691                 });
692                 // Assume we may have some new events and wake the event processor
693                 self.event_notifier.notify();
694         }
695
696         fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
697                 let mut txids = Vec::new();
698                 let monitor_states = self.monitors.read().unwrap();
699                 for monitor_state in monitor_states.values() {
700                         txids.append(&mut monitor_state.monitor.get_relevant_txids());
701                 }
702
703                 txids.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
704                 txids.dedup_by_key(|(txid, _, _)| *txid);
705                 txids
706         }
707 }
708
709 impl<ChannelSigner: EcdsaChannelSigner, C: Deref , T: Deref , F: Deref , L: Deref , P: Deref >
710 chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
711 where C::Target: chain::Filter,
712             T::Target: BroadcasterInterface,
713             F::Target: FeeEstimator,
714             L::Target: Logger,
715             P::Target: Persist<ChannelSigner>,
716 {
717         fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<ChannelMonitorUpdateStatus, ()> {
718                 let logger = WithChannelMonitor::from(&self.logger, &monitor, None);
719                 let mut monitors = self.monitors.write().unwrap();
720                 let entry = match monitors.entry(funding_outpoint) {
721                         hash_map::Entry::Occupied(_) => {
722                                 log_error!(logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
723                                 return Err(());
724                         },
725                         hash_map::Entry::Vacant(e) => e,
726                 };
727                 log_trace!(logger, "Got new ChannelMonitor for channel {}", log_funding_info!(monitor));
728                 let update_id = monitor.get_latest_update_id();
729                 let mut pending_monitor_updates = Vec::new();
730                 let persist_res = self.persister.persist_new_channel(funding_outpoint, &monitor);
731                 match persist_res {
732                         ChannelMonitorUpdateStatus::InProgress => {
733                                 log_info!(logger, "Persistence of new ChannelMonitor for channel {} in progress", log_funding_info!(monitor));
734                                 pending_monitor_updates.push(update_id);
735                         },
736                         ChannelMonitorUpdateStatus::Completed => {
737                                 log_info!(logger, "Persistence of new ChannelMonitor for channel {} completed", log_funding_info!(monitor));
738                         },
739                         ChannelMonitorUpdateStatus::UnrecoverableError => {
740                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
741                                 log_error!(logger, "{}", err_str);
742                                 panic!("{}", err_str);
743                         },
744                 }
745                 if let Some(ref chain_source) = self.chain_source {
746                         monitor.load_outputs_to_watch(chain_source , &self.logger);
747                 }
748                 entry.insert(MonitorHolder {
749                         monitor,
750                         pending_monitor_updates: Mutex::new(pending_monitor_updates),
751                 });
752                 Ok(persist_res)
753         }
754
755         fn update_channel(&self, funding_txo: OutPoint, update: &ChannelMonitorUpdate) -> ChannelMonitorUpdateStatus {
756                 // `ChannelMonitorUpdate`'s `channel_id` is `None` prior to 0.0.121 and all channels in those
757                 // versions are V1-established. For 0.0.121+ the `channel_id` fields is always `Some`.
758                 let channel_id = update.channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(funding_txo));
759                 // Update the monitor that watches the channel referred to by the given outpoint.
760                 let monitors = self.monitors.read().unwrap();
761                 match monitors.get(&funding_txo) {
762                         None => {
763                                 let logger = WithContext::from(&self.logger, update.counterparty_node_id, Some(channel_id), None);
764                                 log_error!(logger, "Failed to update channel monitor: no such monitor registered");
765
766                                 // We should never ever trigger this from within ChannelManager. Technically a
767                                 // user could use this object with some proxying in between which makes this
768                                 // possible, but in tests and fuzzing, this should be a panic.
769                                 #[cfg(debug_assertions)]
770                                 panic!("ChannelManager generated a channel update for a channel that was not yet registered!");
771                                 #[cfg(not(debug_assertions))]
772                                 ChannelMonitorUpdateStatus::InProgress
773                         },
774                         Some(monitor_state) => {
775                                 let monitor = &monitor_state.monitor;
776                                 let logger = WithChannelMonitor::from(&self.logger, &monitor, None);
777                                 log_trace!(logger, "Updating ChannelMonitor to id {} for channel {}", update.update_id, log_funding_info!(monitor));
778                                 let update_res = monitor.update_monitor(update, &self.broadcaster, &self.fee_estimator, &self.logger);
779
780                                 let update_id = update.update_id;
781                                 let mut pending_monitor_updates = monitor_state.pending_monitor_updates.lock().unwrap();
782                                 let persist_res = if update_res.is_err() {
783                                         // Even if updating the monitor returns an error, the monitor's state will
784                                         // still be changed. Therefore, we should persist the updated monitor despite the error.
785                                         // We don't want to persist a `monitor_update` which results in a failure to apply later
786                                         // while reading `channel_monitor` with updates from storage. Instead, we should persist
787                                         // the entire `channel_monitor` here.
788                                         log_warn!(logger, "Failed to update ChannelMonitor for channel {}. Going ahead and persisting the entire ChannelMonitor", log_funding_info!(monitor));
789                                         self.persister.update_persisted_channel(funding_txo, None, monitor)
790                                 } else {
791                                         self.persister.update_persisted_channel(funding_txo, Some(update), monitor)
792                                 };
793                                 match persist_res {
794                                         ChannelMonitorUpdateStatus::InProgress => {
795                                                 pending_monitor_updates.push(update_id);
796                                                 log_debug!(logger,
797                                                         "Persistence of ChannelMonitorUpdate id {:?} for channel {} in progress",
798                                                         update_id,
799                                                         log_funding_info!(monitor)
800                                                 );
801                                         },
802                                         ChannelMonitorUpdateStatus::Completed => {
803                                                 log_debug!(logger,
804                                                         "Persistence of ChannelMonitorUpdate id {:?} for channel {} completed",
805                                                         update_id,
806                                                         log_funding_info!(monitor)
807                                                 );
808                                         },
809                                         ChannelMonitorUpdateStatus::UnrecoverableError => {
810                                                 // Take the monitors lock for writing so that we poison it and any future
811                                                 // operations going forward fail immediately.
812                                                 core::mem::drop(pending_monitor_updates);
813                                                 core::mem::drop(monitors);
814                                                 let _poison = self.monitors.write().unwrap();
815                                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
816                                                 log_error!(logger, "{}", err_str);
817                                                 panic!("{}", err_str);
818                                         },
819                                 }
820                                 if update_res.is_err() {
821                                         ChannelMonitorUpdateStatus::InProgress
822                                 } else {
823                                         persist_res
824                                 }
825                         }
826                 }
827         }
828
829         fn release_pending_monitor_events(&self) -> Vec<(OutPoint, ChannelId, Vec<MonitorEvent>, Option<PublicKey>)> {
830                 let mut pending_monitor_events = self.pending_monitor_events.lock().unwrap().split_off(0);
831                 for monitor_state in self.monitors.read().unwrap().values() {
832                         let monitor_events = monitor_state.monitor.get_and_clear_pending_monitor_events();
833                         if monitor_events.len() > 0 {
834                                 let monitor_outpoint = monitor_state.monitor.get_funding_txo().0;
835                                 let monitor_channel_id = monitor_state.monitor.channel_id();
836                                 let counterparty_node_id = monitor_state.monitor.get_counterparty_node_id();
837                                 pending_monitor_events.push((monitor_outpoint, monitor_channel_id, monitor_events, counterparty_node_id));
838                         }
839                 }
840                 pending_monitor_events
841         }
842 }
843
844 impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
845         where C::Target: chain::Filter,
846               T::Target: BroadcasterInterface,
847               F::Target: FeeEstimator,
848               L::Target: Logger,
849               P::Target: Persist<ChannelSigner>,
850 {
851         /// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
852         ///
853         /// For channels featuring anchor outputs, this method will also process [`BumpTransaction`]
854         /// events produced from each [`ChannelMonitor`] while there is a balance to claim onchain
855         /// within each channel. As the confirmation of a commitment transaction may be critical to the
856         /// safety of funds, we recommend invoking this every 30 seconds, or lower if running in an
857         /// environment with spotty connections, like on mobile.
858         ///
859         /// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
860         /// order to handle these events.
861         ///
862         /// [`SpendableOutputs`]: events::Event::SpendableOutputs
863         /// [`BumpTransaction`]: events::Event::BumpTransaction
864         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
865                 for monitor_state in self.monitors.read().unwrap().values() {
866                         monitor_state.monitor.process_pending_events(&handler);
867                 }
868         }
869 }
870
871 #[cfg(test)]
872 mod tests {
873         use crate::check_added_monitors;
874         use crate::{expect_payment_path_successful, get_event_msg};
875         use crate::{get_htlc_update_msgs, get_revoke_commit_msgs};
876         use crate::chain::{ChannelMonitorUpdateStatus, Watch};
877         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
878         use crate::ln::functional_test_utils::*;
879         use crate::ln::msgs::ChannelMessageHandler;
880
881         #[test]
882         fn test_async_ooo_offchain_updates() {
883                 // Test that if we have multiple offchain updates being persisted and they complete
884                 // out-of-order, the ChainMonitor waits until all have completed before informing the
885                 // ChannelManager.
886                 let chanmon_cfgs = create_chanmon_cfgs(2);
887                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
888                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
889                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
890                 create_announced_chan_between_nodes(&nodes, 0, 1);
891
892                 // Route two payments to be claimed at the same time.
893                 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
894                 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
895
896                 chanmon_cfgs[1].persister.offchain_monitor_updates.lock().unwrap().clear();
897                 chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
898                 chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
899
900                 nodes[1].node.claim_funds(payment_preimage_1);
901                 check_added_monitors!(nodes[1], 1);
902                 nodes[1].node.claim_funds(payment_preimage_2);
903                 check_added_monitors!(nodes[1], 1);
904
905                 let persistences = chanmon_cfgs[1].persister.offchain_monitor_updates.lock().unwrap().clone();
906                 assert_eq!(persistences.len(), 1);
907                 let (funding_txo, updates) = persistences.iter().next().unwrap();
908                 assert_eq!(updates.len(), 2);
909
910                 // Note that updates is a HashMap so the ordering here is actually random. This shouldn't
911                 // fail either way but if it fails intermittently it's depending on the ordering of updates.
912                 let mut update_iter = updates.iter();
913                 let next_update = update_iter.next().unwrap().clone();
914                 // Should contain next_update when pending updates listed.
915                 #[cfg(not(c_bindings))]
916                 assert!(nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().get(funding_txo)
917                         .unwrap().contains(&next_update));
918                 #[cfg(c_bindings)]
919                 assert!(nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().iter()
920                         .find(|(txo, _)| txo == funding_txo).unwrap().1.contains(&next_update));
921                 nodes[1].chain_monitor.chain_monitor.channel_monitor_updated(*funding_txo, next_update.clone()).unwrap();
922                 // Should not contain the previously pending next_update when pending updates listed.
923                 #[cfg(not(c_bindings))]
924                 assert!(!nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().get(funding_txo)
925                         .unwrap().contains(&next_update));
926                 #[cfg(c_bindings)]
927                 assert!(!nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().iter()
928                         .find(|(txo, _)| txo == funding_txo).unwrap().1.contains(&next_update));
929                 assert!(nodes[1].chain_monitor.release_pending_monitor_events().is_empty());
930                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
931                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
932                 nodes[1].chain_monitor.chain_monitor.channel_monitor_updated(*funding_txo, update_iter.next().unwrap().clone()).unwrap();
933
934                 let claim_events = nodes[1].node.get_and_clear_pending_events();
935                 assert_eq!(claim_events.len(), 2);
936                 match claim_events[0] {
937                         Event::PaymentClaimed { ref payment_hash, amount_msat: 1_000_000, .. } => {
938                                 assert_eq!(payment_hash_1, *payment_hash);
939                         },
940                         _ => panic!("Unexpected event"),
941                 }
942                 match claim_events[1] {
943                         Event::PaymentClaimed { ref payment_hash, amount_msat: 1_000_000, .. } => {
944                                 assert_eq!(payment_hash_2, *payment_hash);
945                         },
946                         _ => panic!("Unexpected event"),
947                 }
948
949                 // Now manually walk the commitment signed dance - because we claimed two payments
950                 // back-to-back it doesn't fit into the neat walk commitment_signed_dance does.
951
952                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
953                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
954                 expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
955                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
956                 check_added_monitors!(nodes[0], 1);
957                 let (as_first_raa, as_first_update) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
958
959                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
960                 check_added_monitors!(nodes[1], 1);
961                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
962                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_update);
963                 check_added_monitors!(nodes[1], 1);
964                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
965
966                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
967                 expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
968                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
969                 check_added_monitors!(nodes[0], 1);
970                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
971                 expect_payment_path_successful!(nodes[0]);
972                 check_added_monitors!(nodes[0], 1);
973                 let (as_second_raa, as_second_update) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
974
975                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
976                 check_added_monitors!(nodes[1], 1);
977                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update);
978                 check_added_monitors!(nodes[1], 1);
979                 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
980
981                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
982                 expect_payment_path_successful!(nodes[0]);
983                 check_added_monitors!(nodes[0], 1);
984         }
985
986         #[test]
987         #[cfg(feature = "std")]
988         fn update_during_chainsync_poisons_channel() {
989                 let chanmon_cfgs = create_chanmon_cfgs(2);
990                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
991                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
992                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
993                 create_announced_chan_between_nodes(&nodes, 0, 1);
994
995                 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::UnrecoverableError);
996
997                 assert!(std::panic::catch_unwind(|| {
998                         // Returning an UnrecoverableError should always panic immediately
999                         connect_blocks(&nodes[0], 1);
1000                 }).is_err());
1001                 assert!(std::panic::catch_unwind(|| {
1002                         // ...and also poison our locks causing later use to panic as well
1003                         core::mem::drop(nodes);
1004                 }).is_err());
1005         }
1006 }
1007