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