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