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