Bump workspace to rust edition 2018
[rust-lightning] / lightning / src / ln / monitor_tests.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 //! Further functional tests which test blockchain reorganizations.
11
12 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, Balance};
13 use crate::chain::transaction::OutPoint;
14 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
15 use crate::ln::channel;
16 use crate::ln::channelmanager::{self, BREAKDOWN_TIMEOUT};
17 use crate::ln::msgs::ChannelMessageHandler;
18 use crate::util::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
19
20 use bitcoin::blockdata::script::Builder;
21 use bitcoin::blockdata::opcodes;
22 use bitcoin::secp256k1::Secp256k1;
23 use bitcoin::Transaction;
24
25 use crate::prelude::*;
26
27 use crate::ln::functional_test_utils::*;
28
29 #[test]
30 fn chanmon_fail_from_stale_commitment() {
31         // If we forward an HTLC to our counterparty, but we force-closed the channel before our
32         // counterparty provides us an updated commitment transaction, we'll end up with a commitment
33         // transaction that does not contain the HTLC which we attempted to forward. In this case, we
34         // need to wait `ANTI_REORG_DELAY` blocks and then fail back the HTLC as there is no way for us
35         // to learn the preimage and the confirmed commitment transaction paid us the value of the
36         // HTLC.
37         //
38         // However, previously, we did not do this, ignoring the HTLC entirely.
39         //
40         // This could lead to channel closure if the sender we received the HTLC from decides to go on
41         // chain to get their HTLC back before it times out.
42         //
43         // Here, we check exactly this case, forwarding a payment from A, through B, to C, before B
44         // broadcasts its latest commitment transaction, which should result in it eventually failing
45         // the HTLC back off-chain to A.
46         let chanmon_cfgs = create_chanmon_cfgs(3);
47         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
48         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
49         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
50
51         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
52         let (update_a, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
53
54         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
55         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
56         check_added_monitors!(nodes[0], 1);
57
58         let bs_txn = get_local_commitment_txn!(nodes[1], chan_id_2);
59
60         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
61         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
62         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
63
64         expect_pending_htlcs_forwardable!(nodes[1]);
65         get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
66         check_added_monitors!(nodes[1], 1);
67
68         // Don't bother delivering the new HTLC add/commits, instead confirming the pre-HTLC commitment
69         // transaction for nodes[1].
70         mine_transaction(&nodes[1], &bs_txn[0]);
71         check_added_monitors!(nodes[1], 1);
72         check_closed_broadcast!(nodes[1], true);
73         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
74         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
75
76         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
77         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
78         check_added_monitors!(nodes[1], 1);
79         let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
80
81         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
82         commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, true, true);
83         expect_payment_failed_with_update!(nodes[0], payment_hash, false, update_a.contents.short_channel_id, true);
84 }
85
86 fn test_spendable_output<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, spendable_tx: &Transaction) {
87         let mut spendable = node.chain_monitor.chain_monitor.get_and_clear_pending_events();
88         assert_eq!(spendable.len(), 1);
89         if let Event::SpendableOutputs { outputs } = spendable.pop().unwrap() {
90                 assert_eq!(outputs.len(), 1);
91                 let spend_tx = node.keys_manager.backing.spend_spendable_outputs(&[&outputs[0]], Vec::new(),
92                         Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &Secp256k1::new()).unwrap();
93                 check_spends!(spend_tx, spendable_tx);
94         } else { panic!(); }
95 }
96
97 #[test]
98 fn revoked_output_htlc_resolution_timing() {
99         // Tests that HTLCs which were present in a broadcasted remote revoked commitment transaction
100         // are resolved only after a spend of the HTLC output reaches six confirmations. Preivously
101         // they would resolve after the revoked commitment transaction itself reaches six
102         // confirmations.
103         let chanmon_cfgs = create_chanmon_cfgs(2);
104         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
105         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
106         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
107
108         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
109
110         let payment_hash_1 = route_payment(&nodes[1], &[&nodes[0]], 1_000_000).1;
111
112         // Get a commitment transaction which contains the HTLC we care about, but which we'll revoke
113         // before forwarding.
114         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
115         assert_eq!(revoked_local_txn.len(), 1);
116
117         // Route a dust payment to revoke the above commitment transaction
118         route_payment(&nodes[0], &[&nodes[1]], 1_000);
119
120         // Confirm the revoked commitment transaction, closing the channel.
121         mine_transaction(&nodes[1], &revoked_local_txn[0]);
122         check_added_monitors!(nodes[1], 1);
123         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
124         check_closed_broadcast!(nodes[1], true);
125
126         let bs_spend_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
127         assert_eq!(bs_spend_txn.len(), 2);
128         check_spends!(bs_spend_txn[0], revoked_local_txn[0]);
129         check_spends!(bs_spend_txn[1], chan.3);
130
131         // After the commitment transaction confirms, we should still wait on the HTLC spend
132         // transaction to confirm before resolving the HTLC.
133         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
134         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
135         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
136
137         // Spend the HTLC output, generating a HTLC failure event after ANTI_REORG_DELAY confirmations.
138         mine_transaction(&nodes[1], &bs_spend_txn[0]);
139         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
140         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
141
142         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
143         expect_payment_failed!(nodes[1], payment_hash_1, false);
144 }
145
146 #[test]
147 fn chanmon_claim_value_coop_close() {
148         // Tests `get_claimable_balances` returns the correct values across a simple cooperative claim.
149         // Specifically, this tests that the channel non-HTLC balances show up in
150         // `get_claimable_balances` until the cooperative claims have confirmed and generated a
151         // `SpendableOutputs` event, and no longer.
152         let chanmon_cfgs = create_chanmon_cfgs(2);
153         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
154         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
155         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
156
157         let (_, _, chan_id, funding_tx) =
158                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
159         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
160         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
161
162         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
163         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
164
165         assert_eq!(vec![Balance::ClaimableOnChannelClose {
166                         claimable_amount_satoshis: 1_000_000 - 1_000 - chan_feerate * channel::commitment_tx_base_weight(opt_anchors) / 1000
167                 }],
168                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
169         assert_eq!(vec![Balance::ClaimableOnChannelClose { claimable_amount_satoshis: 1_000, }],
170                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
171
172         nodes[0].node.close_channel(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
173         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
174         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &channelmanager::provided_init_features(), &node_0_shutdown);
175         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
176         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &channelmanager::provided_init_features(), &node_1_shutdown);
177
178         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
179         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
180         let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
181         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
182         let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
183         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
184         let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
185         assert!(node_1_none.is_none());
186
187         let shutdown_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
188         assert_eq!(shutdown_tx, nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0));
189         assert_eq!(shutdown_tx.len(), 1);
190
191         mine_transaction(&nodes[0], &shutdown_tx[0]);
192         mine_transaction(&nodes[1], &shutdown_tx[0]);
193
194         assert!(nodes[0].node.list_channels().is_empty());
195         assert!(nodes[1].node.list_channels().is_empty());
196
197         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
198         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
199
200         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
201                         claimable_amount_satoshis: 1_000_000 - 1_000 - chan_feerate * channel::commitment_tx_base_weight(opt_anchors) / 1000,
202                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
203                 }],
204                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
205         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
206                         claimable_amount_satoshis: 1000,
207                         confirmation_height: nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1,
208                 }],
209                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
210
211         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
212         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
213
214         assert_eq!(Vec::<Balance>::new(),
215                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
216         assert_eq!(Vec::<Balance>::new(),
217                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
218
219         test_spendable_output(&nodes[0], &shutdown_tx[0]);
220         test_spendable_output(&nodes[1], &shutdown_tx[0]);
221
222         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
223         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
224 }
225
226 fn sorted_vec<T: Ord>(mut v: Vec<T>) -> Vec<T> {
227         v.sort_unstable();
228         v
229 }
230
231 /// Asserts that `a` and `b` are close, but maybe off by up to 5.
232 /// This is useful when checking fees and weights on transactions as things may vary by a few based
233 /// on signature size and signature size estimation being non-exact.
234 fn fuzzy_assert_eq<V: core::convert::TryInto<u64>>(a: V, b: V) {
235         let a_u64 = a.try_into().map_err(|_| ()).unwrap();
236         let b_u64 = b.try_into().map_err(|_| ()).unwrap();
237         eprintln!("Checking {} and {} for fuzzy equality", a_u64, b_u64);
238         assert!(a_u64 >= b_u64 - 5);
239         assert!(b_u64 >= a_u64 - 5);
240 }
241
242 fn do_test_claim_value_force_close(prev_commitment_tx: bool) {
243         // Tests `get_claimable_balances` with an HTLC across a force-close.
244         // We build a channel with an HTLC pending, then force close the channel and check that the
245         // `get_claimable_balances` return value is correct as transactions confirm on-chain.
246         let mut chanmon_cfgs = create_chanmon_cfgs(2);
247         if prev_commitment_tx {
248                 // We broadcast a second-to-latest commitment transaction, without providing the revocation
249                 // secret to the counterparty. However, because we always immediately take the revocation
250                 // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
251                 // transaction which, from the point of view of our keys_manager, is revoked.
252                 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
253         }
254         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
255         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
256         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
257
258         let (_, _, chan_id, funding_tx) =
259                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
260         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
261         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
262
263         // This HTLC is immediately claimed, giving node B the preimage
264         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
265         // This HTLC is allowed to time out, letting A claim it. However, in order to test claimable
266         // balances more fully we also give B the preimage for this HTLC.
267         let (timeout_payment_preimage, timeout_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 4_000_000);
268         // This HTLC will be dust, and not be claimable at all:
269         let (dust_payment_preimage, dust_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000);
270
271         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
272
273         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
274         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
275
276         let remote_txn = get_local_commitment_txn!(nodes[1], chan_id);
277         // Before B receives the payment preimage, it only suggests the push_msat value of 1_000 sats
278         // as claimable. A lists both its to-self balance and the (possibly-claimable) HTLCs.
279         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
280                         claimable_amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - chan_feerate *
281                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
282                 }, Balance::MaybeTimeoutClaimableHTLC {
283                         claimable_amount_satoshis: 3_000,
284                         claimable_height: htlc_cltv_timeout,
285                 }, Balance::MaybeTimeoutClaimableHTLC {
286                         claimable_amount_satoshis: 4_000,
287                         claimable_height: htlc_cltv_timeout,
288                 }]),
289                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
290         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
291                         claimable_amount_satoshis: 1_000,
292                 }, Balance::MaybePreimageClaimableHTLC {
293                         claimable_amount_satoshis: 3_000,
294                         expiry_height: htlc_cltv_timeout,
295                 }, Balance::MaybePreimageClaimableHTLC {
296                         claimable_amount_satoshis: 4_000,
297                         expiry_height: htlc_cltv_timeout,
298                 }]),
299                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
300
301         nodes[1].node.claim_funds(payment_preimage);
302         check_added_monitors!(nodes[1], 1);
303         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
304
305         let b_htlc_msgs = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
306         // We claim the dust payment here as well, but it won't impact our claimable balances as its
307         // dust and thus doesn't appear on chain at all.
308         nodes[1].node.claim_funds(dust_payment_preimage);
309         check_added_monitors!(nodes[1], 1);
310         expect_payment_claimed!(nodes[1], dust_payment_hash, 3_000);
311
312         nodes[1].node.claim_funds(timeout_payment_preimage);
313         check_added_monitors!(nodes[1], 1);
314         expect_payment_claimed!(nodes[1], timeout_payment_hash, 4_000_000);
315
316         if prev_commitment_tx {
317                 // To build a previous commitment transaction, deliver one round of commitment messages.
318                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.update_fulfill_htlcs[0]);
319                 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
320                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.commitment_signed);
321                 check_added_monitors!(nodes[0], 1);
322                 let (as_raa, as_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
323                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
324                 let _htlc_updates = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
325                 check_added_monitors!(nodes[1], 1);
326                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs);
327                 let _bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
328                 check_added_monitors!(nodes[1], 1);
329         }
330
331         // Once B has received the payment preimage, it includes the value of the HTLC in its
332         // "claimable if you were to close the channel" balance.
333         let mut a_expected_balances = vec![Balance::ClaimableOnChannelClose {
334                         claimable_amount_satoshis: 1_000_000 - // Channel funding value in satoshis
335                                 4_000 - // The to-be-failed HTLC value in satoshis
336                                 3_000 - // The claimed HTLC value in satoshis
337                                 1_000 - // The push_msat value in satoshis
338                                 3 - // The dust HTLC value in satoshis
339                                 // The commitment transaction fee with two HTLC outputs:
340                                 chan_feerate * (channel::commitment_tx_base_weight(opt_anchors) +
341                                                                 if prev_commitment_tx { 1 } else { 2 } *
342                                                                 channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
343                 }, Balance::MaybeTimeoutClaimableHTLC {
344                         claimable_amount_satoshis: 4_000,
345                         claimable_height: htlc_cltv_timeout,
346                 }];
347         if !prev_commitment_tx {
348                 a_expected_balances.push(Balance::MaybeTimeoutClaimableHTLC {
349                         claimable_amount_satoshis: 3_000,
350                         claimable_height: htlc_cltv_timeout,
351                 });
352         }
353         assert_eq!(sorted_vec(a_expected_balances),
354                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
355         assert_eq!(vec![Balance::ClaimableOnChannelClose {
356                         claimable_amount_satoshis: 1_000 + 3_000 + 4_000,
357                 }],
358                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
359
360         // Broadcast the closing transaction (which has both pending HTLCs in it) and get B's
361         // broadcasted HTLC claim transaction with preimage.
362         let node_b_commitment_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
363         mine_transaction(&nodes[0], &remote_txn[0]);
364         mine_transaction(&nodes[1], &remote_txn[0]);
365
366         let b_broadcast_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
367         assert_eq!(b_broadcast_txn.len(), if prev_commitment_tx { 4 } else { 5 });
368         if prev_commitment_tx {
369                 check_spends!(b_broadcast_txn[3], b_broadcast_txn[2]);
370         } else {
371                 assert_eq!(b_broadcast_txn[0], b_broadcast_txn[3]);
372                 assert_eq!(b_broadcast_txn[1], b_broadcast_txn[4]);
373         }
374         // b_broadcast_txn[0] should spend the HTLC output of the commitment tx for 3_000 sats
375         check_spends!(b_broadcast_txn[0], remote_txn[0]);
376         check_spends!(b_broadcast_txn[1], remote_txn[0]);
377         assert_eq!(b_broadcast_txn[0].input.len(), 1);
378         assert_eq!(b_broadcast_txn[1].input.len(), 1);
379         assert_eq!(remote_txn[0].output[b_broadcast_txn[0].input[0].previous_output.vout as usize].value, 3_000);
380         assert_eq!(remote_txn[0].output[b_broadcast_txn[1].input[0].previous_output.vout as usize].value, 4_000);
381         check_spends!(b_broadcast_txn[2], funding_tx);
382
383         assert!(nodes[0].node.list_channels().is_empty());
384         check_closed_broadcast!(nodes[0], true);
385         check_added_monitors!(nodes[0], 1);
386         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
387         assert!(nodes[1].node.list_channels().is_empty());
388         check_closed_broadcast!(nodes[1], true);
389         check_added_monitors!(nodes[1], 1);
390         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
391         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
392         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
393
394         // Once the commitment transaction confirms, we will wait until ANTI_REORG_DELAY until we
395         // generate any `SpendableOutputs` events. Thus, the same balances will still be listed
396         // available in `get_claimable_balances`. However, both will swap from `ClaimableOnClose` to
397         // other Balance variants, as close has already happened.
398         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
399         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
400
401         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
402                         claimable_amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - chan_feerate *
403                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
404                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
405                 }, Balance::MaybeTimeoutClaimableHTLC {
406                         claimable_amount_satoshis: 3_000,
407                         claimable_height: htlc_cltv_timeout,
408                 }, Balance::MaybeTimeoutClaimableHTLC {
409                         claimable_amount_satoshis: 4_000,
410                         claimable_height: htlc_cltv_timeout,
411                 }]),
412                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
413         // The main non-HTLC balance is just awaiting confirmations, but the claimable height is the
414         // CSV delay, not ANTI_REORG_DELAY.
415         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
416                         claimable_amount_satoshis: 1_000,
417                         confirmation_height: node_b_commitment_claimable,
418                 },
419                 // Both HTLC balances are "contentious" as our counterparty could claim them if we wait too
420                 // long.
421                 Balance::ContentiousClaimable {
422                         claimable_amount_satoshis: 3_000,
423                         timeout_height: htlc_cltv_timeout,
424                 }, Balance::ContentiousClaimable {
425                         claimable_amount_satoshis: 4_000,
426                         timeout_height: htlc_cltv_timeout,
427                 }]),
428                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
429
430         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
431         expect_payment_failed!(nodes[0], dust_payment_hash, false);
432         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
433
434         // After ANTI_REORG_DELAY, A will consider its balance fully spendable and generate a
435         // `SpendableOutputs` event. However, B still has to wait for the CSV delay.
436         assert_eq!(sorted_vec(vec![Balance::MaybeTimeoutClaimableHTLC {
437                         claimable_amount_satoshis: 3_000,
438                         claimable_height: htlc_cltv_timeout,
439                 }, Balance::MaybeTimeoutClaimableHTLC {
440                         claimable_amount_satoshis: 4_000,
441                         claimable_height: htlc_cltv_timeout,
442                 }]),
443                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
444         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
445                         claimable_amount_satoshis: 1_000,
446                         confirmation_height: node_b_commitment_claimable,
447                 }, Balance::ContentiousClaimable {
448                         claimable_amount_satoshis: 3_000,
449                         timeout_height: htlc_cltv_timeout,
450                 }, Balance::ContentiousClaimable {
451                         claimable_amount_satoshis: 4_000,
452                         timeout_height: htlc_cltv_timeout,
453                 }]),
454                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
455
456         test_spendable_output(&nodes[0], &remote_txn[0]);
457         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
458
459         // After broadcasting the HTLC claim transaction, node A will still consider the HTLC
460         // possibly-claimable up to ANTI_REORG_DELAY, at which point it will drop it.
461         mine_transaction(&nodes[0], &b_broadcast_txn[0]);
462         if prev_commitment_tx {
463                 expect_payment_path_successful!(nodes[0]);
464         } else {
465                 expect_payment_sent!(nodes[0], payment_preimage);
466         }
467         assert_eq!(sorted_vec(vec![Balance::MaybeTimeoutClaimableHTLC {
468                         claimable_amount_satoshis: 3_000,
469                         claimable_height: htlc_cltv_timeout,
470                 }, Balance::MaybeTimeoutClaimableHTLC {
471                         claimable_amount_satoshis: 4_000,
472                         claimable_height: htlc_cltv_timeout,
473                 }]),
474                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
475         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
476         assert_eq!(vec![Balance::MaybeTimeoutClaimableHTLC {
477                         claimable_amount_satoshis: 4_000,
478                         claimable_height: htlc_cltv_timeout,
479                 }],
480                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
481
482         // When the HTLC timeout output is spendable in the next block, A should broadcast it
483         connect_blocks(&nodes[0], htlc_cltv_timeout - nodes[0].best_block_info().1 - 1);
484         let a_broadcast_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
485         assert_eq!(a_broadcast_txn.len(), 3);
486         check_spends!(a_broadcast_txn[0], funding_tx);
487         assert_eq!(a_broadcast_txn[1].input.len(), 1);
488         check_spends!(a_broadcast_txn[1], remote_txn[0]);
489         assert_eq!(a_broadcast_txn[2].input.len(), 1);
490         check_spends!(a_broadcast_txn[2], remote_txn[0]);
491         assert_ne!(a_broadcast_txn[1].input[0].previous_output.vout,
492                    a_broadcast_txn[2].input[0].previous_output.vout);
493         // a_broadcast_txn [1] and [2] should spend the HTLC outputs of the commitment tx
494         assert_eq!(remote_txn[0].output[a_broadcast_txn[1].input[0].previous_output.vout as usize].value, 3_000);
495         assert_eq!(remote_txn[0].output[a_broadcast_txn[2].input[0].previous_output.vout as usize].value, 4_000);
496
497         // Once the HTLC-Timeout transaction confirms, A will no longer consider the HTLC
498         // "MaybeClaimable", but instead move it to "AwaitingConfirmations".
499         mine_transaction(&nodes[0], &a_broadcast_txn[2]);
500         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
501         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
502                         claimable_amount_satoshis: 4_000,
503                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
504                 }],
505                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
506         // After ANTI_REORG_DELAY, A will generate a SpendableOutputs event and drop the claimable
507         // balance entry.
508         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
509         assert_eq!(Vec::<Balance>::new(),
510                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
511         expect_payment_failed!(nodes[0], timeout_payment_hash, false);
512
513         test_spendable_output(&nodes[0], &a_broadcast_txn[2]);
514
515         // Node B will no longer consider the HTLC "contentious" after the HTLC claim transaction
516         // confirms, and consider it simply "awaiting confirmations". Note that it has to wait for the
517         // standard revocable transaction CSV delay before receiving a `SpendableOutputs`.
518         let node_b_htlc_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
519         mine_transaction(&nodes[1], &b_broadcast_txn[0]);
520
521         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
522                         claimable_amount_satoshis: 1_000,
523                         confirmation_height: node_b_commitment_claimable,
524                 }, Balance::ClaimableAwaitingConfirmations {
525                         claimable_amount_satoshis: 3_000,
526                         confirmation_height: node_b_htlc_claimable,
527                 }, Balance::ContentiousClaimable {
528                         claimable_amount_satoshis: 4_000,
529                         timeout_height: htlc_cltv_timeout,
530                 }]),
531                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
532
533         // After reaching the commitment output CSV, we'll get a SpendableOutputs event for it and have
534         // only the HTLCs claimable on node B.
535         connect_blocks(&nodes[1], node_b_commitment_claimable - nodes[1].best_block_info().1);
536         test_spendable_output(&nodes[1], &remote_txn[0]);
537
538         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
539                         claimable_amount_satoshis: 3_000,
540                         confirmation_height: node_b_htlc_claimable,
541                 }, Balance::ContentiousClaimable {
542                         claimable_amount_satoshis: 4_000,
543                         timeout_height: htlc_cltv_timeout,
544                 }]),
545                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
546
547         // After reaching the claimed HTLC output CSV, we'll get a SpendableOutptus event for it and
548         // have only one HTLC output left spendable.
549         connect_blocks(&nodes[1], node_b_htlc_claimable - nodes[1].best_block_info().1);
550         test_spendable_output(&nodes[1], &b_broadcast_txn[0]);
551
552         assert_eq!(vec![Balance::ContentiousClaimable {
553                         claimable_amount_satoshis: 4_000,
554                         timeout_height: htlc_cltv_timeout,
555                 }],
556                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
557
558         // Finally, mine the HTLC timeout transaction that A broadcasted (even though B should be able
559         // to claim this HTLC with the preimage it knows!). It will remain listed as a claimable HTLC
560         // until ANTI_REORG_DELAY confirmations on the spend.
561         mine_transaction(&nodes[1], &a_broadcast_txn[2]);
562         assert_eq!(vec![Balance::ContentiousClaimable {
563                         claimable_amount_satoshis: 4_000,
564                         timeout_height: htlc_cltv_timeout,
565                 }],
566                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
567         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
568         assert_eq!(Vec::<Balance>::new(),
569                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
570 }
571
572 #[test]
573 fn test_claim_value_force_close() {
574         do_test_claim_value_force_close(true);
575         do_test_claim_value_force_close(false);
576 }
577
578 #[test]
579 fn test_balances_on_local_commitment_htlcs() {
580         // Previously, when handling the broadcast of a local commitment transactions (with associated
581         // CSV delays prior to spendability), we incorrectly handled the CSV delays on HTLC
582         // transactions. This caused us to miss spendable outputs for HTLCs which were awaiting a CSV
583         // delay prior to spendability.
584         //
585         // Further, because of this, we could hit an assertion as `get_claimable_balances` asserted
586         // that HTLCs were resolved after the funding spend was resolved, which was not true if the
587         // HTLC did not have a CSV delay attached (due to the above bug or due to it being an HTLC
588         // claim by our counterparty).
589         let chanmon_cfgs = create_chanmon_cfgs(2);
590         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
592         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
593
594         // Create a single channel with two pending HTLCs from nodes[0] to nodes[1], one which nodes[1]
595         // knows the preimage for, one which it does not.
596         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
597         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
598
599         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000_000);
600         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
601         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
602         check_added_monitors!(nodes[0], 1);
603
604         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
605         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
606         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
607
608         expect_pending_htlcs_forwardable!(nodes[1]);
609         expect_payment_received!(nodes[1], payment_hash, payment_secret, 10_000_000);
610
611         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 20_000_000);
612         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
613         check_added_monitors!(nodes[0], 1);
614
615         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
616         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
617         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
618
619         expect_pending_htlcs_forwardable!(nodes[1]);
620         expect_payment_received!(nodes[1], payment_hash_2, payment_secret_2, 20_000_000);
621         nodes[1].node.claim_funds(payment_preimage_2);
622         get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
623         check_added_monitors!(nodes[1], 1);
624         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000_000);
625
626         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
627         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
628
629         // Get nodes[0]'s commitment transaction and HTLC-Timeout transactions
630         let as_txn = get_local_commitment_txn!(nodes[0], chan_id);
631         assert_eq!(as_txn.len(), 3);
632         check_spends!(as_txn[1], as_txn[0]);
633         check_spends!(as_txn[2], as_txn[0]);
634         check_spends!(as_txn[0], funding_tx);
635
636         // First confirm the commitment transaction on nodes[0], which should leave us with three
637         // claimable balances.
638         let node_a_commitment_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
639         mine_transaction(&nodes[0], &as_txn[0]);
640         check_added_monitors!(nodes[0], 1);
641         check_closed_broadcast!(nodes[0], true);
642         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
643
644         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
645                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
646                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
647                         confirmation_height: node_a_commitment_claimable,
648                 }, Balance::MaybeTimeoutClaimableHTLC {
649                         claimable_amount_satoshis: 10_000,
650                         claimable_height: htlc_cltv_timeout,
651                 }, Balance::MaybeTimeoutClaimableHTLC {
652                         claimable_amount_satoshis: 20_000,
653                         claimable_height: htlc_cltv_timeout,
654                 }]),
655                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
656
657         // Get nodes[1]'s HTLC claim tx for the second HTLC
658         mine_transaction(&nodes[1], &as_txn[0]);
659         check_added_monitors!(nodes[1], 1);
660         check_closed_broadcast!(nodes[1], true);
661         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
662         let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
663         assert_eq!(bs_htlc_claim_txn.len(), 3);
664         check_spends!(bs_htlc_claim_txn[0], as_txn[0]);
665         check_spends!(bs_htlc_claim_txn[1], funding_tx);
666         check_spends!(bs_htlc_claim_txn[2], bs_htlc_claim_txn[1]);
667
668         // Connect blocks until the HTLCs expire, allowing us to (validly) broadcast the HTLC-Timeout
669         // transaction.
670         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
671         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
672                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
673                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
674                         confirmation_height: node_a_commitment_claimable,
675                 }, Balance::MaybeTimeoutClaimableHTLC {
676                         claimable_amount_satoshis: 10_000,
677                         claimable_height: htlc_cltv_timeout,
678                 }, Balance::MaybeTimeoutClaimableHTLC {
679                         claimable_amount_satoshis: 20_000,
680                         claimable_height: htlc_cltv_timeout,
681                 }]),
682                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
683         assert_eq!(as_txn[1].lock_time.0, nodes[0].best_block_info().1 + 1); // as_txn[1] can be included in the next block
684
685         // Now confirm nodes[0]'s HTLC-Timeout transaction, which changes the claimable balance to an
686         // "awaiting confirmations" one.
687         let node_a_htlc_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
688         mine_transaction(&nodes[0], &as_txn[1]);
689         // Note that prior to the fix in the commit which introduced this test, this (and the next
690         // balance) check failed. With this check removed, the code panicked in the `connect_blocks`
691         // call, as described, two hunks down.
692         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
693                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
694                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
695                         confirmation_height: node_a_commitment_claimable,
696                 }, Balance::ClaimableAwaitingConfirmations {
697                         claimable_amount_satoshis: 10_000,
698                         confirmation_height: node_a_htlc_claimable,
699                 }, Balance::MaybeTimeoutClaimableHTLC {
700                         claimable_amount_satoshis: 20_000,
701                         claimable_height: htlc_cltv_timeout,
702                 }]),
703                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
704
705         // Now confirm nodes[1]'s HTLC claim, giving nodes[0] the preimage. Note that the "maybe
706         // claimable" balance remains until we see ANTI_REORG_DELAY blocks.
707         mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
708         expect_payment_sent!(nodes[0], payment_preimage_2);
709         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
710                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
711                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
712                         confirmation_height: node_a_commitment_claimable,
713                 }, Balance::ClaimableAwaitingConfirmations {
714                         claimable_amount_satoshis: 10_000,
715                         confirmation_height: node_a_htlc_claimable,
716                 }, Balance::MaybeTimeoutClaimableHTLC {
717                         claimable_amount_satoshis: 20_000,
718                         claimable_height: htlc_cltv_timeout,
719                 }]),
720                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
721
722         // Finally make the HTLC transactions have ANTI_REORG_DELAY blocks. This call previously
723         // panicked as described in the test introduction. This will remove the "maybe claimable"
724         // spendable output as nodes[1] has fully claimed the second HTLC.
725         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
726         expect_payment_failed!(nodes[0], payment_hash, false);
727
728         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
729                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
730                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
731                         confirmation_height: node_a_commitment_claimable,
732                 }, Balance::ClaimableAwaitingConfirmations {
733                         claimable_amount_satoshis: 10_000,
734                         confirmation_height: node_a_htlc_claimable,
735                 }]),
736                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
737
738         // Connect blocks until the commitment transaction's CSV expires, providing us the relevant
739         // `SpendableOutputs` event and removing the claimable balance entry.
740         connect_blocks(&nodes[0], node_a_commitment_claimable - nodes[0].best_block_info().1);
741         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
742                         claimable_amount_satoshis: 10_000,
743                         confirmation_height: node_a_htlc_claimable,
744                 }],
745                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
746         test_spendable_output(&nodes[0], &as_txn[0]);
747
748         // Connect blocks until the HTLC-Timeout's CSV expires, providing us the relevant
749         // `SpendableOutputs` event and removing the claimable balance entry.
750         connect_blocks(&nodes[0], node_a_htlc_claimable - nodes[0].best_block_info().1);
751         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
752         test_spendable_output(&nodes[0], &as_txn[1]);
753 }
754
755 #[test]
756 fn test_no_preimage_inbound_htlc_balances() {
757         // Tests that MaybePreimageClaimableHTLC are generated for inbound HTLCs for which we do not
758         // have a preimage.
759         let chanmon_cfgs = create_chanmon_cfgs(2);
760         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
761         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
762         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
763
764         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
765         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
766
767         // Send two HTLCs, one from A to B, and one from B to A.
768         let to_b_failed_payment_hash = route_payment(&nodes[0], &[&nodes[1]], 10_000_000).1;
769         let to_a_failed_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 20_000_000).1;
770         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
771
772         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
773         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
774
775         // Both A and B will have an HTLC that's claimable on timeout and one that's claimable if they
776         // receive the preimage. These will remain the same through the channel closure and until the
777         // HTLC output is spent.
778
779         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
780                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
781                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
782                 }, Balance::MaybePreimageClaimableHTLC {
783                         claimable_amount_satoshis: 20_000,
784                         expiry_height: htlc_cltv_timeout,
785                 }, Balance::MaybeTimeoutClaimableHTLC {
786                         claimable_amount_satoshis: 10_000,
787                         claimable_height: htlc_cltv_timeout,
788                 }]),
789                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
790
791         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
792                         claimable_amount_satoshis: 500_000 - 20_000,
793                 }, Balance::MaybePreimageClaimableHTLC {
794                         claimable_amount_satoshis: 10_000,
795                         expiry_height: htlc_cltv_timeout,
796                 }, Balance::MaybeTimeoutClaimableHTLC {
797                         claimable_amount_satoshis: 20_000,
798                         claimable_height: htlc_cltv_timeout,
799                 }]),
800                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
801
802         // Get nodes[0]'s commitment transaction and HTLC-Timeout transaction
803         let as_txn = get_local_commitment_txn!(nodes[0], chan_id);
804         assert_eq!(as_txn.len(), 2);
805         check_spends!(as_txn[1], as_txn[0]);
806         check_spends!(as_txn[0], funding_tx);
807
808         // Now close the channel by confirming A's commitment transaction on both nodes, checking the
809         // claimable balances remain the same except for the non-HTLC balance changing variant.
810         let node_a_commitment_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
811         let as_pre_spend_claims = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
812                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
813                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
814                         confirmation_height: node_a_commitment_claimable,
815                 }, Balance::MaybePreimageClaimableHTLC {
816                         claimable_amount_satoshis: 20_000,
817                         expiry_height: htlc_cltv_timeout,
818                 }, Balance::MaybeTimeoutClaimableHTLC {
819                         claimable_amount_satoshis: 10_000,
820                         claimable_height: htlc_cltv_timeout,
821                 }]);
822
823         mine_transaction(&nodes[0], &as_txn[0]);
824         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
825         check_added_monitors!(nodes[0], 1);
826         check_closed_broadcast!(nodes[0], true);
827         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
828
829         assert_eq!(as_pre_spend_claims,
830                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
831
832         mine_transaction(&nodes[1], &as_txn[0]);
833         check_added_monitors!(nodes[1], 1);
834         check_closed_broadcast!(nodes[1], true);
835         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
836
837         let node_b_commitment_claimable = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
838         let mut bs_pre_spend_claims = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
839                         claimable_amount_satoshis: 500_000 - 20_000,
840                         confirmation_height: node_b_commitment_claimable,
841                 }, Balance::MaybePreimageClaimableHTLC {
842                         claimable_amount_satoshis: 10_000,
843                         expiry_height: htlc_cltv_timeout,
844                 }, Balance::MaybeTimeoutClaimableHTLC {
845                         claimable_amount_satoshis: 20_000,
846                         claimable_height: htlc_cltv_timeout,
847                 }]);
848         assert_eq!(bs_pre_spend_claims,
849                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
850
851         // We'll broadcast the HTLC-Timeout transaction one block prior to the htlc's expiration (as it
852         // is confirmable in the next block), but will still include the same claimable balances as no
853         // HTLC has been spent, even after the HTLC expires. We'll also fail the inbound HTLC, but it
854         // won't do anything as the channel is already closed.
855
856         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
857         let as_htlc_timeout_claim = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
858         assert_eq!(as_htlc_timeout_claim.len(), 1);
859         check_spends!(as_htlc_timeout_claim[0], as_txn[0]);
860         expect_pending_htlcs_forwardable_conditions!(nodes[0],
861                 [HTLCDestination::FailedPayment { payment_hash: to_a_failed_payment_hash }]);
862
863         assert_eq!(as_pre_spend_claims,
864                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
865
866         connect_blocks(&nodes[0], 1);
867         assert_eq!(as_pre_spend_claims,
868                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
869
870         // For node B, we'll get the non-HTLC funds claimable after ANTI_REORG_DELAY confirmations
871         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
872         test_spendable_output(&nodes[1], &as_txn[0]);
873         bs_pre_spend_claims.retain(|e| if let Balance::ClaimableAwaitingConfirmations { .. } = e { false } else { true });
874
875         // The next few blocks for B look the same as for A, though for the opposite HTLC
876         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
877         connect_blocks(&nodes[1], TEST_FINAL_CLTV - (ANTI_REORG_DELAY - 1) - 1);
878         expect_pending_htlcs_forwardable_conditions!(nodes[1],
879                 [HTLCDestination::FailedPayment { payment_hash: to_b_failed_payment_hash }]);
880         let bs_htlc_timeout_claim = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
881         assert_eq!(bs_htlc_timeout_claim.len(), 1);
882         check_spends!(bs_htlc_timeout_claim[0], as_txn[0]);
883
884         assert_eq!(bs_pre_spend_claims,
885                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
886
887         connect_blocks(&nodes[1], 1);
888         assert_eq!(bs_pre_spend_claims,
889                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
890
891         // Now confirm the two HTLC timeout transactions for A, checking that the inbound HTLC resolves
892         // after ANTI_REORG_DELAY confirmations and the other takes BREAKDOWN_TIMEOUT confirmations.
893         mine_transaction(&nodes[0], &as_htlc_timeout_claim[0]);
894         let as_timeout_claimable_height = nodes[0].best_block_info().1 + (BREAKDOWN_TIMEOUT as u32) - 1;
895         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
896                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
897                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
898                         confirmation_height: node_a_commitment_claimable,
899                 }, Balance::MaybePreimageClaimableHTLC {
900                         claimable_amount_satoshis: 20_000,
901                         expiry_height: htlc_cltv_timeout,
902                 }, Balance::ClaimableAwaitingConfirmations {
903                         claimable_amount_satoshis: 10_000,
904                         confirmation_height: as_timeout_claimable_height,
905                 }]),
906                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
907
908         mine_transaction(&nodes[0], &bs_htlc_timeout_claim[0]);
909         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
910                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
911                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
912                         confirmation_height: node_a_commitment_claimable,
913                 }, Balance::MaybePreimageClaimableHTLC {
914                         claimable_amount_satoshis: 20_000,
915                         expiry_height: htlc_cltv_timeout,
916                 }, Balance::ClaimableAwaitingConfirmations {
917                         claimable_amount_satoshis: 10_000,
918                         confirmation_height: as_timeout_claimable_height,
919                 }]),
920                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
921
922         // Once as_htlc_timeout_claim[0] reaches ANTI_REORG_DELAY confirmations, we should get a
923         // payment failure event.
924         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
925         expect_payment_failed!(nodes[0], to_b_failed_payment_hash, false);
926
927         connect_blocks(&nodes[0], 1);
928         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
929                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
930                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
931                         confirmation_height: node_a_commitment_claimable,
932                 }, Balance::ClaimableAwaitingConfirmations {
933                         claimable_amount_satoshis: 10_000,
934                         confirmation_height: core::cmp::max(as_timeout_claimable_height, htlc_cltv_timeout),
935                 }]),
936                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
937
938         connect_blocks(&nodes[0], node_a_commitment_claimable - nodes[0].best_block_info().1);
939         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
940                         claimable_amount_satoshis: 10_000,
941                         confirmation_height: core::cmp::max(as_timeout_claimable_height, htlc_cltv_timeout),
942                 }],
943                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
944         test_spendable_output(&nodes[0], &as_txn[0]);
945
946         connect_blocks(&nodes[0], as_timeout_claimable_height - nodes[0].best_block_info().1);
947         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
948         test_spendable_output(&nodes[0], &as_htlc_timeout_claim[0]);
949
950         // The process for B should be completely identical as well, noting that the non-HTLC-balance
951         // was already claimed.
952         mine_transaction(&nodes[1], &bs_htlc_timeout_claim[0]);
953         let bs_timeout_claimable_height = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
954         assert_eq!(sorted_vec(vec![Balance::MaybePreimageClaimableHTLC {
955                         claimable_amount_satoshis: 10_000,
956                         expiry_height: htlc_cltv_timeout,
957                 }, Balance::ClaimableAwaitingConfirmations {
958                         claimable_amount_satoshis: 20_000,
959                         confirmation_height: bs_timeout_claimable_height,
960                 }]),
961                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
962
963         mine_transaction(&nodes[1], &as_htlc_timeout_claim[0]);
964         assert_eq!(sorted_vec(vec![Balance::MaybePreimageClaimableHTLC {
965                         claimable_amount_satoshis: 10_000,
966                         expiry_height: htlc_cltv_timeout,
967                 }, Balance::ClaimableAwaitingConfirmations {
968                         claimable_amount_satoshis: 20_000,
969                         confirmation_height: bs_timeout_claimable_height,
970                 }]),
971                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
972
973         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 2);
974         expect_payment_failed!(nodes[1], to_a_failed_payment_hash, false);
975
976         assert_eq!(vec![Balance::MaybePreimageClaimableHTLC {
977                         claimable_amount_satoshis: 10_000,
978                         expiry_height: htlc_cltv_timeout,
979                 }],
980                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
981         test_spendable_output(&nodes[1], &bs_htlc_timeout_claim[0]);
982
983         connect_blocks(&nodes[1], 1);
984         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
985 }
986
987 fn sorted_vec_with_additions<T: Ord + Clone>(v_orig: &Vec<T>, extra_ts: &[&T]) -> Vec<T> {
988         let mut v = v_orig.clone();
989         for t in extra_ts {
990                 v.push((*t).clone());
991         }
992         v.sort_unstable();
993         v
994 }
995
996 fn do_test_revoked_counterparty_commitment_balances(confirm_htlc_spend_first: bool) {
997         // Tests `get_claimable_balances` for revoked counterparty commitment transactions.
998         let mut chanmon_cfgs = create_chanmon_cfgs(2);
999         // We broadcast a second-to-latest commitment transaction, without providing the revocation
1000         // secret to the counterparty. However, because we always immediately take the revocation
1001         // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
1002         // transaction which, from the point of view of our keys_manager, is revoked.
1003         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
1004         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1005         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1006         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1007
1008         let (_, _, chan_id, funding_tx) =
1009                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 100_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1010         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
1011         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
1012
1013         // We create five HTLCs for B to claim against A's revoked commitment transaction:
1014         //
1015         // (1) one for which A is the originator and B knows the preimage
1016         // (2) one for which B is the originator where the HTLC has since timed-out
1017         // (3) one for which B is the originator but where the HTLC has not yet timed-out
1018         // (4) one dust HTLC which is lost in the channel closure
1019         // (5) one that actually isn't in the revoked commitment transaction at all, but was added in
1020         //     later commitment transaction updates
1021         //
1022         // Though they could all be claimed in a single claim transaction, due to CLTV timeouts they
1023         // are all currently claimed in separate transactions, which helps us test as we can claim
1024         // HTLCs individually.
1025
1026         let (claimed_payment_preimage, claimed_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
1027         let timeout_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 4_000_000).1;
1028         let dust_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 3_000).1;
1029
1030         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1031
1032         connect_blocks(&nodes[0], 10);
1033         connect_blocks(&nodes[1], 10);
1034
1035         let live_htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1036         let live_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 5_000_000).1;
1037
1038         // Get the latest commitment transaction from A and then update the fee to revoke it
1039         let as_revoked_txn = get_local_commitment_txn!(nodes[0], chan_id);
1040         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
1041
1042         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
1043
1044         let missing_htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1045         let missing_htlc_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 2_000_000).1;
1046
1047         nodes[1].node.claim_funds(claimed_payment_preimage);
1048         expect_payment_claimed!(nodes[1], claimed_payment_hash, 3_000_000);
1049         check_added_monitors!(nodes[1], 1);
1050         let _b_htlc_msgs = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
1051
1052         connect_blocks(&nodes[0], htlc_cltv_timeout + 1 - 10);
1053         check_closed_broadcast!(nodes[0], true);
1054         check_added_monitors!(nodes[0], 1);
1055
1056         let mut events = nodes[0].node.get_and_clear_pending_events();
1057         assert_eq!(events.len(), 6);
1058         let mut failed_payments: HashSet<_> =
1059                 [timeout_payment_hash, dust_payment_hash, live_payment_hash, missing_htlc_payment_hash]
1060                 .iter().map(|a| *a).collect();
1061         events.retain(|ev| {
1062                 match ev {
1063                         Event::HTLCHandlingFailed { failed_next_destination: HTLCDestination::NextHopChannel { node_id, channel_id }, .. } => {
1064                                 assert_eq!(*channel_id, chan_id);
1065                                 assert_eq!(*node_id, Some(nodes[1].node.get_our_node_id()));
1066                                 false
1067                         },
1068                         Event::HTLCHandlingFailed { failed_next_destination: HTLCDestination::FailedPayment { payment_hash }, .. } => {
1069                                 assert!(failed_payments.remove(payment_hash));
1070                                 false
1071                         },
1072                         _ => true,
1073                 }
1074         });
1075         assert!(failed_payments.is_empty());
1076         if let Event::PendingHTLCsForwardable { .. } = events[0] {} else { panic!(); }
1077         match &events[1] {
1078                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
1079                 _ => panic!(),
1080         }
1081
1082         connect_blocks(&nodes[1], htlc_cltv_timeout + 1 - 10);
1083         check_closed_broadcast!(nodes[1], true);
1084         check_added_monitors!(nodes[1], 1);
1085         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
1086
1087         // Prior to channel closure, B considers the preimage HTLC as its own, and otherwise only
1088         // lists the two on-chain timeout-able HTLCs as claimable balances.
1089         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
1090                         claimable_amount_satoshis: 100_000 - 5_000 - 4_000 - 3 - 2_000 + 3_000,
1091                 }, Balance::MaybeTimeoutClaimableHTLC {
1092                         claimable_amount_satoshis: 2_000,
1093                         claimable_height: missing_htlc_cltv_timeout,
1094                 }, Balance::MaybeTimeoutClaimableHTLC {
1095                         claimable_amount_satoshis: 4_000,
1096                         claimable_height: htlc_cltv_timeout,
1097                 }, Balance::MaybeTimeoutClaimableHTLC {
1098                         claimable_amount_satoshis: 5_000,
1099                         claimable_height: live_htlc_cltv_timeout,
1100                 }]),
1101                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1102
1103         mine_transaction(&nodes[1], &as_revoked_txn[0]);
1104         let mut claim_txn: Vec<_> = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..).filter(|tx| tx.input.iter().any(|inp| inp.previous_output.txid == as_revoked_txn[0].txid())).collect();
1105         // Currently the revoked commitment is claimed in four transactions as the HTLCs all expire
1106         // quite soon.
1107         assert_eq!(claim_txn.len(), 4);
1108         claim_txn.sort_unstable_by_key(|tx| tx.output.iter().map(|output| output.value).sum::<u64>());
1109
1110         // The following constants were determined experimentally
1111         const BS_TO_SELF_CLAIM_EXP_WEIGHT: usize = 483;
1112         const OUTBOUND_HTLC_CLAIM_EXP_WEIGHT: usize = 571;
1113         const INBOUND_HTLC_CLAIM_EXP_WEIGHT: usize = 578;
1114
1115         // Check that the weight is close to the expected weight. Note that signature sizes vary
1116         // somewhat so it may not always be exact.
1117         fuzzy_assert_eq(claim_txn[0].weight(), OUTBOUND_HTLC_CLAIM_EXP_WEIGHT);
1118         fuzzy_assert_eq(claim_txn[1].weight(), INBOUND_HTLC_CLAIM_EXP_WEIGHT);
1119         fuzzy_assert_eq(claim_txn[2].weight(), INBOUND_HTLC_CLAIM_EXP_WEIGHT);
1120         fuzzy_assert_eq(claim_txn[3].weight(), BS_TO_SELF_CLAIM_EXP_WEIGHT);
1121
1122         // The expected balance for the next three checks, with the largest-HTLC and to_self output
1123         // claim balances separated out.
1124         let expected_balance = vec![Balance::ClaimableAwaitingConfirmations {
1125                         // to_remote output in A's revoked commitment
1126                         claimable_amount_satoshis: 100_000 - 5_000 - 4_000 - 3,
1127                         confirmation_height: nodes[1].best_block_info().1 + 5,
1128                 }, Balance::CounterpartyRevokedOutputClaimable {
1129                         claimable_amount_satoshis: 3_000,
1130                 }, Balance::CounterpartyRevokedOutputClaimable {
1131                         claimable_amount_satoshis: 4_000,
1132                 }];
1133
1134         let to_self_unclaimed_balance = Balance::CounterpartyRevokedOutputClaimable {
1135                 claimable_amount_satoshis: 1_000_000 - 100_000 - 3_000 - chan_feerate *
1136                         (channel::commitment_tx_base_weight(opt_anchors) + 3 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1137         };
1138         let to_self_claimed_avail_height;
1139         let largest_htlc_unclaimed_balance = Balance::CounterpartyRevokedOutputClaimable {
1140                 claimable_amount_satoshis: 5_000,
1141         };
1142         let largest_htlc_claimed_avail_height;
1143
1144         // Once the channel has been closed by A, B now considers all of the commitment transactions'
1145         // outputs as `CounterpartyRevokedOutputClaimable`.
1146         assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_unclaimed_balance, &largest_htlc_unclaimed_balance]),
1147                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1148
1149         if confirm_htlc_spend_first {
1150                 mine_transaction(&nodes[1], &claim_txn[2]);
1151                 largest_htlc_claimed_avail_height = nodes[1].best_block_info().1 + 5;
1152                 to_self_claimed_avail_height = nodes[1].best_block_info().1 + 6; // will be claimed in the next block
1153         } else {
1154                 // Connect the to_self output claim, taking all of A's non-HTLC funds
1155                 mine_transaction(&nodes[1], &claim_txn[3]);
1156                 to_self_claimed_avail_height = nodes[1].best_block_info().1 + 5;
1157                 largest_htlc_claimed_avail_height = nodes[1].best_block_info().1 + 6; // will be claimed in the next block
1158         }
1159
1160         let largest_htlc_claimed_balance = Balance::ClaimableAwaitingConfirmations {
1161                 claimable_amount_satoshis: 5_000 - chan_feerate * INBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1162                 confirmation_height: largest_htlc_claimed_avail_height,
1163         };
1164         let to_self_claimed_balance = Balance::ClaimableAwaitingConfirmations {
1165                 claimable_amount_satoshis: 1_000_000 - 100_000 - 3_000 - chan_feerate *
1166                         (channel::commitment_tx_base_weight(opt_anchors) + 3 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000
1167                         - chan_feerate * claim_txn[3].weight() as u64 / 1000,
1168                 confirmation_height: to_self_claimed_avail_height,
1169         };
1170
1171         if confirm_htlc_spend_first {
1172                 assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_unclaimed_balance, &largest_htlc_claimed_balance]),
1173                         sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1174         } else {
1175                 assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_claimed_balance, &largest_htlc_unclaimed_balance]),
1176                         sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1177         }
1178
1179         if confirm_htlc_spend_first {
1180                 mine_transaction(&nodes[1], &claim_txn[3]);
1181         } else {
1182                 mine_transaction(&nodes[1], &claim_txn[2]);
1183         }
1184         assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_claimed_balance, &largest_htlc_claimed_balance]),
1185                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1186
1187         // Finally, connect the last two remaining HTLC spends and check that they move to
1188         // `ClaimableAwaitingConfirmations`
1189         mine_transaction(&nodes[1], &claim_txn[0]);
1190         mine_transaction(&nodes[1], &claim_txn[1]);
1191
1192         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1193                         // to_remote output in A's revoked commitment
1194                         claimable_amount_satoshis: 100_000 - 5_000 - 4_000 - 3,
1195                         confirmation_height: nodes[1].best_block_info().1 + 1,
1196                 }, Balance::ClaimableAwaitingConfirmations {
1197                         claimable_amount_satoshis: 1_000_000 - 100_000 - 3_000 - chan_feerate *
1198                                 (channel::commitment_tx_base_weight(opt_anchors) + 3 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000
1199                                 - chan_feerate * claim_txn[3].weight() as u64 / 1000,
1200                         confirmation_height: to_self_claimed_avail_height,
1201                 }, Balance::ClaimableAwaitingConfirmations {
1202                         claimable_amount_satoshis: 3_000 - chan_feerate * OUTBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1203                         confirmation_height: nodes[1].best_block_info().1 + 4,
1204                 }, Balance::ClaimableAwaitingConfirmations {
1205                         claimable_amount_satoshis: 4_000 - chan_feerate * INBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1206                         confirmation_height: nodes[1].best_block_info().1 + 5,
1207                 }, Balance::ClaimableAwaitingConfirmations {
1208                         claimable_amount_satoshis: 5_000 - chan_feerate * INBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1209                         confirmation_height: largest_htlc_claimed_avail_height,
1210                 }]),
1211                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1212
1213         connect_blocks(&nodes[1], 1);
1214         test_spendable_output(&nodes[1], &as_revoked_txn[0]);
1215
1216         let mut payment_failed_events = nodes[1].node.get_and_clear_pending_events();
1217         expect_payment_failed_conditions_event(&nodes[1], payment_failed_events.pop().unwrap(),
1218                 dust_payment_hash, false, PaymentFailedConditions::new());
1219         expect_payment_failed_conditions_event(&nodes[1], payment_failed_events.pop().unwrap(),
1220                 missing_htlc_payment_hash, false, PaymentFailedConditions::new());
1221         assert!(payment_failed_events.is_empty());
1222
1223         connect_blocks(&nodes[1], 1);
1224         test_spendable_output(&nodes[1], &claim_txn[if confirm_htlc_spend_first { 2 } else { 3 }]);
1225         connect_blocks(&nodes[1], 1);
1226         test_spendable_output(&nodes[1], &claim_txn[if confirm_htlc_spend_first { 3 } else { 2 }]);
1227         expect_payment_failed!(nodes[1], live_payment_hash, false);
1228         connect_blocks(&nodes[1], 1);
1229         test_spendable_output(&nodes[1], &claim_txn[0]);
1230         connect_blocks(&nodes[1], 1);
1231         test_spendable_output(&nodes[1], &claim_txn[1]);
1232         expect_payment_failed!(nodes[1], timeout_payment_hash, false);
1233         assert_eq!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances(), Vec::new());
1234 }
1235
1236 #[test]
1237 fn test_revoked_counterparty_commitment_balances() {
1238         do_test_revoked_counterparty_commitment_balances(true);
1239         do_test_revoked_counterparty_commitment_balances(false);
1240 }
1241
1242 #[test]
1243 fn test_revoked_counterparty_htlc_tx_balances() {
1244         // Tests `get_claimable_balances` for revocation spends of HTLC transactions.
1245         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1246         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
1247         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1248         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1249         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1250
1251         // Create some initial channels
1252         let (_, _, chan_id, funding_tx) =
1253                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 11_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1254         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
1255         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
1256
1257         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
1258         let failed_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 1_000_000).1;
1259         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_id);
1260         assert_eq!(revoked_local_txn[0].input.len(), 1);
1261         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, funding_tx.txid());
1262
1263         // The to-be-revoked commitment tx should have two HTLCs and an output for both sides
1264         assert_eq!(revoked_local_txn[0].output.len(), 4);
1265
1266         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
1267
1268         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
1269         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
1270
1271         // B will generate an HTLC-Success from its revoked commitment tx
1272         mine_transaction(&nodes[1], &revoked_local_txn[0]);
1273         check_closed_broadcast!(nodes[1], true);
1274         check_added_monitors!(nodes[1], 1);
1275         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
1276         let revoked_htlc_success_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1277
1278         assert_eq!(revoked_htlc_success_txn.len(), 2);
1279         assert_eq!(revoked_htlc_success_txn[0].input.len(), 1);
1280         assert_eq!(revoked_htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
1281         check_spends!(revoked_htlc_success_txn[0], revoked_local_txn[0]);
1282         check_spends!(revoked_htlc_success_txn[1], funding_tx);
1283
1284         connect_blocks(&nodes[1], TEST_FINAL_CLTV);
1285         let revoked_htlc_timeout_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1286         assert_eq!(revoked_htlc_timeout_txn.len(), 1);
1287         check_spends!(revoked_htlc_timeout_txn[0], revoked_local_txn[0]);
1288         assert_ne!(revoked_htlc_success_txn[0].input[0].previous_output, revoked_htlc_timeout_txn[0].input[0].previous_output);
1289         assert_eq!(revoked_htlc_success_txn[0].lock_time.0, 0);
1290         assert_ne!(revoked_htlc_timeout_txn[0].lock_time.0, 0);
1291
1292         // A will generate justice tx from B's revoked commitment/HTLC tx
1293         mine_transaction(&nodes[0], &revoked_local_txn[0]);
1294         check_closed_broadcast!(nodes[0], true);
1295         check_added_monitors!(nodes[0], 1);
1296         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1297         let to_remote_conf_height = nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1;
1298
1299         let as_commitment_claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1300         assert_eq!(as_commitment_claim_txn.len(), 2);
1301         check_spends!(as_commitment_claim_txn[0], revoked_local_txn[0]);
1302         check_spends!(as_commitment_claim_txn[1], funding_tx);
1303
1304         // The next two checks have the same balance set for A - even though we confirm a revoked HTLC
1305         // transaction our balance tracking doesn't use the on-chain value so the
1306         // `CounterpartyRevokedOutputClaimable` entry doesn't change.
1307         let as_balances = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1308                         // to_remote output in B's revoked commitment
1309                         claimable_amount_satoshis: 1_000_000 - 11_000 - 3_000 - chan_feerate *
1310                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1311                         confirmation_height: to_remote_conf_height,
1312                 }, Balance::CounterpartyRevokedOutputClaimable {
1313                         // to_self output in B's revoked commitment
1314                         claimable_amount_satoshis: 10_000,
1315                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1316                         claimable_amount_satoshis: 3_000,
1317                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1318                         claimable_amount_satoshis: 1_000,
1319                 }]);
1320         assert_eq!(as_balances,
1321                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1322
1323         mine_transaction(&nodes[0], &revoked_htlc_success_txn[0]);
1324         let as_htlc_claim_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1325         assert_eq!(as_htlc_claim_tx.len(), 2);
1326         check_spends!(as_htlc_claim_tx[0], revoked_htlc_success_txn[0]);
1327         check_spends!(as_htlc_claim_tx[1], revoked_local_txn[0]); // A has to generate a new claim for the remaining revoked
1328                                                                   // outputs (which no longer includes the spent HTLC output)
1329
1330         assert_eq!(as_balances,
1331                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1332
1333         assert_eq!(as_htlc_claim_tx[0].output.len(), 1);
1334         fuzzy_assert_eq(as_htlc_claim_tx[0].output[0].value,
1335                 3_000 - chan_feerate * (revoked_htlc_success_txn[0].weight() + as_htlc_claim_tx[0].weight()) as u64 / 1000);
1336
1337         mine_transaction(&nodes[0], &as_htlc_claim_tx[0]);
1338         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1339                         // to_remote output in B's revoked commitment
1340                         claimable_amount_satoshis: 1_000_000 - 11_000 - 3_000 - chan_feerate *
1341                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1342                         confirmation_height: to_remote_conf_height,
1343                 }, Balance::CounterpartyRevokedOutputClaimable {
1344                         // to_self output in B's revoked commitment
1345                         claimable_amount_satoshis: 10_000,
1346                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1347                         claimable_amount_satoshis: 1_000,
1348                 }, Balance::ClaimableAwaitingConfirmations {
1349                         claimable_amount_satoshis: as_htlc_claim_tx[0].output[0].value,
1350                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
1351                 }]),
1352                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1353
1354         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 3);
1355         test_spendable_output(&nodes[0], &revoked_local_txn[0]);
1356         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1357                         // to_self output to B
1358                         claimable_amount_satoshis: 10_000,
1359                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1360                         claimable_amount_satoshis: 1_000,
1361                 }, Balance::ClaimableAwaitingConfirmations {
1362                         claimable_amount_satoshis: as_htlc_claim_tx[0].output[0].value,
1363                         confirmation_height: nodes[0].best_block_info().1 + 2,
1364                 }]),
1365                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1366
1367         connect_blocks(&nodes[0], 2);
1368         test_spendable_output(&nodes[0], &as_htlc_claim_tx[0]);
1369         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1370                         // to_self output in B's revoked commitment
1371                         claimable_amount_satoshis: 10_000,
1372                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1373                         claimable_amount_satoshis: 1_000,
1374                 }]),
1375                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1376
1377         connect_blocks(&nodes[0], revoked_htlc_timeout_txn[0].lock_time.0 - nodes[0].best_block_info().1);
1378         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(&nodes[0],
1379                 [HTLCDestination::FailedPayment { payment_hash: failed_payment_hash }]);
1380         // As time goes on A may split its revocation claim transaction into multiple.
1381         let as_fewer_input_rbf = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1382         for tx in as_fewer_input_rbf.iter() {
1383                 check_spends!(tx, revoked_local_txn[0]);
1384         }
1385
1386         // Connect a number of additional blocks to ensure we don't forget the HTLC output needs
1387         // claiming.
1388         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
1389         let as_fewer_input_rbf = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1390         for tx in as_fewer_input_rbf.iter() {
1391                 check_spends!(tx, revoked_local_txn[0]);
1392         }
1393
1394         mine_transaction(&nodes[0], &revoked_htlc_timeout_txn[0]);
1395         let as_second_htlc_claim_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1396         assert_eq!(as_second_htlc_claim_tx.len(), 2);
1397
1398         check_spends!(as_second_htlc_claim_tx[0], revoked_htlc_timeout_txn[0]);
1399         check_spends!(as_second_htlc_claim_tx[1], revoked_local_txn[0]);
1400
1401         // Connect blocks to finalize the HTLC resolution with the HTLC-Timeout transaction. In a
1402         // previous iteration of the revoked balance handling this would result in us "forgetting" that
1403         // the revoked HTLC output still needed to be claimed.
1404         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
1405         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1406                         // to_self output in B's revoked commitment
1407                         claimable_amount_satoshis: 10_000,
1408                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1409                         claimable_amount_satoshis: 1_000,
1410                 }]),
1411                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1412
1413         mine_transaction(&nodes[0], &as_second_htlc_claim_tx[0]);
1414         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1415                         // to_self output in B's revoked commitment
1416                         claimable_amount_satoshis: 10_000,
1417                 }, Balance::ClaimableAwaitingConfirmations {
1418                         claimable_amount_satoshis: as_second_htlc_claim_tx[0].output[0].value,
1419                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
1420                 }]),
1421                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1422
1423         mine_transaction(&nodes[0], &as_second_htlc_claim_tx[1]);
1424         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1425                         // to_self output in B's revoked commitment
1426                         claimable_amount_satoshis: as_second_htlc_claim_tx[1].output[0].value,
1427                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
1428                 }, Balance::ClaimableAwaitingConfirmations {
1429                         claimable_amount_satoshis: as_second_htlc_claim_tx[0].output[0].value,
1430                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 2,
1431                 }]),
1432                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1433
1434         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
1435         test_spendable_output(&nodes[0], &as_second_htlc_claim_tx[0]);
1436         connect_blocks(&nodes[0], 1);
1437         test_spendable_output(&nodes[0], &as_second_htlc_claim_tx[1]);
1438
1439         assert_eq!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances(), Vec::new());
1440 }
1441
1442 #[test]
1443 fn test_revoked_counterparty_aggregated_claims() {
1444         // Tests `get_claimable_balances` for revoked counterparty commitment transactions when
1445         // claiming with an aggregated claim transaction.
1446         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1447         // We broadcast a second-to-latest commitment transaction, without providing the revocation
1448         // secret to the counterparty. However, because we always immediately take the revocation
1449         // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
1450         // transaction which, from the point of view of our keys_manager, is revoked.
1451         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
1452         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1453         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1454         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1455
1456         let (_, _, chan_id, funding_tx) =
1457                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 100_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1458         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
1459         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
1460
1461         // We create two HTLCs, one which we will give A the preimage to to generate an HTLC-Success
1462         // transaction, and one which we will not, allowing B to claim the HTLC output in an aggregated
1463         // revocation-claim transaction.
1464
1465         let (claimed_payment_preimage, claimed_payment_hash, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
1466         let revoked_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 4_000_000).1;
1467
1468         let htlc_cltv_timeout = nodes[1].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1469
1470         // Cheat by giving A's ChannelMonitor the preimage to the to-be-claimed HTLC so that we have an
1471         // HTLC-claim transaction on the to-be-revoked state.
1472         get_monitor!(nodes[0], chan_id).provide_payment_preimage(&claimed_payment_hash, &claimed_payment_preimage,
1473                 &node_cfgs[0].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[0].fee_estimator), &nodes[0].logger);
1474
1475         // Now get the latest commitment transaction from A and then update the fee to revoke it
1476         let as_revoked_txn = get_local_commitment_txn!(nodes[0], chan_id);
1477
1478         assert_eq!(as_revoked_txn.len(), 2);
1479         check_spends!(as_revoked_txn[0], funding_tx);
1480         check_spends!(as_revoked_txn[1], as_revoked_txn[0]); // The HTLC-Claim transaction
1481
1482         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
1483         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
1484
1485         {
1486                 let mut feerate = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1487                 *feerate += 1;
1488         }
1489         nodes[0].node.timer_tick_occurred();
1490         check_added_monitors!(nodes[0], 1);
1491
1492         let fee_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1493         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &fee_update.update_fee.unwrap());
1494         commitment_signed_dance!(nodes[1], nodes[0], fee_update.commitment_signed, false);
1495
1496         nodes[0].node.claim_funds(claimed_payment_preimage);
1497         expect_payment_claimed!(nodes[0], claimed_payment_hash, 3_000_000);
1498         check_added_monitors!(nodes[0], 1);
1499         let _a_htlc_msgs = get_htlc_update_msgs!(&nodes[0], nodes[1].node.get_our_node_id());
1500
1501         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
1502                         claimable_amount_satoshis: 100_000 - 4_000 - 3_000,
1503                 }, Balance::MaybeTimeoutClaimableHTLC {
1504                         claimable_amount_satoshis: 4_000,
1505                         claimable_height: htlc_cltv_timeout,
1506                 }, Balance::MaybeTimeoutClaimableHTLC {
1507                         claimable_amount_satoshis: 3_000,
1508                         claimable_height: htlc_cltv_timeout,
1509                 }]),
1510                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1511
1512         mine_transaction(&nodes[1], &as_revoked_txn[0]);
1513         check_closed_broadcast!(nodes[1], true);
1514         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
1515         check_added_monitors!(nodes[1], 1);
1516
1517         let mut claim_txn: Vec<_> = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..).filter(|tx| tx.input.iter().any(|inp| inp.previous_output.txid == as_revoked_txn[0].txid())).collect();
1518         // Currently the revoked commitment outputs are all claimed in one aggregated transaction
1519         assert_eq!(claim_txn.len(), 1);
1520         assert_eq!(claim_txn[0].input.len(), 3);
1521         check_spends!(claim_txn[0], as_revoked_txn[0]);
1522
1523         let to_remote_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1524
1525         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1526                         // to_remote output in A's revoked commitment
1527                         claimable_amount_satoshis: 100_000 - 4_000 - 3_000,
1528                         confirmation_height: to_remote_maturity,
1529                 }, Balance::CounterpartyRevokedOutputClaimable {
1530                         // to_self output in A's revoked commitment
1531                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1532                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1533                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1534                         claimable_amount_satoshis: 4_000,
1535                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1536                         claimable_amount_satoshis: 3_000,
1537                 }]),
1538                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1539
1540         // Confirm A's HTLC-Success tranasction which presumably raced B's claim, causing B to create a
1541         // new claim.
1542         mine_transaction(&nodes[1], &as_revoked_txn[1]);
1543         expect_payment_sent!(nodes[1], claimed_payment_preimage);
1544         let mut claim_txn_2: Vec<_> = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1545         claim_txn_2.sort_unstable_by_key(|tx| if tx.input.iter().any(|inp| inp.previous_output.txid == as_revoked_txn[0].txid()) { 0 } else { 1 });
1546         // Once B sees the HTLC-Success transaction it splits its claim transaction into two, though in
1547         // theory it could re-aggregate the claims as well.
1548         assert_eq!(claim_txn_2.len(), 2);
1549         assert_eq!(claim_txn_2[0].input.len(), 2);
1550         check_spends!(claim_txn_2[0], as_revoked_txn[0]);
1551         assert_eq!(claim_txn_2[1].input.len(), 1);
1552         check_spends!(claim_txn_2[1], as_revoked_txn[1]);
1553
1554         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1555                         // to_remote output in A's revoked commitment
1556                         claimable_amount_satoshis: 100_000 - 4_000 - 3_000,
1557                         confirmation_height: to_remote_maturity,
1558                 }, Balance::CounterpartyRevokedOutputClaimable {
1559                         // to_self output in A's revoked commitment
1560                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1561                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1562                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1563                         claimable_amount_satoshis: 4_000,
1564                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1565                         // The amount here is a bit of a misnomer, really its been reduced by the HTLC
1566                         // transaction fee, but the claimable amount is always a bit of an overshoot for HTLCs
1567                         // anyway, so its not a big change.
1568                         claimable_amount_satoshis: 3_000,
1569                 }]),
1570                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1571
1572         connect_blocks(&nodes[1], 5);
1573         test_spendable_output(&nodes[1], &as_revoked_txn[0]);
1574
1575         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1576                         // to_self output in A's revoked commitment
1577                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1578                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1579                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1580                         claimable_amount_satoshis: 4_000,
1581                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1582                         // The amount here is a bit of a misnomer, really its been reduced by the HTLC
1583                         // transaction fee, but the claimable amount is always a bit of an overshoot for HTLCs
1584                         // anyway, so its not a big change.
1585                         claimable_amount_satoshis: 3_000,
1586                 }]),
1587                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1588
1589         mine_transaction(&nodes[1], &claim_txn_2[1]);
1590         let htlc_2_claim_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1591
1592         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1593                         // to_self output in A's revoked commitment
1594                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1595                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1596                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1597                         claimable_amount_satoshis: 4_000,
1598                 }, Balance::ClaimableAwaitingConfirmations { // HTLC 2
1599                         claimable_amount_satoshis: claim_txn_2[1].output[0].value,
1600                         confirmation_height: htlc_2_claim_maturity,
1601                 }]),
1602                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1603
1604         connect_blocks(&nodes[1], 5);
1605         test_spendable_output(&nodes[1], &claim_txn_2[1]);
1606
1607         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1608                         // to_self output in A's revoked commitment
1609                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1610                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1611                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1612                         claimable_amount_satoshis: 4_000,
1613                 }]),
1614                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1615
1616         mine_transaction(&nodes[1], &claim_txn_2[0]);
1617         let rest_claim_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1618
1619         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
1620                         claimable_amount_satoshis: claim_txn_2[0].output[0].value,
1621                         confirmation_height: rest_claim_maturity,
1622                 }],
1623                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
1624
1625         assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); // We shouldn't fail the payment until we spend the output
1626
1627         connect_blocks(&nodes[1], 5);
1628         expect_payment_failed!(nodes[1], revoked_payment_hash, false);
1629         test_spendable_output(&nodes[1], &claim_txn_2[0]);
1630         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1631 }