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