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