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