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