Persist `ChannelMonitor`s after new blocks are connected
[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::{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};
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, 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. The data can be stored any way you want, but the identifier
96         /// provided by LDK is the channel's outpoint (and it is up to you to maintain a correct
97         /// mapping between the outpoint and the stored channel data). Note that you **must** persist
98         /// every new monitor to disk.
99         ///
100         /// The `update_id` is used to identify this call to [`ChainMonitor::channel_monitor_updated`],
101         /// if you return [`ChannelMonitorUpdateErr::TemporaryFailure`].
102         ///
103         /// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`
104         /// and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
105         ///
106         /// [`Writeable::write`]: crate::util::ser::Writeable::write
107         fn persist_new_channel(&self, channel_id: OutPoint, data: &ChannelMonitor<ChannelSigner>, update_id: MonitorUpdateId) -> Result<(), ChannelMonitorUpdateErr>;
108
109         /// Update one channel's data. The provided [`ChannelMonitor`] has already applied the given
110         /// update.
111         ///
112         /// Note that on every update, you **must** persist either the [`ChannelMonitorUpdate`] or the
113         /// updated monitor itself to disk/backups. See the [`Persist`] trait documentation for more
114         /// details.
115         ///
116         /// During blockchain synchronization operations, this may be called with no
117         /// [`ChannelMonitorUpdate`], in which case the full [`ChannelMonitor`] needs to be persisted.
118         /// Note that after the full [`ChannelMonitor`] is persisted any previous
119         /// [`ChannelMonitorUpdate`]s which were persisted should be discarded - they can no longer be
120         /// applied to the persisted [`ChannelMonitor`] as they were already applied.
121         ///
122         /// If an implementer chooses to persist the updates only, they need to make
123         /// sure that all the updates are applied to the `ChannelMonitors` *before*
124         /// the set of channel monitors is given to the `ChannelManager`
125         /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
126         /// applying a monitor update to a monitor. If full `ChannelMonitors` are
127         /// persisted, then there is no need to persist individual updates.
128         ///
129         /// Note that there could be a performance tradeoff between persisting complete
130         /// channel monitors on every update vs. persisting only updates and applying
131         /// them in batches. The size of each monitor grows `O(number of state updates)`
132         /// whereas updates are small and `O(1)`.
133         ///
134         /// The `update_id` is used to identify this call to [`ChainMonitor::channel_monitor_updated`],
135         /// if you return [`ChannelMonitorUpdateErr::TemporaryFailure`].
136         ///
137         /// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`,
138         /// [`Writeable::write`] on [`ChannelMonitorUpdate`] for writing out an update, and
139         /// [`ChannelMonitorUpdateErr`] for requirements when returning errors.
140         ///
141         /// [`Writeable::write`]: crate::util::ser::Writeable::write
142         fn update_persisted_channel(&self, channel_id: OutPoint, update: &Option<ChannelMonitorUpdate>, data: &ChannelMonitor<ChannelSigner>, update_id: MonitorUpdateId) -> Result<(), ChannelMonitorUpdateErr>;
143 }
144
145 struct MonitorHolder<ChannelSigner: Sign> {
146         monitor: ChannelMonitor<ChannelSigner>,
147         /// The full set of pending monitor updates for this Channel.
148         ///
149         /// Note that this lock must be held during updates to prevent a race where we call
150         /// update_persisted_channel, the user returns a TemporaryFailure, and then calls
151         /// channel_monitor_updated immediately, racing our insertion of the pending update into the
152         /// contained Vec.
153         ///
154         /// Beyond the synchronization of updates themselves, we cannot handle user events until after
155         /// any chain updates have been stored on disk. Thus, we scan this list when returning updates
156         /// to the ChannelManager, refusing to return any updates for a ChannelMonitor which is still
157         /// being persisted fully to disk after a chain update.
158         ///
159         /// This avoids the possibility of handling, e.g. an on-chain claim, generating a claim monitor
160         /// event, resulting in the relevant ChannelManager generating a PaymentSent event and dropping
161         /// the pending payment entry, and then reloading before the monitor is persisted, resulting in
162         /// the ChannelManager re-adding the same payment entry, before the same block is replayed,
163         /// resulting in a duplicate PaymentSent event.
164         pending_monitor_updates: Mutex<Vec<MonitorUpdateId>>,
165         /// When the user returns a PermanentFailure error from an update_persisted_channel call during
166         /// block processing, we inform the ChannelManager that the channel should be closed
167         /// asynchronously. In order to ensure no further changes happen before the ChannelManager has
168         /// processed the closure event, we set this to true and return PermanentFailure for any other
169         /// chain::Watch events.
170         channel_perm_failed: AtomicBool,
171 }
172
173 impl<ChannelSigner: Sign> MonitorHolder<ChannelSigner> {
174         fn has_pending_offchain_updates(&self, pending_monitor_updates_lock: &MutexGuard<Vec<MonitorUpdateId>>) -> bool {
175                 pending_monitor_updates_lock.iter().any(|update_id|
176                         if let UpdateOrigin::OffChain(_) = update_id.contents { true } else { false })
177         }
178         fn has_pending_chainsync_updates(&self, pending_monitor_updates_lock: &MutexGuard<Vec<MonitorUpdateId>>) -> bool {
179                 pending_monitor_updates_lock.iter().any(|update_id|
180                         if let UpdateOrigin::ChainSync(_) = update_id.contents { true } else { false })
181         }
182 }
183
184 /// A read-only reference to a current ChannelMonitor.
185 ///
186 /// Note that this holds a mutex in [`ChainMonitor`] and may block other events until it is
187 /// released.
188 pub struct LockedChannelMonitor<'a, ChannelSigner: Sign> {
189         lock: RwLockReadGuard<'a, HashMap<OutPoint, MonitorHolder<ChannelSigner>>>,
190         funding_txo: OutPoint,
191 }
192
193 impl<ChannelSigner: Sign> Deref for LockedChannelMonitor<'_, ChannelSigner> {
194         type Target = ChannelMonitor<ChannelSigner>;
195         fn deref(&self) -> &ChannelMonitor<ChannelSigner> {
196                 &self.lock.get(&self.funding_txo).expect("Checked at construction").monitor
197         }
198 }
199
200 /// An implementation of [`chain::Watch`] for monitoring channels.
201 ///
202 /// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
203 /// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
204 /// or used independently to monitor channels remotely. See the [module-level documentation] for
205 /// details.
206 ///
207 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
208 /// [module-level documentation]: crate::chain::chainmonitor
209 pub struct ChainMonitor<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
210         where C::Target: chain::Filter,
211         T::Target: BroadcasterInterface,
212         F::Target: FeeEstimator,
213         L::Target: Logger,
214         P::Target: Persist<ChannelSigner>,
215 {
216         monitors: RwLock<HashMap<OutPoint, MonitorHolder<ChannelSigner>>>,
217         /// When we generate a [`MonitorUpdateId`] for a chain-event monitor persistence, we need a
218         /// unique ID, which we calculate by simply getting the next value from this counter. Note that
219         /// the ID is never persisted so it's ok that they reset on restart.
220         sync_persistence_id: AtomicCounter,
221         chain_source: Option<C>,
222         broadcaster: T,
223         logger: L,
224         fee_estimator: F,
225         persister: P,
226         /// "User-provided" (ie persistence-completion/-failed) [`MonitorEvent`]s. These came directly
227         /// from the user and not from a [`ChannelMonitor`].
228         pending_monitor_events: Mutex<Vec<MonitorEvent>>,
229 }
230
231 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P>
232 where C::Target: chain::Filter,
233             T::Target: BroadcasterInterface,
234             F::Target: FeeEstimator,
235             L::Target: Logger,
236             P::Target: Persist<ChannelSigner>,
237 {
238         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
239         /// of a channel and reacting accordingly based on transactions in the given chain data. See
240         /// [`ChannelMonitor::block_connected`] for details. Any HTLCs that were resolved on chain will
241         /// be returned by [`chain::Watch::release_pending_monitor_events`].
242         ///
243         /// Calls back to [`chain::Filter`] if any monitor indicated new outputs to watch. Subsequent
244         /// calls must not exclude any transactions matching the new outputs nor any in-block
245         /// descendants of such transactions. It is not necessary to re-fetch the block to obtain
246         /// updated `txdata`.
247         fn process_chain_data<FN>(&self, header: &BlockHeader, txdata: &TransactionData, process: FN)
248         where
249                 FN: Fn(&ChannelMonitor<ChannelSigner>, &TransactionData) -> Vec<TransactionOutputs>
250         {
251                 let mut dependent_txdata = Vec::new();
252                 {
253                         let monitor_states = self.monitors.write().unwrap();
254                         for (funding_outpoint, monitor_state) in monitor_states.iter() {
255                                 let monitor = &monitor_state.monitor;
256                                 let mut txn_outputs;
257                                 {
258                                         txn_outputs = process(monitor, txdata);
259                                         let update_id = MonitorUpdateId {
260                                                 contents: UpdateOrigin::ChainSync(self.sync_persistence_id.get_increment()),
261                                         };
262                                         let mut pending_monitor_updates = monitor_state.pending_monitor_updates.lock().unwrap();
263
264                                         log_trace!(self.logger, "Syncing Channel Monitor for channel {}", log_funding_info!(monitor));
265                                         match self.persister.update_persisted_channel(*funding_outpoint, &None, monitor, update_id) {
266                                                 Ok(()) =>
267                                                         log_trace!(self.logger, "Finished syncing Channel Monitor for channel {}", log_funding_info!(monitor)),
268                                                 Err(ChannelMonitorUpdateErr::PermanentFailure) => {
269                                                         monitor_state.channel_perm_failed.store(true, Ordering::Release);
270                                                         self.pending_monitor_events.lock().unwrap().push(MonitorEvent::UpdateFailed(*funding_outpoint));
271                                                 },
272                                                 Err(ChannelMonitorUpdateErr::TemporaryFailure) => {
273                                                         log_debug!(self.logger, "Channel Monitor sync for channel {} in progress, holding events until completion!", log_funding_info!(monitor));
274                                                         pending_monitor_updates.push(update_id);
275                                                 },
276                                         }
277                                 }
278
279                                 // Register any new outputs with the chain source for filtering, storing any dependent
280                                 // transactions from within the block that previously had not been included in txdata.
281                                 if let Some(ref chain_source) = self.chain_source {
282                                         let block_hash = header.block_hash();
283                                         for (txid, mut outputs) in txn_outputs.drain(..) {
284                                                 for (idx, output) in outputs.drain(..) {
285                                                         // Register any new outputs with the chain source for filtering and recurse
286                                                         // if it indicates that there are dependent transactions within the block
287                                                         // that had not been previously included in txdata.
288                                                         let output = WatchedOutput {
289                                                                 block_hash: Some(block_hash),
290                                                                 outpoint: OutPoint { txid, index: idx as u16 },
291                                                                 script_pubkey: output.script_pubkey,
292                                                         };
293                                                         if let Some(tx) = chain_source.register_output(output) {
294                                                                 dependent_txdata.push(tx);
295                                                         }
296                                                 }
297                                         }
298                                 }
299                         }
300                 }
301
302                 // Recursively call for any dependent transactions that were identified by the chain source.
303                 if !dependent_txdata.is_empty() {
304                         dependent_txdata.sort_unstable_by_key(|(index, _tx)| *index);
305                         dependent_txdata.dedup_by_key(|(index, _tx)| *index);
306                         let txdata: Vec<_> = dependent_txdata.iter().map(|(index, tx)| (*index, tx)).collect();
307                         self.process_chain_data(header, &txdata, process);
308                 }
309         }
310
311         /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
312         ///
313         /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
314         /// will call back to it indicating transactions and outputs of interest. This allows clients to
315         /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
316         /// always need to fetch full blocks absent another means for determining which blocks contain
317         /// transactions relevant to the watched channels.
318         pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
319                 Self {
320                         monitors: RwLock::new(HashMap::new()),
321                         sync_persistence_id: AtomicCounter::new(),
322                         chain_source,
323                         broadcaster,
324                         logger,
325                         fee_estimator: feeest,
326                         persister,
327                         pending_monitor_events: Mutex::new(Vec::new()),
328                 }
329         }
330
331         /// Gets the balances in the contained [`ChannelMonitor`]s which are claimable on-chain or
332         /// claims which are awaiting confirmation.
333         ///
334         /// Includes the balances from each [`ChannelMonitor`] *except* those included in
335         /// `ignored_channels`, allowing you to filter out balances from channels which are still open
336         /// (and whose balance should likely be pulled from the [`ChannelDetails`]).
337         ///
338         /// See [`ChannelMonitor::get_claimable_balances`] for more details on the exact criteria for
339         /// inclusion in the return value.
340         pub fn get_claimable_balances(&self, ignored_channels: &[&ChannelDetails]) -> Vec<Balance> {
341                 let mut ret = Vec::new();
342                 let monitor_states = self.monitors.read().unwrap();
343                 for (_, monitor_state) in monitor_states.iter().filter(|(funding_outpoint, _)| {
344                         for chan in ignored_channels {
345                                 if chan.funding_txo.as_ref() == Some(funding_outpoint) {
346                                         return false;
347                                 }
348                         }
349                         true
350                 }) {
351                         ret.append(&mut monitor_state.monitor.get_claimable_balances());
352                 }
353                 ret
354         }
355
356         /// Gets the [`LockedChannelMonitor`] for a given funding outpoint, returning an `Err` if no
357         /// such [`ChannelMonitor`] is currently being monitored for.
358         ///
359         /// Note that the result holds a mutex over our monitor set, and should not be held
360         /// indefinitely.
361         pub fn get_monitor(&self, funding_txo: OutPoint) -> Result<LockedChannelMonitor<'_, ChannelSigner>, ()> {
362                 let lock = self.monitors.read().unwrap();
363                 if lock.get(&funding_txo).is_some() {
364                         Ok(LockedChannelMonitor { lock, funding_txo })
365                 } else {
366                         Err(())
367                 }
368         }
369
370         /// Lists the funding outpoint of each [`ChannelMonitor`] being monitored.
371         ///
372         /// Note that [`ChannelMonitor`]s are not removed when a channel is closed as they are always
373         /// monitoring for on-chain state resolutions.
374         pub fn list_monitors(&self) -> Vec<OutPoint> {
375                 self.monitors.read().unwrap().keys().map(|outpoint| *outpoint).collect()
376         }
377
378         #[cfg(test)]
379         pub fn remove_monitor(&self, funding_txo: &OutPoint) -> ChannelMonitor<ChannelSigner> {
380                 self.monitors.write().unwrap().remove(funding_txo).unwrap().monitor
381         }
382
383         /// Indicates the persistence of a [`ChannelMonitor`] has completed after
384         /// [`ChannelMonitorUpdateErr::TemporaryFailure`] was returned from an update operation.
385         ///
386         /// Thus, the anticipated use is, at a high level:
387         ///  1) This [`ChainMonitor`] calls [`Persist::update_persisted_channel`] which stores the
388         ///     update to disk and begins updating any remote (e.g. watchtower/backup) copies,
389         ///     returning [`ChannelMonitorUpdateErr::TemporaryFailure`],
390         ///  2) once all remote copies are updated, you call this function with the
391         ///     `completed_update_id` that completed, and once all pending updates have completed the
392         ///     channel will be re-enabled.
393         //      Note that we re-enable only after `UpdateOrigin::OffChain` updates complete, we don't
394         //      care about `UpdateOrigin::ChainSync` updates for the channel state being updated. We
395         //      only care about `UpdateOrigin::ChainSync` for returning `MonitorEvent`s.
396         ///
397         /// Returns an [`APIError::APIMisuseError`] if `funding_txo` does not match any currently
398         /// registered [`ChannelMonitor`]s.
399         pub fn channel_monitor_updated(&self, funding_txo: OutPoint, completed_update_id: MonitorUpdateId) -> Result<(), APIError> {
400                 let monitors = self.monitors.read().unwrap();
401                 let monitor_data = if let Some(mon) = monitors.get(&funding_txo) { mon } else {
402                         return Err(APIError::APIMisuseError { err: format!("No ChannelMonitor matching funding outpoint {:?} found", funding_txo) });
403                 };
404                 let mut pending_monitor_updates = monitor_data.pending_monitor_updates.lock().unwrap();
405                 pending_monitor_updates.retain(|update_id| *update_id != completed_update_id);
406
407                 match completed_update_id {
408                         MonitorUpdateId { contents: UpdateOrigin::OffChain(_) } => {
409                                 // Note that we only check for `UpdateOrigin::OffChain` failures here - if
410                                 // we're being told that a `UpdateOrigin::OffChain` monitor update completed,
411                                 // we only care about ensuring we don't tell the `ChannelManager` to restore
412                                 // the channel to normal operation until all `UpdateOrigin::OffChain` updates
413                                 // complete.
414                                 // If there's some `UpdateOrigin::ChainSync` update still pending that's okay
415                                 // - we can still update our channel state, just as long as we don't return
416                                 // `MonitorEvent`s from the monitor back to the `ChannelManager` until they
417                                 // complete.
418                                 let monitor_is_pending_updates = monitor_data.has_pending_offchain_updates(&pending_monitor_updates);
419                                 if monitor_is_pending_updates || monitor_data.channel_perm_failed.load(Ordering::Acquire) {
420                                         // If there are still monitor updates pending (or an old monitor update
421                                         // finished after a later one perm-failed), we cannot yet construct an
422                                         // UpdateCompleted event.
423                                         return Ok(());
424                                 }
425                                 self.pending_monitor_events.lock().unwrap().push(MonitorEvent::UpdateCompleted {
426                                         funding_txo,
427                                         monitor_update_id: monitor_data.monitor.get_latest_update_id(),
428                                 });
429                         },
430                         MonitorUpdateId { contents: UpdateOrigin::ChainSync(_) } => {
431                                 // We've already done everything we need to, the next time
432                                 // release_pending_monitor_events is called, any events for this ChannelMonitor
433                                 // will be returned if there's no more SyncPersistId events left.
434                         },
435                 }
436                 Ok(())
437         }
438
439         /// This wrapper avoids having to update some of our tests for now as they assume the direct
440         /// chain::Watch API wherein we mark a monitor fully-updated by just calling
441         /// channel_monitor_updated once with the highest ID.
442         #[cfg(any(test, feature = "fuzztarget"))]
443         pub fn force_channel_monitor_updated(&self, funding_txo: OutPoint, monitor_update_id: u64) {
444                 self.pending_monitor_events.lock().unwrap().push(MonitorEvent::UpdateCompleted {
445                         funding_txo,
446                         monitor_update_id,
447                 });
448         }
449
450         #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
451         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
452                 use util::events::EventsProvider;
453                 let events = core::cell::RefCell::new(Vec::new());
454                 let event_handler = |event: &events::Event| events.borrow_mut().push(event.clone());
455                 self.process_pending_events(&event_handler);
456                 events.into_inner()
457         }
458 }
459
460 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
461 chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P>
462 where
463         C::Target: chain::Filter,
464         T::Target: BroadcasterInterface,
465         F::Target: FeeEstimator,
466         L::Target: Logger,
467         P::Target: Persist<ChannelSigner>,
468 {
469         fn block_connected(&self, block: &Block, height: u32) {
470                 let header = &block.header;
471                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
472                 log_debug!(self.logger, "New best block {} at height {} provided via block_connected", header.block_hash(), height);
473                 self.process_chain_data(header, &txdata, |monitor, txdata| {
474                         monitor.block_connected(
475                                 header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
476                 });
477         }
478
479         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
480                 let monitor_states = self.monitors.read().unwrap();
481                 log_debug!(self.logger, "Latest block {} at height {} removed via block_disconnected", header.block_hash(), height);
482                 for monitor_state in monitor_states.values() {
483                         monitor_state.monitor.block_disconnected(
484                                 header, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
485                 }
486         }
487 }
488
489 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
490 chain::Confirm for ChainMonitor<ChannelSigner, C, T, F, L, P>
491 where
492         C::Target: chain::Filter,
493         T::Target: BroadcasterInterface,
494         F::Target: FeeEstimator,
495         L::Target: Logger,
496         P::Target: Persist<ChannelSigner>,
497 {
498         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
499                 log_debug!(self.logger, "{} provided transactions confirmed at height {} in block {}", txdata.len(), height, header.block_hash());
500                 self.process_chain_data(header, txdata, |monitor, txdata| {
501                         monitor.transactions_confirmed(
502                                 header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
503                 });
504         }
505
506         fn transaction_unconfirmed(&self, txid: &Txid) {
507                 log_debug!(self.logger, "Transaction {} reorganized out of chain", txid);
508                 let monitor_states = self.monitors.read().unwrap();
509                 for monitor_state in monitor_states.values() {
510                         monitor_state.monitor.transaction_unconfirmed(txid, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
511                 }
512         }
513
514         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
515                 log_debug!(self.logger, "New best block {} at height {} provided via best_block_updated", header.block_hash(), height);
516                 self.process_chain_data(header, &[], |monitor, txdata| {
517                         // While in practice there shouldn't be any recursive calls when given empty txdata,
518                         // it's still possible if a chain::Filter implementation returns a transaction.
519                         debug_assert!(txdata.is_empty());
520                         monitor.best_block_updated(
521                                 header, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
522                 });
523         }
524
525         fn get_relevant_txids(&self) -> Vec<Txid> {
526                 let mut txids = Vec::new();
527                 let monitor_states = self.monitors.read().unwrap();
528                 for monitor_state in monitor_states.values() {
529                         txids.append(&mut monitor_state.monitor.get_relevant_txids());
530                 }
531
532                 txids.sort_unstable();
533                 txids.dedup();
534                 txids
535         }
536 }
537
538 impl<ChannelSigner: Sign, C: Deref , T: Deref , F: Deref , L: Deref , P: Deref >
539 chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
540 where C::Target: chain::Filter,
541             T::Target: BroadcasterInterface,
542             F::Target: FeeEstimator,
543             L::Target: Logger,
544             P::Target: Persist<ChannelSigner>,
545 {
546         /// Adds the monitor that watches the channel referred to by the given outpoint.
547         ///
548         /// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
549         ///
550         /// Note that we persist the given `ChannelMonitor` while holding the `ChainMonitor`
551         /// monitors lock.
552         fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
553                 let mut monitors = self.monitors.write().unwrap();
554                 let entry = match monitors.entry(funding_outpoint) {
555                         hash_map::Entry::Occupied(_) => {
556                                 log_error!(self.logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
557                                 return Err(ChannelMonitorUpdateErr::PermanentFailure)},
558                         hash_map::Entry::Vacant(e) => e,
559                 };
560                 let update_id = MonitorUpdateId::from_new_monitor(&monitor);
561                 let mut pending_monitor_updates = Vec::new();
562                 let persist_res = self.persister.persist_new_channel(funding_outpoint, &monitor, update_id);
563                 if persist_res.is_err() {
564                         log_error!(self.logger, "Failed to persist new channel data: {:?}", persist_res);
565                 }
566                 if persist_res == Err(ChannelMonitorUpdateErr::PermanentFailure) {
567                         return persist_res;
568                 } else if persist_res.is_err() {
569                         pending_monitor_updates.push(update_id);
570                 }
571                 {
572                         let funding_txo = monitor.get_funding_txo();
573                         log_trace!(self.logger, "Got new Channel Monitor for channel {}", log_bytes!(funding_txo.0.to_channel_id()[..]));
574
575                         if let Some(ref chain_source) = self.chain_source {
576                                 monitor.load_outputs_to_watch(chain_source);
577                         }
578                 }
579                 entry.insert(MonitorHolder {
580                         monitor,
581                         pending_monitor_updates: Mutex::new(pending_monitor_updates),
582                         channel_perm_failed: AtomicBool::new(false),
583                 });
584                 persist_res
585         }
586
587         /// Note that we persist the given `ChannelMonitor` update while holding the
588         /// `ChainMonitor` monitors lock.
589         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
590                 // Update the monitor that watches the channel referred to by the given outpoint.
591                 let monitors = self.monitors.read().unwrap();
592                 match monitors.get(&funding_txo) {
593                         None => {
594                                 log_error!(self.logger, "Failed to update channel monitor: no such monitor registered");
595
596                                 // We should never ever trigger this from within ChannelManager. Technically a
597                                 // user could use this object with some proxying in between which makes this
598                                 // possible, but in tests and fuzzing, this should be a panic.
599                                 #[cfg(any(test, feature = "fuzztarget"))]
600                                 panic!("ChannelManager generated a channel update for a channel that was not yet registered!");
601                                 #[cfg(not(any(test, feature = "fuzztarget")))]
602                                 Err(ChannelMonitorUpdateErr::PermanentFailure)
603                         },
604                         Some(monitor_state) => {
605                                 let monitor = &monitor_state.monitor;
606                                 log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(monitor));
607                                 let update_res = monitor.update_monitor(&update, &self.broadcaster, &self.fee_estimator, &self.logger);
608                                 if let Err(e) = &update_res {
609                                         log_error!(self.logger, "Failed to update channel monitor: {:?}", e);
610                                 }
611                                 // Even if updating the monitor returns an error, the monitor's state will
612                                 // still be changed. So, persist the updated monitor despite the error.
613                                 let update_id = MonitorUpdateId::from_monitor_update(&update);
614                                 let mut pending_monitor_updates = monitor_state.pending_monitor_updates.lock().unwrap();
615                                 let persist_res = self.persister.update_persisted_channel(funding_txo, &Some(update), monitor, update_id);
616                                 if let Err(e) = persist_res {
617                                         if e == ChannelMonitorUpdateErr::TemporaryFailure {
618                                                 pending_monitor_updates.push(update_id);
619                                         } else {
620                                                 monitor_state.channel_perm_failed.store(true, Ordering::Release);
621                                         }
622                                         log_error!(self.logger, "Failed to persist channel monitor update: {:?}", e);
623                                 }
624                                 if update_res.is_err() {
625                                         Err(ChannelMonitorUpdateErr::PermanentFailure)
626                                 } else if monitor_state.channel_perm_failed.load(Ordering::Acquire) {
627                                         Err(ChannelMonitorUpdateErr::PermanentFailure)
628                                 } else {
629                                         persist_res
630                                 }
631                         }
632                 }
633         }
634
635         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
636                 let mut pending_monitor_events = self.pending_monitor_events.lock().unwrap().split_off(0);
637                 for monitor_state in self.monitors.read().unwrap().values() {
638                         let is_pending_monitor_update = monitor_state.has_pending_chainsync_updates(&monitor_state.pending_monitor_updates.lock().unwrap());
639                         if is_pending_monitor_update {
640                                 log_info!(self.logger, "A Channel Monitor sync is still in progress, refusing to provide monitor events!");
641                         } else {
642                                 if monitor_state.channel_perm_failed.load(Ordering::Acquire) {
643                                         // If a `UpdateOrigin::ChainSync` persistence failed with `PermanantFailure`,
644                                         // we don't really know if the latest `ChannelMonitor` state is on disk or not.
645                                         // We're supposed to hold monitor updates until the latest state is on disk to
646                                         // avoid duplicate events, but the user told us persistence is screw-y and may
647                                         // not complete. We can't hold events forever because we may learn some payment
648                                         // preimage, so instead we just log and hope the user complied with the
649                                         // `PermanentFailure` requirements of having at least the local-disk copy
650                                         // updated.
651                                         log_info!(self.logger, "A Channel Monitor sync returned PermanentFailure. Returning monitor events but duplicate events may appear after reload!");
652                                 }
653                                 pending_monitor_events.append(&mut monitor_state.monitor.get_and_clear_pending_monitor_events());
654                         }
655                 }
656                 pending_monitor_events
657         }
658 }
659
660 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
661         where C::Target: chain::Filter,
662               T::Target: BroadcasterInterface,
663               F::Target: FeeEstimator,
664               L::Target: Logger,
665               P::Target: Persist<ChannelSigner>,
666 {
667         /// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
668         ///
669         /// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
670         /// order to handle these events.
671         ///
672         /// [`SpendableOutputs`]: events::Event::SpendableOutputs
673         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
674                 let mut pending_events = Vec::new();
675                 for monitor_state in self.monitors.read().unwrap().values() {
676                         pending_events.append(&mut monitor_state.monitor.get_and_clear_pending_events());
677                 }
678                 for event in pending_events.drain(..) {
679                         handler.handle_event(&event);
680                 }
681         }
682 }
683
684 #[cfg(test)]
685 mod tests {
686         use ::{check_added_monitors, get_local_commitment_txn};
687         use ln::features::InitFeatures;
688         use ln::functional_test_utils::*;
689         use util::events::MessageSendEventsProvider;
690         use util::test_utils::{OnRegisterOutput, TxOutReference};
691
692         /// Tests that in-block dependent transactions are processed by `block_connected` when not
693         /// included in `txdata` but returned by [`chain::Filter::register_output`]. For instance,
694         /// a (non-anchor) commitment transaction's HTLC output may be spent in the same block as the
695         /// commitment transaction itself. An Electrum client may filter the commitment transaction but
696         /// needs to return the HTLC transaction so it can be processed.
697         #[test]
698         fn connect_block_checks_dependent_transactions() {
699                 let chanmon_cfgs = create_chanmon_cfgs(2);
700                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
701                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
702                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
703                 let channel = create_announced_chan_between_nodes(
704                         &nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
705
706                 // Send a payment, saving nodes[0]'s revoked commitment and HTLC-Timeout transactions.
707                 let (commitment_tx, htlc_tx) = {
708                         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000).0;
709                         let mut txn = get_local_commitment_txn!(nodes[0], channel.2);
710                         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
711
712                         assert_eq!(txn.len(), 2);
713                         (txn.remove(0), txn.remove(0))
714                 };
715
716                 // Set expectations on nodes[1]'s chain source to return dependent transactions.
717                 let htlc_output = TxOutReference(commitment_tx.clone(), 0);
718                 let to_local_output = TxOutReference(commitment_tx.clone(), 1);
719                 let htlc_timeout_output = TxOutReference(htlc_tx.clone(), 0);
720                 nodes[1].chain_source
721                         .expect(OnRegisterOutput { with: htlc_output, returns: Some((1, htlc_tx)) })
722                         .expect(OnRegisterOutput { with: to_local_output, returns: None })
723                         .expect(OnRegisterOutput { with: htlc_timeout_output, returns: None });
724
725                 // Notify nodes[1] that nodes[0]'s revoked commitment transaction was mined. The chain
726                 // source should return the dependent HTLC transaction when the HTLC output is registered.
727                 mine_transaction(&nodes[1], &commitment_tx);
728
729                 // Clean up so uninteresting assertions don't fail.
730                 check_added_monitors!(nodes[1], 1);
731                 nodes[1].node.get_and_clear_pending_msg_events();
732                 nodes[1].node.get_and_clear_pending_events();
733         }
734 }