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