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