e17e2dbd34b83afd0a5edba181c59fd9a7f334f4
[rust-lightning] / lightning / src / chain / chainmonitor.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Logic to connect off-chain channel management with on-chain transaction monitoring.
11 //!
12 //! [`ChainMonitor`] is an implementation of [`chain::Watch`] used both to process blocks and to
13 //! update [`ChannelMonitor`]s accordingly. If any on-chain events need further processing, it will
14 //! make those available as [`MonitorEvent`]s to be consumed.
15 //!
16 //! [`ChainMonitor`] is parameterized by an optional chain source, which must implement the
17 //! [`chain::Filter`] trait. This provides a mechanism to signal new relevant outputs back to light
18 //! clients, such that transactions spending those outputs are included in block data.
19 //!
20 //! [`ChainMonitor`] may be used directly to monitor channels locally or as a part of a distributed
21 //! setup to monitor channels remotely. In the latter case, a custom [`chain::Watch`] implementation
22 //! would be responsible for routing each update to a remote server and for retrieving monitor
23 //! events. The remote server would make use of [`ChainMonitor`] for block processing and for
24 //! servicing [`ChannelMonitor`] updates from the client.
25
26 use bitcoin::blockdata::block::BlockHeader;
27 use bitcoin::hash_types::{Txid, BlockHash};
28
29 use crate::chain;
30 use crate::chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput};
31 use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
32 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, Balance, MonitorEvent, TransactionOutputs, LATENCY_GRACE_PERIOD_BLOCKS};
33 use crate::chain::transaction::{OutPoint, TransactionData};
34 use crate::sign::WriteableEcdsaChannelSigner;
35 use crate::events;
36 use crate::events::{Event, EventHandler};
37 use crate::util::atomic_counter::AtomicCounter;
38 use crate::util::logger::Logger;
39 use crate::util::errors::APIError;
40 use crate::util::wakers::{Future, Notifier};
41 use crate::ln::channelmanager::ChannelDetails;
42
43 use crate::prelude::*;
44 use crate::sync::{RwLock, RwLockReadGuard, Mutex, MutexGuard};
45 use core::iter::FromIterator;
46 use core::ops::Deref;
47 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
48 use bitcoin::secp256k1::PublicKey;
49
50 #[derive(Clone, Copy, Hash, PartialEq, Eq)]
51 /// A specific update's ID stored in a `MonitorUpdateId`, separated out to make the contents
52 /// entirely opaque.
53 enum UpdateOrigin {
54         /// An update that was generated by the `ChannelManager` (via our `chain::Watch`
55         /// implementation). This corresponds to an actual [`ChannelMonitorUpdate::update_id`] field
56         /// and [`ChannelMonitor::get_latest_update_id`].
57         OffChain(u64),
58         /// An update that was generated during blockchain processing. The ID here is specific to the
59         /// generating [`ChainMonitor`] and does *not* correspond to any on-disk IDs.
60         ChainSync(u64),
61 }
62
63 /// An opaque identifier describing a specific [`Persist`] method call.
64 #[derive(Clone, Copy, Hash, PartialEq, Eq)]
65 pub struct MonitorUpdateId {
66         contents: UpdateOrigin,
67 }
68
69 impl MonitorUpdateId {
70         pub(crate) fn from_monitor_update(update: &ChannelMonitorUpdate) -> Self {
71                 Self { contents: UpdateOrigin::OffChain(update.update_id) }
72         }
73         pub(crate) fn from_new_monitor<ChannelSigner: WriteableEcdsaChannelSigner>(monitor: &ChannelMonitor<ChannelSigner>) -> Self {
74                 Self { contents: UpdateOrigin::OffChain(monitor.get_latest_update_id()) }
75         }
76 }
77
78 /// `Persist` defines behavior for persisting channel monitors: this could mean
79 /// writing once to disk, and/or uploading to one or more backup services.
80 ///
81 /// Each method can return two possible values:
82 ///  * If persistence (including any relevant `fsync()` calls) happens immediately, the
83 ///    implementation should return [`ChannelMonitorUpdateStatus::Completed`], indicating normal
84 ///    channel operation should continue.
85 ///  * If persistence happens asynchronously, implementations should first ensure the
86 ///    [`ChannelMonitor`] or [`ChannelMonitorUpdate`] are written durably to disk, and then return
87 ///    [`ChannelMonitorUpdateStatus::InProgress`] while the update continues in the background.
88 ///    Once the update completes, [`ChainMonitor::channel_monitor_updated`] should be called with
89 ///    the corresponding [`MonitorUpdateId`].
90 ///
91 ///    Note that unlike the direct [`chain::Watch`] interface,
92 ///    [`ChainMonitor::channel_monitor_updated`] must be called once for *each* update which occurs.
93 ///
94 ///    If persistence fails for some reason, implementations should still return
95 ///    [`ChannelMonitorUpdateStatus::InProgress`] and attempt to shut down or otherwise resolve the
96 ///    situation ASAP.
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 funding_outpoints: HashSet<OutPoint> = HashSet::from_iter(self.monitors.read().unwrap().keys().cloned());
289                 for funding_outpoint in funding_outpoints.iter() {
290                         let monitor_lock = self.monitors.read().unwrap();
291                         if let Some(monitor_state) = monitor_lock.get(funding_outpoint) {
292                                 self.update_monitor_with_chain_data(header, best_height, txdata, &process, funding_outpoint, &monitor_state);
293                         }
294                 }
295
296                 // do some followup cleanup if any funding outpoints were added in between iterations
297                 let monitor_states = self.monitors.write().unwrap();
298                 for (funding_outpoint, monitor_state) in monitor_states.iter() {
299                         if !funding_outpoints.contains(funding_outpoint) {
300                                 self.update_monitor_with_chain_data(header, best_height, txdata, &process, funding_outpoint, &monitor_state);
301                         }
302                 }
303
304                 if let Some(height) = best_height {
305                         // If the best block height is being updated, update highest_chain_height under the
306                         // monitors write lock.
307                         let old_height = self.highest_chain_height.load(Ordering::Acquire);
308                         let new_height = height as usize;
309                         if new_height > old_height {
310                                 self.highest_chain_height.store(new_height, Ordering::Release);
311                         }
312                 }
313         }
314
315         fn update_monitor_with_chain_data<FN>(&self, header: &BlockHeader, best_height: Option<u32>, txdata: &TransactionData, process: FN, funding_outpoint: &OutPoint, monitor_state: &MonitorHolder<ChannelSigner>) where FN: Fn(&ChannelMonitor<ChannelSigner>, &TransactionData) -> Vec<TransactionOutputs> {
316                 let monitor = &monitor_state.monitor;
317                 let mut txn_outputs;
318                 {
319                         txn_outputs = process(monitor, txdata);
320                         let update_id = MonitorUpdateId {
321                                 contents: UpdateOrigin::ChainSync(self.sync_persistence_id.get_increment()),
322                         };
323                         let mut pending_monitor_updates = monitor_state.pending_monitor_updates.lock().unwrap();
324                         if let Some(height) = best_height {
325                                 if !monitor_state.has_pending_chainsync_updates(&pending_monitor_updates) {
326                                         // If there are not ChainSync persists awaiting completion, go ahead and
327                                         // set last_chain_persist_height here - we wouldn't want the first
328                                         // InProgress to always immediately be considered "overly delayed".
329                                         monitor_state.last_chain_persist_height.store(height as usize, Ordering::Release);
330                                 }
331                         }
332
333                         log_trace!(self.logger, "Syncing Channel Monitor for channel {}", log_funding_info!(monitor));
334                         match self.persister.update_persisted_channel(*funding_outpoint, None, monitor, update_id) {
335                                 ChannelMonitorUpdateStatus::Completed =>
336                                         log_trace!(self.logger, "Finished syncing Channel Monitor for channel {}", log_funding_info!(monitor)),
337                                 ChannelMonitorUpdateStatus::InProgress => {
338                                         log_debug!(self.logger, "Channel Monitor sync for channel {} in progress, holding events until completion!", log_funding_info!(monitor));
339                                         pending_monitor_updates.push(update_id);
340                                 }
341                         }
342                 }
343
344                 // Register any new outputs with the chain source for filtering, storing any dependent
345                 // transactions from within the block that previously had not been included in txdata.
346                 if let Some(ref chain_source) = self.chain_source {
347                         let block_hash = header.block_hash();
348                         for (txid, mut outputs) in txn_outputs.drain(..) {
349                                 for (idx, output) in outputs.drain(..) {
350                                         // Register any new outputs with the chain source for filtering
351                                         let output = WatchedOutput {
352                                                 block_hash: Some(block_hash),
353                                                 outpoint: OutPoint { txid, index: idx as u16 },
354                                                 script_pubkey: output.script_pubkey,
355                                         };
356                                         chain_source.register_output(output)
357                                 }
358                         }
359                 }
360         }
361
362         /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
363         ///
364         /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
365         /// will call back to it indicating transactions and outputs of interest. This allows clients to
366         /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
367         /// always need to fetch full blocks absent another means for determining which blocks contain
368         /// transactions relevant to the watched channels.
369         pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
370                 Self {
371                         monitors: RwLock::new(HashMap::new()),
372                         sync_persistence_id: AtomicCounter::new(),
373                         chain_source,
374                         broadcaster,
375                         logger,
376                         fee_estimator: feeest,
377                         persister,
378                         pending_monitor_events: Mutex::new(Vec::new()),
379                         highest_chain_height: AtomicUsize::new(0),
380                         event_notifier: Notifier::new(),
381                 }
382         }
383
384         /// Gets the balances in the contained [`ChannelMonitor`]s which are claimable on-chain or
385         /// claims which are awaiting confirmation.
386         ///
387         /// Includes the balances from each [`ChannelMonitor`] *except* those included in
388         /// `ignored_channels`.
389         ///
390         /// See [`ChannelMonitor::get_claimable_balances`] for more details on the exact criteria for
391         /// inclusion in the return value.
392         pub fn get_claimable_balances(&self, ignored_channels: &[&ChannelDetails]) -> Vec<Balance> {
393                 let mut ret = Vec::new();
394                 let monitor_states = self.monitors.read().unwrap();
395                 for (_, monitor_state) in monitor_states.iter().filter(|(funding_outpoint, _)| {
396                         for chan in ignored_channels {
397                                 if chan.funding_txo.as_ref() == Some(funding_outpoint) {
398                                         return false;
399                                 }
400                         }
401                         true
402                 }) {
403                         ret.append(&mut monitor_state.monitor.get_claimable_balances());
404                 }
405                 ret
406         }
407
408         /// Gets the [`LockedChannelMonitor`] for a given funding outpoint, returning an `Err` if no
409         /// such [`ChannelMonitor`] is currently being monitored for.
410         ///
411         /// Note that the result holds a mutex over our monitor set, and should not be held
412         /// indefinitely.
413         pub fn get_monitor(&self, funding_txo: OutPoint) -> Result<LockedChannelMonitor<'_, ChannelSigner>, ()> {
414                 let lock = self.monitors.read().unwrap();
415                 if lock.get(&funding_txo).is_some() {
416                         Ok(LockedChannelMonitor { lock, funding_txo })
417                 } else {
418                         Err(())
419                 }
420         }
421
422         /// Lists the funding outpoint of each [`ChannelMonitor`] being monitored.
423         ///
424         /// Note that [`ChannelMonitor`]s are not removed when a channel is closed as they are always
425         /// monitoring for on-chain state resolutions.
426         pub fn list_monitors(&self) -> Vec<OutPoint> {
427                 self.monitors.read().unwrap().keys().map(|outpoint| *outpoint).collect()
428         }
429
430         #[cfg(not(c_bindings))]
431         /// Lists the pending updates for each [`ChannelMonitor`] (by `OutPoint` being monitored).
432         pub fn list_pending_monitor_updates(&self) -> HashMap<OutPoint, Vec<MonitorUpdateId>> {
433                 self.monitors.read().unwrap().iter().map(|(outpoint, holder)| {
434                         (*outpoint, holder.pending_monitor_updates.lock().unwrap().clone())
435                 }).collect()
436         }
437
438         #[cfg(c_bindings)]
439         /// Lists the pending updates for each [`ChannelMonitor`] (by `OutPoint` being monitored).
440         pub fn list_pending_monitor_updates(&self) -> Vec<(OutPoint, Vec<MonitorUpdateId>)> {
441                 self.monitors.read().unwrap().iter().map(|(outpoint, holder)| {
442                         (*outpoint, holder.pending_monitor_updates.lock().unwrap().clone())
443                 }).collect()
444         }
445
446
447         #[cfg(test)]
448         pub fn remove_monitor(&self, funding_txo: &OutPoint) -> ChannelMonitor<ChannelSigner> {
449                 self.monitors.write().unwrap().remove(funding_txo).unwrap().monitor
450         }
451
452         /// Indicates the persistence of a [`ChannelMonitor`] has completed after
453         /// [`ChannelMonitorUpdateStatus::InProgress`] was returned from an update operation.
454         ///
455         /// Thus, the anticipated use is, at a high level:
456         ///  1) This [`ChainMonitor`] calls [`Persist::update_persisted_channel`] which stores the
457         ///     update to disk and begins updating any remote (e.g. watchtower/backup) copies,
458         ///     returning [`ChannelMonitorUpdateStatus::InProgress`],
459         ///  2) once all remote copies are updated, you call this function with the
460         ///     `completed_update_id` that completed, and once all pending updates have completed the
461         ///     channel will be re-enabled.
462         //      Note that we re-enable only after `UpdateOrigin::OffChain` updates complete, we don't
463         //      care about `UpdateOrigin::ChainSync` updates for the channel state being updated. We
464         //      only care about `UpdateOrigin::ChainSync` for returning `MonitorEvent`s.
465         ///
466         /// Returns an [`APIError::APIMisuseError`] if `funding_txo` does not match any currently
467         /// registered [`ChannelMonitor`]s.
468         pub fn channel_monitor_updated(&self, funding_txo: OutPoint, completed_update_id: MonitorUpdateId) -> Result<(), APIError> {
469                 let monitors = self.monitors.read().unwrap();
470                 let monitor_data = if let Some(mon) = monitors.get(&funding_txo) { mon } else {
471                         return Err(APIError::APIMisuseError { err: format!("No ChannelMonitor matching funding outpoint {:?} found", funding_txo) });
472                 };
473                 let mut pending_monitor_updates = monitor_data.pending_monitor_updates.lock().unwrap();
474                 pending_monitor_updates.retain(|update_id| *update_id != completed_update_id);
475
476                 match completed_update_id {
477                         MonitorUpdateId { contents: UpdateOrigin::OffChain(_) } => {
478                                 // Note that we only check for `UpdateOrigin::OffChain` failures here - if
479                                 // we're being told that a `UpdateOrigin::OffChain` monitor update completed,
480                                 // we only care about ensuring we don't tell the `ChannelManager` to restore
481                                 // the channel to normal operation until all `UpdateOrigin::OffChain` updates
482                                 // complete.
483                                 // If there's some `UpdateOrigin::ChainSync` update still pending that's okay
484                                 // - we can still update our channel state, just as long as we don't return
485                                 // `MonitorEvent`s from the monitor back to the `ChannelManager` until they
486                                 // complete.
487                                 let monitor_is_pending_updates = monitor_data.has_pending_offchain_updates(&pending_monitor_updates);
488                                 if monitor_is_pending_updates || monitor_data.channel_perm_failed.load(Ordering::Acquire) {
489                                         // If there are still monitor updates pending (or an old monitor update
490                                         // finished after a later one perm-failed), we cannot yet construct an
491                                         // Completed event.
492                                         return Ok(());
493                                 }
494                                 self.pending_monitor_events.lock().unwrap().push((funding_txo, vec![MonitorEvent::Completed {
495                                         funding_txo,
496                                         monitor_update_id: monitor_data.monitor.get_latest_update_id(),
497                                 }], monitor_data.monitor.get_counterparty_node_id()));
498                         },
499                         MonitorUpdateId { contents: UpdateOrigin::ChainSync(_) } => {
500                                 if !monitor_data.has_pending_chainsync_updates(&pending_monitor_updates) {
501                                         monitor_data.last_chain_persist_height.store(self.highest_chain_height.load(Ordering::Acquire), Ordering::Release);
502                                         // The next time release_pending_monitor_events is called, any events for this
503                                         // ChannelMonitor will be returned.
504                                 }
505                         },
506                 }
507                 self.event_notifier.notify();
508                 Ok(())
509         }
510
511         /// This wrapper avoids having to update some of our tests for now as they assume the direct
512         /// chain::Watch API wherein we mark a monitor fully-updated by just calling
513         /// channel_monitor_updated once with the highest ID.
514         #[cfg(any(test, fuzzing))]
515         pub fn force_channel_monitor_updated(&self, funding_txo: OutPoint, monitor_update_id: u64) {
516                 let monitors = self.monitors.read().unwrap();
517                 let counterparty_node_id = monitors.get(&funding_txo).and_then(|m| m.monitor.get_counterparty_node_id());
518                 self.pending_monitor_events.lock().unwrap().push((funding_txo, vec![MonitorEvent::Completed {
519                         funding_txo,
520                         monitor_update_id,
521                 }], counterparty_node_id));
522                 self.event_notifier.notify();
523         }
524
525         #[cfg(any(test, feature = "_test_utils"))]
526         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
527                 use crate::events::EventsProvider;
528                 let events = core::cell::RefCell::new(Vec::new());
529                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
530                 self.process_pending_events(&event_handler);
531                 events.into_inner()
532         }
533
534         /// Processes any events asynchronously in the order they were generated since the last call
535         /// using the given event handler.
536         ///
537         /// See the trait-level documentation of [`EventsProvider`] for requirements.
538         ///
539         /// [`EventsProvider`]: crate::events::EventsProvider
540         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
541                 &self, handler: H
542         ) {
543                 // Sadly we can't hold the monitors read lock through an async call. Thus we have to do a
544                 // crazy dance to process a monitor's events then only remove them once we've done so.
545                 let mons_to_process = self.monitors.read().unwrap().keys().cloned().collect::<Vec<_>>();
546                 for funding_txo in mons_to_process {
547                         let mut ev;
548                         super::channelmonitor::process_events_body!(
549                                 self.monitors.read().unwrap().get(&funding_txo).map(|m| &m.monitor), ev, handler(ev).await);
550                 }
551         }
552
553         /// Gets a [`Future`] that completes when an event is available either via
554         /// [`chain::Watch::release_pending_monitor_events`] or
555         /// [`EventsProvider::process_pending_events`].
556         ///
557         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
558         /// [`ChainMonitor`] and should instead register actions to be taken later.
559         ///
560         /// [`EventsProvider::process_pending_events`]: crate::events::EventsProvider::process_pending_events
561         pub fn get_update_future(&self) -> Future {
562                 self.event_notifier.get_future()
563         }
564
565         /// Triggers rebroadcasts/fee-bumps of pending claims from a force-closed channel. This is
566         /// crucial in preventing certain classes of pinning attacks, detecting substantial mempool
567         /// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend
568         /// invoking this every 30 seconds, or lower if running in an environment with spotty
569         /// connections, like on mobile.
570         pub fn rebroadcast_pending_claims(&self) {
571                 let monitors = self.monitors.read().unwrap();
572                 for (_, monitor_holder) in &*monitors {
573                         monitor_holder.monitor.rebroadcast_pending_claims(
574                                 &*self.broadcaster, &*self.fee_estimator, &*self.logger
575                         )
576                 }
577         }
578 }
579
580 impl<ChannelSigner: WriteableEcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
581 chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P>
582 where
583         C::Target: chain::Filter,
584         T::Target: BroadcasterInterface,
585         F::Target: FeeEstimator,
586         L::Target: Logger,
587         P::Target: Persist<ChannelSigner>,
588 {
589         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
590                 log_debug!(self.logger, "New best block {} at height {} provided via block_connected", header.block_hash(), height);
591                 self.process_chain_data(header, Some(height), &txdata, |monitor, txdata| {
592                         monitor.block_connected(
593                                 header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
594                 });
595         }
596
597         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
598                 let monitor_states = self.monitors.read().unwrap();
599                 log_debug!(self.logger, "Latest block {} at height {} removed via block_disconnected", header.block_hash(), height);
600                 for monitor_state in monitor_states.values() {
601                         monitor_state.monitor.block_disconnected(
602                                 header, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
603                 }
604         }
605 }
606
607 impl<ChannelSigner: WriteableEcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
608 chain::Confirm for ChainMonitor<ChannelSigner, C, T, F, L, P>
609 where
610         C::Target: chain::Filter,
611         T::Target: BroadcasterInterface,
612         F::Target: FeeEstimator,
613         L::Target: Logger,
614         P::Target: Persist<ChannelSigner>,
615 {
616         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
617                 log_debug!(self.logger, "{} provided transactions confirmed at height {} in block {}", txdata.len(), height, header.block_hash());
618                 self.process_chain_data(header, None, txdata, |monitor, txdata| {
619                         monitor.transactions_confirmed(
620                                 header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
621                 });
622         }
623
624         fn transaction_unconfirmed(&self, txid: &Txid) {
625                 log_debug!(self.logger, "Transaction {} reorganized out of chain", txid);
626                 let monitor_states = self.monitors.read().unwrap();
627                 for monitor_state in monitor_states.values() {
628                         monitor_state.monitor.transaction_unconfirmed(txid, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
629                 }
630         }
631
632         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
633                 log_debug!(self.logger, "New best block {} at height {} provided via best_block_updated", header.block_hash(), height);
634                 self.process_chain_data(header, Some(height), &[], |monitor, txdata| {
635                         // While in practice there shouldn't be any recursive calls when given empty txdata,
636                         // it's still possible if a chain::Filter implementation returns a transaction.
637                         debug_assert!(txdata.is_empty());
638                         monitor.best_block_updated(
639                                 header, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
640                 });
641         }
642
643         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)> {
644                 let mut txids = Vec::new();
645                 let monitor_states = self.monitors.read().unwrap();
646                 for monitor_state in monitor_states.values() {
647                         txids.append(&mut monitor_state.monitor.get_relevant_txids());
648                 }
649
650                 txids.sort_unstable();
651                 txids.dedup();
652                 txids
653         }
654 }
655
656 impl<ChannelSigner: WriteableEcdsaChannelSigner, C: Deref , T: Deref , F: Deref , L: Deref , P: Deref >
657 chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
658 where C::Target: chain::Filter,
659             T::Target: BroadcasterInterface,
660             F::Target: FeeEstimator,
661             L::Target: Logger,
662             P::Target: Persist<ChannelSigner>,
663 {
664         /// Adds the monitor that watches the channel referred to by the given outpoint.
665         ///
666         /// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
667         ///
668         /// Note that we persist the given `ChannelMonitor` while holding the `ChainMonitor`
669         /// monitors lock.
670         fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<ChannelMonitorUpdateStatus, ()> {
671                 let mut monitors = self.monitors.write().unwrap();
672                 let entry = match monitors.entry(funding_outpoint) {
673                         hash_map::Entry::Occupied(_) => {
674                                 log_error!(self.logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
675                                 return Err(());
676                         },
677                         hash_map::Entry::Vacant(e) => e,
678                 };
679                 log_trace!(self.logger, "Got new ChannelMonitor for channel {}", log_funding_info!(monitor));
680                 let update_id = MonitorUpdateId::from_new_monitor(&monitor);
681                 let mut pending_monitor_updates = Vec::new();
682                 let persist_res = self.persister.persist_new_channel(funding_outpoint, &monitor, update_id);
683                 match persist_res {
684                         ChannelMonitorUpdateStatus::InProgress => {
685                                 log_info!(self.logger, "Persistence of new ChannelMonitor for channel {} in progress", log_funding_info!(monitor));
686                                 pending_monitor_updates.push(update_id);
687                         },
688                         ChannelMonitorUpdateStatus::Completed => {
689                                 log_info!(self.logger, "Persistence of new ChannelMonitor for channel {} completed", log_funding_info!(monitor));
690                         }
691                 }
692                 if let Some(ref chain_source) = self.chain_source {
693                         monitor.load_outputs_to_watch(chain_source);
694                 }
695                 entry.insert(MonitorHolder {
696                         monitor,
697                         pending_monitor_updates: Mutex::new(pending_monitor_updates),
698                         channel_perm_failed: AtomicBool::new(false),
699                         last_chain_persist_height: AtomicUsize::new(self.highest_chain_height.load(Ordering::Acquire)),
700                 });
701                 Ok(persist_res)
702         }
703
704         /// Note that we persist the given `ChannelMonitor` update while holding the
705         /// `ChainMonitor` monitors lock.
706         fn update_channel(&self, funding_txo: OutPoint, update: &ChannelMonitorUpdate) -> ChannelMonitorUpdateStatus {
707                 // Update the monitor that watches the channel referred to by the given outpoint.
708                 let monitors = self.monitors.read().unwrap();
709                 match monitors.get(&funding_txo) {
710                         None => {
711                                 log_error!(self.logger, "Failed to update channel monitor: no such monitor registered");
712
713                                 // We should never ever trigger this from within ChannelManager. Technically a
714                                 // user could use this object with some proxying in between which makes this
715                                 // possible, but in tests and fuzzing, this should be a panic.
716                                 #[cfg(debug_assertions)]
717                                 panic!("ChannelManager generated a channel update for a channel that was not yet registered!");
718                                 #[cfg(not(debug_assertions))]
719                                 ChannelMonitorUpdateStatus::InProgress
720                         },
721                         Some(monitor_state) => {
722                                 let monitor = &monitor_state.monitor;
723                                 log_trace!(self.logger, "Updating ChannelMonitor for channel {}", log_funding_info!(monitor));
724                                 let update_res = monitor.update_monitor(update, &self.broadcaster, &*self.fee_estimator, &self.logger);
725                                 if update_res.is_err() {
726                                         log_error!(self.logger, "Failed to update ChannelMonitor for channel {}.", log_funding_info!(monitor));
727                                 }
728                                 // Even if updating the monitor returns an error, the monitor's state will
729                                 // still be changed. So, persist the updated monitor despite the error.
730                                 let update_id = MonitorUpdateId::from_monitor_update(update);
731                                 let mut pending_monitor_updates = monitor_state.pending_monitor_updates.lock().unwrap();
732                                 let persist_res = self.persister.update_persisted_channel(funding_txo, Some(update), monitor, update_id);
733                                 match persist_res {
734                                         ChannelMonitorUpdateStatus::InProgress => {
735                                                 pending_monitor_updates.push(update_id);
736                                                 log_debug!(self.logger, "Persistence of ChannelMonitorUpdate for channel {} in progress", log_funding_info!(monitor));
737                                         },
738                                         ChannelMonitorUpdateStatus::Completed => {
739                                                 log_debug!(self.logger, "Persistence of ChannelMonitorUpdate for channel {} completed", log_funding_info!(monitor));
740                                         },
741                                 }
742                                 if update_res.is_err() {
743                                         ChannelMonitorUpdateStatus::InProgress
744                                 } else if monitor_state.channel_perm_failed.load(Ordering::Acquire) {
745                                         ChannelMonitorUpdateStatus::InProgress
746                                 } else {
747                                         persist_res
748                                 }
749                         }
750                 }
751         }
752
753         fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
754                 let mut pending_monitor_events = self.pending_monitor_events.lock().unwrap().split_off(0);
755                 for monitor_state in self.monitors.read().unwrap().values() {
756                         let is_pending_monitor_update = monitor_state.has_pending_chainsync_updates(&monitor_state.pending_monitor_updates.lock().unwrap());
757                         if is_pending_monitor_update &&
758                                         monitor_state.last_chain_persist_height.load(Ordering::Acquire) + LATENCY_GRACE_PERIOD_BLOCKS as usize
759                                                 > self.highest_chain_height.load(Ordering::Acquire)
760                         {
761                                 log_debug!(self.logger, "A Channel Monitor sync is still in progress, refusing to provide monitor events!");
762                         } else {
763                                 if monitor_state.channel_perm_failed.load(Ordering::Acquire) {
764                                         // If a `UpdateOrigin::ChainSync` persistence failed with `PermanantFailure`,
765                                         // we don't really know if the latest `ChannelMonitor` state is on disk or not.
766                                         // We're supposed to hold monitor updates until the latest state is on disk to
767                                         // avoid duplicate events, but the user told us persistence is screw-y and may
768                                         // not complete. We can't hold events forever because we may learn some payment
769                                         // preimage, so instead we just log and hope the user complied with the
770                                         // `PermanentFailure` requirements of having at least the local-disk copy
771                                         // updated.
772                                         log_info!(self.logger, "A Channel Monitor sync returned PermanentFailure. Returning monitor events but duplicate events may appear after reload!");
773                                 }
774                                 if is_pending_monitor_update {
775                                         log_error!(self.logger, "A ChannelMonitor sync took longer than {} blocks to complete.", LATENCY_GRACE_PERIOD_BLOCKS);
776                                         log_error!(self.logger, "   To avoid funds-loss, we are allowing monitor updates to be released.");
777                                         log_error!(self.logger, "   This may cause duplicate payment events to be generated.");
778                                 }
779                                 let monitor_events = monitor_state.monitor.get_and_clear_pending_monitor_events();
780                                 if monitor_events.len() > 0 {
781                                         let monitor_outpoint = monitor_state.monitor.get_funding_txo().0;
782                                         let counterparty_node_id = monitor_state.monitor.get_counterparty_node_id();
783                                         pending_monitor_events.push((monitor_outpoint, monitor_events, counterparty_node_id));
784                                 }
785                         }
786                 }
787                 pending_monitor_events
788         }
789 }
790
791 impl<ChannelSigner: WriteableEcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
792         where C::Target: chain::Filter,
793               T::Target: BroadcasterInterface,
794               F::Target: FeeEstimator,
795               L::Target: Logger,
796               P::Target: Persist<ChannelSigner>,
797 {
798         /// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
799         ///
800         /// For channels featuring anchor outputs, this method will also process [`BumpTransaction`]
801         /// events produced from each [`ChannelMonitor`] while there is a balance to claim onchain
802         /// within each channel. As the confirmation of a commitment transaction may be critical to the
803         /// safety of funds, we recommend invoking this every 30 seconds, or lower if running in an
804         /// environment with spotty connections, like on mobile.
805         ///
806         /// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
807         /// order to handle these events.
808         ///
809         /// [`SpendableOutputs`]: events::Event::SpendableOutputs
810         /// [`BumpTransaction`]: events::Event::BumpTransaction
811         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
812                 for monitor_state in self.monitors.read().unwrap().values() {
813                         monitor_state.monitor.process_pending_events(&handler);
814                 }
815         }
816 }
817
818 #[cfg(test)]
819 mod tests {
820         use crate::check_added_monitors;
821         use crate::{expect_payment_claimed, expect_payment_path_successful, get_event_msg};
822         use crate::{get_htlc_update_msgs, get_local_commitment_txn, get_revoke_commit_msgs, get_route_and_payment_hash, unwrap_send_err};
823         use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Watch};
824         use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS;
825         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
826         use crate::ln::channelmanager::{PaymentSendFailure, PaymentId, RecipientOnionFields};
827         use crate::ln::functional_test_utils::*;
828         use crate::ln::msgs::ChannelMessageHandler;
829         use crate::util::errors::APIError;
830
831         #[test]
832         fn test_async_ooo_offchain_updates() {
833                 // Test that if we have multiple offchain updates being persisted and they complete
834                 // out-of-order, the ChainMonitor waits until all have completed before informing the
835                 // ChannelManager.
836                 let chanmon_cfgs = create_chanmon_cfgs(2);
837                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
838                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
839                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
840                 create_announced_chan_between_nodes(&nodes, 0, 1);
841
842                 // Route two payments to be claimed at the same time.
843                 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
844                 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
845
846                 chanmon_cfgs[1].persister.offchain_monitor_updates.lock().unwrap().clear();
847                 chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
848                 chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
849
850                 nodes[1].node.claim_funds(payment_preimage_1);
851                 check_added_monitors!(nodes[1], 1);
852                 nodes[1].node.claim_funds(payment_preimage_2);
853                 check_added_monitors!(nodes[1], 1);
854
855                 let persistences = chanmon_cfgs[1].persister.offchain_monitor_updates.lock().unwrap().clone();
856                 assert_eq!(persistences.len(), 1);
857                 let (funding_txo, updates) = persistences.iter().next().unwrap();
858                 assert_eq!(updates.len(), 2);
859
860                 // Note that updates is a HashMap so the ordering here is actually random. This shouldn't
861                 // fail either way but if it fails intermittently it's depending on the ordering of updates.
862                 let mut update_iter = updates.iter();
863                 let next_update = update_iter.next().unwrap().clone();
864                 // Should contain next_update when pending updates listed.
865                 #[cfg(not(c_bindings))]
866                 assert!(nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().get(funding_txo)
867                         .unwrap().contains(&next_update));
868                 #[cfg(c_bindings)]
869                 assert!(nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().iter()
870                         .find(|(txo, _)| txo == funding_txo).unwrap().1.contains(&next_update));
871                 nodes[1].chain_monitor.chain_monitor.channel_monitor_updated(*funding_txo, next_update.clone()).unwrap();
872                 // Should not contain the previously pending next_update when pending updates listed.
873                 #[cfg(not(c_bindings))]
874                 assert!(!nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().get(funding_txo)
875                         .unwrap().contains(&next_update));
876                 #[cfg(c_bindings)]
877                 assert!(!nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().iter()
878                         .find(|(txo, _)| txo == funding_txo).unwrap().1.contains(&next_update));
879                 assert!(nodes[1].chain_monitor.release_pending_monitor_events().is_empty());
880                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
881                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
882                 nodes[1].chain_monitor.chain_monitor.channel_monitor_updated(*funding_txo, update_iter.next().unwrap().clone()).unwrap();
883
884                 let claim_events = nodes[1].node.get_and_clear_pending_events();
885                 assert_eq!(claim_events.len(), 2);
886                 match claim_events[0] {
887                         Event::PaymentClaimed { ref payment_hash, amount_msat: 1_000_000, .. } => {
888                                 assert_eq!(payment_hash_1, *payment_hash);
889                         },
890                         _ => panic!("Unexpected event"),
891                 }
892                 match claim_events[1] {
893                         Event::PaymentClaimed { ref payment_hash, amount_msat: 1_000_000, .. } => {
894                                 assert_eq!(payment_hash_2, *payment_hash);
895                         },
896                         _ => panic!("Unexpected event"),
897                 }
898
899                 // Now manually walk the commitment signed dance - because we claimed two payments
900                 // back-to-back it doesn't fit into the neat walk commitment_signed_dance does.
901
902                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
903                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
904                 expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
905                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
906                 check_added_monitors!(nodes[0], 1);
907                 let (as_first_raa, as_first_update) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
908
909                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
910                 check_added_monitors!(nodes[1], 1);
911                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
912                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_update);
913                 check_added_monitors!(nodes[1], 1);
914                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
915
916                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
917                 expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
918                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
919                 check_added_monitors!(nodes[0], 1);
920                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
921                 expect_payment_path_successful!(nodes[0]);
922                 check_added_monitors!(nodes[0], 1);
923                 let (as_second_raa, as_second_update) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
924
925                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
926                 check_added_monitors!(nodes[1], 1);
927                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update);
928                 check_added_monitors!(nodes[1], 1);
929                 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
930
931                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
932                 expect_payment_path_successful!(nodes[0]);
933                 check_added_monitors!(nodes[0], 1);
934         }
935
936         fn do_chainsync_pauses_events(block_timeout: bool) {
937                 // When a chainsync monitor update occurs, any MonitorUpdates should be held before being
938                 // passed upstream to a `ChannelManager` via `Watch::release_pending_monitor_events`. This
939                 // tests that behavior, as well as some ways it might go wrong.
940                 let chanmon_cfgs = create_chanmon_cfgs(2);
941                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
942                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
943                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
944                 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
945
946                 // Get a route for later and rebalance the channel somewhat
947                 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
948                 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
949
950                 // First route a payment that we will claim on chain and give the recipient the preimage.
951                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
952                 nodes[1].node.claim_funds(payment_preimage);
953                 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
954                 nodes[1].node.get_and_clear_pending_msg_events();
955                 check_added_monitors!(nodes[1], 1);
956                 let remote_txn = get_local_commitment_txn!(nodes[1], channel.2);
957                 assert_eq!(remote_txn.len(), 2);
958
959                 // Temp-fail the block connection which will hold the channel-closed event
960                 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
961                 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
962
963                 // Connect B's commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
964                 // channel is now closed, but the ChannelManager doesn't know that yet.
965                 let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
966                 nodes[0].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
967                         &[(0, &remote_txn[0]), (1, &remote_txn[1])], nodes[0].best_block_info().1 + 1);
968                 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
969                 nodes[0].chain_monitor.chain_monitor.best_block_updated(&new_header, nodes[0].best_block_info().1 + 1);
970                 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
971
972                 // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
973                 // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
974                 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
975                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, second_payment_hash,
976                                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)
977                         ), false, APIError::MonitorUpdateInProgress, {});
978                 check_added_monitors!(nodes[0], 1);
979
980                 // However, as the ChainMonitor is still waiting for the original persistence to complete,
981                 // it won't yet release the MonitorEvents.
982                 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
983
984                 if block_timeout {
985                         // After three blocks, pending MontiorEvents should be released either way.
986                         let latest_header = create_dummy_header(nodes[0].best_block_info().0, 0);
987                         nodes[0].chain_monitor.chain_monitor.best_block_updated(&latest_header, nodes[0].best_block_info().1 + LATENCY_GRACE_PERIOD_BLOCKS);
988                 } else {
989                         let persistences = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clone();
990                         for (funding_outpoint, update_ids) in persistences {
991                                 for update_id in update_ids {
992                                         nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_outpoint, update_id).unwrap();
993                                 }
994                         }
995                 }
996
997                 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
998         }
999
1000         #[test]
1001         fn chainsync_pauses_events() {
1002                 do_chainsync_pauses_events(false);
1003                 do_chainsync_pauses_events(true);
1004         }
1005 }