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