Handle Persister returning TemporaryFailure for new channels
[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::logger::Logger;
36 use util::events;
37 use util::events::EventHandler;
38 use ln::channelmanager::ChannelDetails;
39
40 use prelude::*;
41 use sync::{RwLock, RwLockReadGuard};
42 use core::ops::Deref;
43
44 /// `Persist` defines behavior for persisting channel monitors: this could mean
45 /// writing once to disk, and/or uploading to one or more backup services.
46 ///
47 /// Note that for every new monitor, you **must** persist the new `ChannelMonitor`
48 /// to disk/backups. And, on every update, you **must** persist either the
49 /// `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk
50 /// of situations such as revoking a transaction, then crashing before this
51 /// revocation can be persisted, then unintentionally broadcasting a revoked
52 /// transaction and losing money. This is a risk because previous channel states
53 /// are toxic, so it's important that whatever channel state is persisted is
54 /// kept up-to-date.
55 pub trait Persist<ChannelSigner: Sign> {
56         /// Persist a new channel's data. The data can be stored any way you want, but
57         /// the identifier provided by Rust-Lightning is the channel's outpoint (and
58         /// it is up to you to maintain a correct mapping between the outpoint and the
59         /// stored channel data). Note that you **must** persist every new monitor to
60         /// disk. See the `Persist` trait documentation for more details.
61         ///
62         /// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`
63         /// and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
64         ///
65         /// [`Writeable::write`]: crate::util::ser::Writeable::write
66         fn persist_new_channel(&self, id: OutPoint, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
67
68         /// Update one channel's data. The provided `ChannelMonitor` has already
69         /// applied the given update.
70         ///
71         /// Note that on every update, you **must** persist either the
72         /// `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
73         /// the `Persist` trait documentation for more details.
74         ///
75         /// If an implementer chooses to persist the updates only, they need to make
76         /// sure that all the updates are applied to the `ChannelMonitors` *before*
77         /// the set of channel monitors is given to the `ChannelManager`
78         /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
79         /// applying a monitor update to a monitor. If full `ChannelMonitors` are
80         /// persisted, then there is no need to persist individual updates.
81         ///
82         /// Note that there could be a performance tradeoff between persisting complete
83         /// channel monitors on every update vs. persisting only updates and applying
84         /// them in batches. The size of each monitor grows `O(number of state updates)`
85         /// whereas updates are small and `O(1)`.
86         ///
87         /// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`,
88         /// [`Writeable::write`] on [`ChannelMonitorUpdate`] for writing out an update, and
89         /// [`ChannelMonitorUpdateErr`] for requirements when returning errors.
90         ///
91         /// [`Writeable::write`]: crate::util::ser::Writeable::write
92         fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
93 }
94
95 struct MonitorHolder<ChannelSigner: Sign> {
96         monitor: ChannelMonitor<ChannelSigner>,
97 }
98
99 /// A read-only reference to a current ChannelMonitor.
100 ///
101 /// Note that this holds a mutex in [`ChainMonitor`] and may block other events until it is
102 /// released.
103 pub struct LockedChannelMonitor<'a, ChannelSigner: Sign> {
104         lock: RwLockReadGuard<'a, HashMap<OutPoint, MonitorHolder<ChannelSigner>>>,
105         funding_txo: OutPoint,
106 }
107
108 impl<ChannelSigner: Sign> Deref for LockedChannelMonitor<'_, ChannelSigner> {
109         type Target = ChannelMonitor<ChannelSigner>;
110         fn deref(&self) -> &ChannelMonitor<ChannelSigner> {
111                 &self.lock.get(&self.funding_txo).expect("Checked at construction").monitor
112         }
113 }
114
115 /// An implementation of [`chain::Watch`] for monitoring channels.
116 ///
117 /// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
118 /// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
119 /// or used independently to monitor channels remotely. See the [module-level documentation] for
120 /// details.
121 ///
122 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
123 /// [module-level documentation]: crate::chain::chainmonitor
124 pub struct ChainMonitor<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
125         where C::Target: chain::Filter,
126         T::Target: BroadcasterInterface,
127         F::Target: FeeEstimator,
128         L::Target: Logger,
129         P::Target: Persist<ChannelSigner>,
130 {
131         monitors: RwLock<HashMap<OutPoint, MonitorHolder<ChannelSigner>>>,
132         chain_source: Option<C>,
133         broadcaster: T,
134         logger: L,
135         fee_estimator: F,
136         persister: P,
137 }
138
139 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P>
140 where C::Target: chain::Filter,
141             T::Target: BroadcasterInterface,
142             F::Target: FeeEstimator,
143             L::Target: Logger,
144             P::Target: Persist<ChannelSigner>,
145 {
146         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
147         /// of a channel and reacting accordingly based on transactions in the given chain data. See
148         /// [`ChannelMonitor::block_connected`] for details. Any HTLCs that were resolved on chain will
149         /// be returned by [`chain::Watch::release_pending_monitor_events`].
150         ///
151         /// Calls back to [`chain::Filter`] if any monitor indicated new outputs to watch. Subsequent
152         /// calls must not exclude any transactions matching the new outputs nor any in-block
153         /// descendants of such transactions. It is not necessary to re-fetch the block to obtain
154         /// updated `txdata`.
155         fn process_chain_data<FN>(&self, header: &BlockHeader, txdata: &TransactionData, process: FN)
156         where
157                 FN: Fn(&ChannelMonitor<ChannelSigner>, &TransactionData) -> Vec<TransactionOutputs>
158         {
159                 let mut dependent_txdata = Vec::new();
160                 let monitor_states = self.monitors.read().unwrap();
161                 for monitor_state in monitor_states.values() {
162                         let mut txn_outputs = process(&monitor_state.monitor, txdata);
163
164                         // Register any new outputs with the chain source for filtering, storing any dependent
165                         // transactions from within the block that previously had not been included in txdata.
166                         if let Some(ref chain_source) = self.chain_source {
167                                 let block_hash = header.block_hash();
168                                 for (txid, mut outputs) in txn_outputs.drain(..) {
169                                         for (idx, output) in outputs.drain(..) {
170                                                 // Register any new outputs with the chain source for filtering and recurse
171                                                 // if it indicates that there are dependent transactions within the block
172                                                 // that had not been previously included in txdata.
173                                                 let output = WatchedOutput {
174                                                         block_hash: Some(block_hash),
175                                                         outpoint: OutPoint { txid, index: idx as u16 },
176                                                         script_pubkey: output.script_pubkey,
177                                                 };
178                                                 if let Some(tx) = chain_source.register_output(output) {
179                                                         dependent_txdata.push(tx);
180                                                 }
181                                         }
182                                 }
183                         }
184                 }
185
186                 // Recursively call for any dependent transactions that were identified by the chain source.
187                 if !dependent_txdata.is_empty() {
188                         dependent_txdata.sort_unstable_by_key(|(index, _tx)| *index);
189                         dependent_txdata.dedup_by_key(|(index, _tx)| *index);
190                         let txdata: Vec<_> = dependent_txdata.iter().map(|(index, tx)| (*index, tx)).collect();
191                         self.process_chain_data(header, &txdata, process);
192                 }
193         }
194
195         /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
196         ///
197         /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
198         /// will call back to it indicating transactions and outputs of interest. This allows clients to
199         /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
200         /// always need to fetch full blocks absent another means for determining which blocks contain
201         /// transactions relevant to the watched channels.
202         pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
203                 Self {
204                         monitors: RwLock::new(HashMap::new()),
205                         chain_source,
206                         broadcaster,
207                         logger,
208                         fee_estimator: feeest,
209                         persister,
210                 }
211         }
212
213         /// Gets the balances in the contained [`ChannelMonitor`]s which are claimable on-chain or
214         /// claims which are awaiting confirmation.
215         ///
216         /// Includes the balances from each [`ChannelMonitor`] *except* those included in
217         /// `ignored_channels`, allowing you to filter out balances from channels which are still open
218         /// (and whose balance should likely be pulled from the [`ChannelDetails`]).
219         ///
220         /// See [`ChannelMonitor::get_claimable_balances`] for more details on the exact criteria for
221         /// inclusion in the return value.
222         pub fn get_claimable_balances(&self, ignored_channels: &[&ChannelDetails]) -> Vec<Balance> {
223                 let mut ret = Vec::new();
224                 let monitor_states = self.monitors.read().unwrap();
225                 for (_, monitor_state) in monitor_states.iter().filter(|(funding_outpoint, _)| {
226                         for chan in ignored_channels {
227                                 if chan.funding_txo.as_ref() == Some(funding_outpoint) {
228                                         return false;
229                                 }
230                         }
231                         true
232                 }) {
233                         ret.append(&mut monitor_state.monitor.get_claimable_balances());
234                 }
235                 ret
236         }
237
238         /// Gets the [`LockedChannelMonitor`] for a given funding outpoint, returning an `Err` if no
239         /// such [`ChannelMonitor`] is currently being monitored for.
240         ///
241         /// Note that the result holds a mutex over our monitor set, and should not be held
242         /// indefinitely.
243         pub fn get_monitor(&self, funding_txo: OutPoint) -> Result<LockedChannelMonitor<'_, ChannelSigner>, ()> {
244                 let lock = self.monitors.read().unwrap();
245                 if lock.get(&funding_txo).is_some() {
246                         Ok(LockedChannelMonitor { lock, funding_txo })
247                 } else {
248                         Err(())
249                 }
250         }
251
252         /// Lists the funding outpoint of each [`ChannelMonitor`] being monitored.
253         ///
254         /// Note that [`ChannelMonitor`]s are not removed when a channel is closed as they are always
255         /// monitoring for on-chain state resolutions.
256         pub fn list_monitors(&self) -> Vec<OutPoint> {
257                 self.monitors.read().unwrap().keys().map(|outpoint| *outpoint).collect()
258         }
259
260         #[cfg(test)]
261         pub fn remove_monitor(&self, funding_txo: &OutPoint) -> ChannelMonitor<ChannelSigner> {
262                 self.monitors.write().unwrap().remove(funding_txo).unwrap().monitor
263         }
264
265         #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
266         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
267                 use util::events::EventsProvider;
268                 let events = core::cell::RefCell::new(Vec::new());
269                 let event_handler = |event: &events::Event| events.borrow_mut().push(event.clone());
270                 self.process_pending_events(&event_handler);
271                 events.into_inner()
272         }
273 }
274
275 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
276 chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P>
277 where
278         C::Target: chain::Filter,
279         T::Target: BroadcasterInterface,
280         F::Target: FeeEstimator,
281         L::Target: Logger,
282         P::Target: Persist<ChannelSigner>,
283 {
284         fn block_connected(&self, block: &Block, height: u32) {
285                 let header = &block.header;
286                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
287                 log_debug!(self.logger, "New best block {} at height {} provided via block_connected", header.block_hash(), height);
288                 self.process_chain_data(header, &txdata, |monitor, txdata| {
289                         monitor.block_connected(
290                                 header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
291                 });
292         }
293
294         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
295                 let monitor_states = self.monitors.read().unwrap();
296                 log_debug!(self.logger, "Latest block {} at height {} removed via block_disconnected", header.block_hash(), height);
297                 for monitor_state in monitor_states.values() {
298                         monitor_state.monitor.block_disconnected(
299                                 header, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
300                 }
301         }
302 }
303
304 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
305 chain::Confirm for ChainMonitor<ChannelSigner, C, T, F, L, P>
306 where
307         C::Target: chain::Filter,
308         T::Target: BroadcasterInterface,
309         F::Target: FeeEstimator,
310         L::Target: Logger,
311         P::Target: Persist<ChannelSigner>,
312 {
313         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
314                 log_debug!(self.logger, "{} provided transactions confirmed at height {} in block {}", txdata.len(), height, header.block_hash());
315                 self.process_chain_data(header, txdata, |monitor, txdata| {
316                         monitor.transactions_confirmed(
317                                 header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
318                 });
319         }
320
321         fn transaction_unconfirmed(&self, txid: &Txid) {
322                 log_debug!(self.logger, "Transaction {} reorganized out of chain", txid);
323                 let monitor_states = self.monitors.read().unwrap();
324                 for monitor_state in monitor_states.values() {
325                         monitor_state.monitor.transaction_unconfirmed(txid, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
326                 }
327         }
328
329         fn best_block_updated(&self, header: &BlockHeader, height: u32) {
330                 log_debug!(self.logger, "New best block {} at height {} provided via best_block_updated", header.block_hash(), height);
331                 self.process_chain_data(header, &[], |monitor, txdata| {
332                         // While in practice there shouldn't be any recursive calls when given empty txdata,
333                         // it's still possible if a chain::Filter implementation returns a transaction.
334                         debug_assert!(txdata.is_empty());
335                         monitor.best_block_updated(
336                                 header, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
337                 });
338         }
339
340         fn get_relevant_txids(&self) -> Vec<Txid> {
341                 let mut txids = Vec::new();
342                 let monitor_states = self.monitors.read().unwrap();
343                 for monitor_state in monitor_states.values() {
344                         txids.append(&mut monitor_state.monitor.get_relevant_txids());
345                 }
346
347                 txids.sort_unstable();
348                 txids.dedup();
349                 txids
350         }
351 }
352
353 impl<ChannelSigner: Sign, C: Deref , T: Deref , F: Deref , L: Deref , P: Deref >
354 chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
355 where C::Target: chain::Filter,
356             T::Target: BroadcasterInterface,
357             F::Target: FeeEstimator,
358             L::Target: Logger,
359             P::Target: Persist<ChannelSigner>,
360 {
361         /// Adds the monitor that watches the channel referred to by the given outpoint.
362         ///
363         /// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
364         ///
365         /// Note that we persist the given `ChannelMonitor` while holding the `ChainMonitor`
366         /// monitors lock.
367         fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
368                 let mut monitors = self.monitors.write().unwrap();
369                 let entry = match monitors.entry(funding_outpoint) {
370                         hash_map::Entry::Occupied(_) => {
371                                 log_error!(self.logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
372                                 return Err(ChannelMonitorUpdateErr::PermanentFailure)},
373                         hash_map::Entry::Vacant(e) => e,
374                 };
375                 let persist_res = self.persister.persist_new_channel(funding_outpoint, &monitor);
376                 if persist_res.is_err() {
377                         log_error!(self.logger, "Failed to persist new channel data: {:?}", persist_res);
378                 }
379                 if persist_res == Err(ChannelMonitorUpdateErr::PermanentFailure) {
380                         return persist_res;
381                 }
382                 {
383                         let funding_txo = monitor.get_funding_txo();
384                         log_trace!(self.logger, "Got new Channel Monitor for channel {}", log_bytes!(funding_txo.0.to_channel_id()[..]));
385
386                         if let Some(ref chain_source) = self.chain_source {
387                                 monitor.load_outputs_to_watch(chain_source);
388                         }
389                 }
390                 entry.insert(MonitorHolder { monitor });
391                 persist_res
392         }
393
394         /// Note that we persist the given `ChannelMonitor` update while holding the
395         /// `ChainMonitor` monitors lock.
396         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
397                 // Update the monitor that watches the channel referred to by the given outpoint.
398                 let monitors = self.monitors.read().unwrap();
399                 match monitors.get(&funding_txo) {
400                         None => {
401                                 log_error!(self.logger, "Failed to update channel monitor: no such monitor registered");
402
403                                 // We should never ever trigger this from within ChannelManager. Technically a
404                                 // user could use this object with some proxying in between which makes this
405                                 // possible, but in tests and fuzzing, this should be a panic.
406                                 #[cfg(any(test, feature = "fuzztarget"))]
407                                 panic!("ChannelManager generated a channel update for a channel that was not yet registered!");
408                                 #[cfg(not(any(test, feature = "fuzztarget")))]
409                                 Err(ChannelMonitorUpdateErr::PermanentFailure)
410                         },
411                         Some(monitor_state) => {
412                                 let monitor = &monitor_state.monitor;
413                                 log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(monitor));
414                                 let update_res = monitor.update_monitor(&update, &self.broadcaster, &self.fee_estimator, &self.logger);
415                                 if let Err(e) = &update_res {
416                                         log_error!(self.logger, "Failed to update channel monitor: {:?}", e);
417                                 }
418                                 // Even if updating the monitor returns an error, the monitor's state will
419                                 // still be changed. So, persist the updated monitor despite the error.
420                                 let persist_res = self.persister.update_persisted_channel(funding_txo, &update, monitor);
421                                 if let Err(ref e) = persist_res {
422                                         log_error!(self.logger, "Failed to persist channel monitor update: {:?}", e);
423                                 }
424                                 if update_res.is_err() {
425                                         Err(ChannelMonitorUpdateErr::PermanentFailure)
426                                 } else {
427                                         persist_res
428                                 }
429                         }
430                 }
431         }
432
433         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
434                 let mut pending_monitor_events = Vec::new();
435                 for monitor_state in self.monitors.read().unwrap().values() {
436                         pending_monitor_events.append(&mut monitor_state.monitor.get_and_clear_pending_monitor_events());
437                 }
438                 pending_monitor_events
439         }
440 }
441
442 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
443         where C::Target: chain::Filter,
444               T::Target: BroadcasterInterface,
445               F::Target: FeeEstimator,
446               L::Target: Logger,
447               P::Target: Persist<ChannelSigner>,
448 {
449         /// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
450         ///
451         /// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
452         /// order to handle these events.
453         ///
454         /// [`SpendableOutputs`]: events::Event::SpendableOutputs
455         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
456                 let mut pending_events = Vec::new();
457                 for monitor_state in self.monitors.read().unwrap().values() {
458                         pending_events.append(&mut monitor_state.monitor.get_and_clear_pending_events());
459                 }
460                 for event in pending_events.drain(..) {
461                         handler.handle_event(&event);
462                 }
463         }
464 }
465
466 #[cfg(test)]
467 mod tests {
468         use ::{check_added_monitors, get_local_commitment_txn};
469         use ln::features::InitFeatures;
470         use ln::functional_test_utils::*;
471         use util::events::MessageSendEventsProvider;
472         use util::test_utils::{OnRegisterOutput, TxOutReference};
473
474         /// Tests that in-block dependent transactions are processed by `block_connected` when not
475         /// included in `txdata` but returned by [`chain::Filter::register_output`]. For instance,
476         /// a (non-anchor) commitment transaction's HTLC output may be spent in the same block as the
477         /// commitment transaction itself. An Electrum client may filter the commitment transaction but
478         /// needs to return the HTLC transaction so it can be processed.
479         #[test]
480         fn connect_block_checks_dependent_transactions() {
481                 let chanmon_cfgs = create_chanmon_cfgs(2);
482                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
483                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
484                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
485                 let channel = create_announced_chan_between_nodes(
486                         &nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
487
488                 // Send a payment, saving nodes[0]'s revoked commitment and HTLC-Timeout transactions.
489                 let (commitment_tx, htlc_tx) = {
490                         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000).0;
491                         let mut txn = get_local_commitment_txn!(nodes[0], channel.2);
492                         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
493
494                         assert_eq!(txn.len(), 2);
495                         (txn.remove(0), txn.remove(0))
496                 };
497
498                 // Set expectations on nodes[1]'s chain source to return dependent transactions.
499                 let htlc_output = TxOutReference(commitment_tx.clone(), 0);
500                 let to_local_output = TxOutReference(commitment_tx.clone(), 1);
501                 let htlc_timeout_output = TxOutReference(htlc_tx.clone(), 0);
502                 nodes[1].chain_source
503                         .expect(OnRegisterOutput { with: htlc_output, returns: Some((1, htlc_tx)) })
504                         .expect(OnRegisterOutput { with: to_local_output, returns: None })
505                         .expect(OnRegisterOutput { with: htlc_timeout_output, returns: None });
506
507                 // Notify nodes[1] that nodes[0]'s revoked commitment transaction was mined. The chain
508                 // source should return the dependent HTLC transaction when the HTLC output is registered.
509                 mine_transaction(&nodes[1], &commitment_tx);
510
511                 // Clean up so uninteresting assertions don't fail.
512                 check_added_monitors!(nodes[1], 1);
513                 nodes[1].node.get_and_clear_pending_msg_events();
514                 nodes[1].node.get_and_clear_pending_events();
515         }
516 }