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