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