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