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