Rename `PaymentReceived` to `PaymentClaimable`
[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, PaymentId};
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), PaymentId(payment_hash.0)).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         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
572         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
573         // monitor events or claimable balances.
574         for node in nodes.iter() {
575                 connect_blocks(node, 6);
576                 connect_blocks(node, 6);
577                 assert!(node.chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
578                 assert!(node.chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
579         }
580 }
581
582 #[test]
583 fn test_claim_value_force_close() {
584         do_test_claim_value_force_close(true);
585         do_test_claim_value_force_close(false);
586 }
587
588 #[test]
589 fn test_balances_on_local_commitment_htlcs() {
590         // Previously, when handling the broadcast of a local commitment transactions (with associated
591         // CSV delays prior to spendability), we incorrectly handled the CSV delays on HTLC
592         // transactions. This caused us to miss spendable outputs for HTLCs which were awaiting a CSV
593         // delay prior to spendability.
594         //
595         // Further, because of this, we could hit an assertion as `get_claimable_balances` asserted
596         // that HTLCs were resolved after the funding spend was resolved, which was not true if the
597         // HTLC did not have a CSV delay attached (due to the above bug or due to it being an HTLC
598         // claim by our counterparty).
599         let chanmon_cfgs = create_chanmon_cfgs(2);
600         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
601         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
602         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
603
604         // Create a single channel with two pending HTLCs from nodes[0] to nodes[1], one which nodes[1]
605         // knows the preimage for, one which it does not.
606         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());
607         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
608
609         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000_000);
610         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
611         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
612         check_added_monitors!(nodes[0], 1);
613
614         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
615         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
616         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
617
618         expect_pending_htlcs_forwardable!(nodes[1]);
619         expect_payment_claimable!(nodes[1], payment_hash, payment_secret, 10_000_000);
620
621         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 20_000_000);
622         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
623         check_added_monitors!(nodes[0], 1);
624
625         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
626         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
627         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
628
629         expect_pending_htlcs_forwardable!(nodes[1]);
630         expect_payment_claimable!(nodes[1], payment_hash_2, payment_secret_2, 20_000_000);
631         nodes[1].node.claim_funds(payment_preimage_2);
632         get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
633         check_added_monitors!(nodes[1], 1);
634         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000_000);
635
636         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
637         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
638
639         // Get nodes[0]'s commitment transaction and HTLC-Timeout transactions
640         let as_txn = get_local_commitment_txn!(nodes[0], chan_id);
641         assert_eq!(as_txn.len(), 3);
642         check_spends!(as_txn[1], as_txn[0]);
643         check_spends!(as_txn[2], as_txn[0]);
644         check_spends!(as_txn[0], funding_tx);
645
646         // First confirm the commitment transaction on nodes[0], which should leave us with three
647         // claimable balances.
648         let node_a_commitment_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
649         mine_transaction(&nodes[0], &as_txn[0]);
650         check_added_monitors!(nodes[0], 1);
651         check_closed_broadcast!(nodes[0], true);
652         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
653
654         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
655                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
656                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
657                         confirmation_height: node_a_commitment_claimable,
658                 }, Balance::MaybeTimeoutClaimableHTLC {
659                         claimable_amount_satoshis: 10_000,
660                         claimable_height: htlc_cltv_timeout,
661                 }, Balance::MaybeTimeoutClaimableHTLC {
662                         claimable_amount_satoshis: 20_000,
663                         claimable_height: htlc_cltv_timeout,
664                 }]),
665                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
666
667         // Get nodes[1]'s HTLC claim tx for the second HTLC
668         mine_transaction(&nodes[1], &as_txn[0]);
669         check_added_monitors!(nodes[1], 1);
670         check_closed_broadcast!(nodes[1], true);
671         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
672         let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
673         assert_eq!(bs_htlc_claim_txn.len(), 3);
674         check_spends!(bs_htlc_claim_txn[0], as_txn[0]);
675         check_spends!(bs_htlc_claim_txn[1], funding_tx);
676         check_spends!(bs_htlc_claim_txn[2], bs_htlc_claim_txn[1]);
677
678         // Connect blocks until the HTLCs expire, allowing us to (validly) broadcast the HTLC-Timeout
679         // transaction.
680         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
681         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
682                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
683                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
684                         confirmation_height: node_a_commitment_claimable,
685                 }, Balance::MaybeTimeoutClaimableHTLC {
686                         claimable_amount_satoshis: 10_000,
687                         claimable_height: htlc_cltv_timeout,
688                 }, Balance::MaybeTimeoutClaimableHTLC {
689                         claimable_amount_satoshis: 20_000,
690                         claimable_height: htlc_cltv_timeout,
691                 }]),
692                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
693         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
694
695         // Now confirm nodes[0]'s HTLC-Timeout transaction, which changes the claimable balance to an
696         // "awaiting confirmations" one.
697         let node_a_htlc_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
698         mine_transaction(&nodes[0], &as_txn[1]);
699         // Note that prior to the fix in the commit which introduced this test, this (and the next
700         // balance) check failed. With this check removed, the code panicked in the `connect_blocks`
701         // call, as described, two hunks down.
702         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
703                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
704                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
705                         confirmation_height: node_a_commitment_claimable,
706                 }, Balance::ClaimableAwaitingConfirmations {
707                         claimable_amount_satoshis: 10_000,
708                         confirmation_height: node_a_htlc_claimable,
709                 }, Balance::MaybeTimeoutClaimableHTLC {
710                         claimable_amount_satoshis: 20_000,
711                         claimable_height: htlc_cltv_timeout,
712                 }]),
713                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
714
715         // Now confirm nodes[1]'s HTLC claim, giving nodes[0] the preimage. Note that the "maybe
716         // claimable" balance remains until we see ANTI_REORG_DELAY blocks.
717         mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
718         expect_payment_sent!(nodes[0], payment_preimage_2);
719         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
720                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
721                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
722                         confirmation_height: node_a_commitment_claimable,
723                 }, Balance::ClaimableAwaitingConfirmations {
724                         claimable_amount_satoshis: 10_000,
725                         confirmation_height: node_a_htlc_claimable,
726                 }, Balance::MaybeTimeoutClaimableHTLC {
727                         claimable_amount_satoshis: 20_000,
728                         claimable_height: htlc_cltv_timeout,
729                 }]),
730                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
731
732         // Finally make the HTLC transactions have ANTI_REORG_DELAY blocks. This call previously
733         // panicked as described in the test introduction. This will remove the "maybe claimable"
734         // spendable output as nodes[1] has fully claimed the second HTLC.
735         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
736         expect_payment_failed!(nodes[0], payment_hash, false);
737
738         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
739                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
740                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
741                         confirmation_height: node_a_commitment_claimable,
742                 }, Balance::ClaimableAwaitingConfirmations {
743                         claimable_amount_satoshis: 10_000,
744                         confirmation_height: node_a_htlc_claimable,
745                 }]),
746                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
747
748         // Connect blocks until the commitment transaction's CSV expires, providing us the relevant
749         // `SpendableOutputs` event and removing the claimable balance entry.
750         connect_blocks(&nodes[0], node_a_commitment_claimable - nodes[0].best_block_info().1);
751         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
752                         claimable_amount_satoshis: 10_000,
753                         confirmation_height: node_a_htlc_claimable,
754                 }],
755                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
756         test_spendable_output(&nodes[0], &as_txn[0]);
757
758         // Connect blocks until the HTLC-Timeout's CSV expires, providing us the relevant
759         // `SpendableOutputs` event and removing the claimable balance entry.
760         connect_blocks(&nodes[0], node_a_htlc_claimable - nodes[0].best_block_info().1);
761         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
762         test_spendable_output(&nodes[0], &as_txn[1]);
763
764         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
765         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
766         // monitor events or claimable balances.
767         connect_blocks(&nodes[0], 6);
768         connect_blocks(&nodes[0], 6);
769         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
770         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
771 }
772
773 #[test]
774 fn test_no_preimage_inbound_htlc_balances() {
775         // Tests that MaybePreimageClaimableHTLC are generated for inbound HTLCs for which we do not
776         // have a preimage.
777         let chanmon_cfgs = create_chanmon_cfgs(2);
778         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
779         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
780         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
781
782         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());
783         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
784
785         // Send two HTLCs, one from A to B, and one from B to A.
786         let to_b_failed_payment_hash = route_payment(&nodes[0], &[&nodes[1]], 10_000_000).1;
787         let to_a_failed_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 20_000_000).1;
788         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
789
790         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
791         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
792
793         // Both A and B will have an HTLC that's claimable on timeout and one that's claimable if they
794         // receive the preimage. These will remain the same through the channel closure and until the
795         // HTLC output is spent.
796
797         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
798                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
799                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
800                 }, Balance::MaybePreimageClaimableHTLC {
801                         claimable_amount_satoshis: 20_000,
802                         expiry_height: htlc_cltv_timeout,
803                 }, Balance::MaybeTimeoutClaimableHTLC {
804                         claimable_amount_satoshis: 10_000,
805                         claimable_height: htlc_cltv_timeout,
806                 }]),
807                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
808
809         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
810                         claimable_amount_satoshis: 500_000 - 20_000,
811                 }, Balance::MaybePreimageClaimableHTLC {
812                         claimable_amount_satoshis: 10_000,
813                         expiry_height: htlc_cltv_timeout,
814                 }, Balance::MaybeTimeoutClaimableHTLC {
815                         claimable_amount_satoshis: 20_000,
816                         claimable_height: htlc_cltv_timeout,
817                 }]),
818                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
819
820         // Get nodes[0]'s commitment transaction and HTLC-Timeout transaction
821         let as_txn = get_local_commitment_txn!(nodes[0], chan_id);
822         assert_eq!(as_txn.len(), 2);
823         check_spends!(as_txn[1], as_txn[0]);
824         check_spends!(as_txn[0], funding_tx);
825
826         // Now close the channel by confirming A's commitment transaction on both nodes, checking the
827         // claimable balances remain the same except for the non-HTLC balance changing variant.
828         let node_a_commitment_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
829         let as_pre_spend_claims = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
830                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
831                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
832                         confirmation_height: node_a_commitment_claimable,
833                 }, Balance::MaybePreimageClaimableHTLC {
834                         claimable_amount_satoshis: 20_000,
835                         expiry_height: htlc_cltv_timeout,
836                 }, Balance::MaybeTimeoutClaimableHTLC {
837                         claimable_amount_satoshis: 10_000,
838                         claimable_height: htlc_cltv_timeout,
839                 }]);
840
841         mine_transaction(&nodes[0], &as_txn[0]);
842         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
843         check_added_monitors!(nodes[0], 1);
844         check_closed_broadcast!(nodes[0], true);
845         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
846
847         assert_eq!(as_pre_spend_claims,
848                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
849
850         mine_transaction(&nodes[1], &as_txn[0]);
851         check_added_monitors!(nodes[1], 1);
852         check_closed_broadcast!(nodes[1], true);
853         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
854
855         let node_b_commitment_claimable = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
856         let mut bs_pre_spend_claims = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
857                         claimable_amount_satoshis: 500_000 - 20_000,
858                         confirmation_height: node_b_commitment_claimable,
859                 }, Balance::MaybePreimageClaimableHTLC {
860                         claimable_amount_satoshis: 10_000,
861                         expiry_height: htlc_cltv_timeout,
862                 }, Balance::MaybeTimeoutClaimableHTLC {
863                         claimable_amount_satoshis: 20_000,
864                         claimable_height: htlc_cltv_timeout,
865                 }]);
866         assert_eq!(bs_pre_spend_claims,
867                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
868
869         // We'll broadcast the HTLC-Timeout transaction one block prior to the htlc's expiration (as it
870         // is confirmable in the next block), but will still include the same claimable balances as no
871         // HTLC has been spent, even after the HTLC expires. We'll also fail the inbound HTLC, but it
872         // won't do anything as the channel is already closed.
873
874         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
875         let as_htlc_timeout_claim = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
876         assert_eq!(as_htlc_timeout_claim.len(), 1);
877         check_spends!(as_htlc_timeout_claim[0], as_txn[0]);
878         expect_pending_htlcs_forwardable_conditions!(nodes[0],
879                 [HTLCDestination::FailedPayment { payment_hash: to_a_failed_payment_hash }]);
880
881         assert_eq!(as_pre_spend_claims,
882                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
883
884         connect_blocks(&nodes[0], 1);
885         assert_eq!(as_pre_spend_claims,
886                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
887
888         // For node B, we'll get the non-HTLC funds claimable after ANTI_REORG_DELAY confirmations
889         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
890         test_spendable_output(&nodes[1], &as_txn[0]);
891         bs_pre_spend_claims.retain(|e| if let Balance::ClaimableAwaitingConfirmations { .. } = e { false } else { true });
892
893         // The next few blocks for B look the same as for A, though for the opposite HTLC
894         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
895         connect_blocks(&nodes[1], TEST_FINAL_CLTV - (ANTI_REORG_DELAY - 1) - 1);
896         expect_pending_htlcs_forwardable_conditions!(nodes[1],
897                 [HTLCDestination::FailedPayment { payment_hash: to_b_failed_payment_hash }]);
898         let bs_htlc_timeout_claim = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
899         assert_eq!(bs_htlc_timeout_claim.len(), 1);
900         check_spends!(bs_htlc_timeout_claim[0], as_txn[0]);
901
902         assert_eq!(bs_pre_spend_claims,
903                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
904
905         connect_blocks(&nodes[1], 1);
906         assert_eq!(bs_pre_spend_claims,
907                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
908
909         // Now confirm the two HTLC timeout transactions for A, checking that the inbound HTLC resolves
910         // after ANTI_REORG_DELAY confirmations and the other takes BREAKDOWN_TIMEOUT confirmations.
911         mine_transaction(&nodes[0], &as_htlc_timeout_claim[0]);
912         let as_timeout_claimable_height = nodes[0].best_block_info().1 + (BREAKDOWN_TIMEOUT as u32) - 1;
913         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
914                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
915                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
916                         confirmation_height: node_a_commitment_claimable,
917                 }, Balance::MaybePreimageClaimableHTLC {
918                         claimable_amount_satoshis: 20_000,
919                         expiry_height: htlc_cltv_timeout,
920                 }, Balance::ClaimableAwaitingConfirmations {
921                         claimable_amount_satoshis: 10_000,
922                         confirmation_height: as_timeout_claimable_height,
923                 }]),
924                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
925
926         mine_transaction(&nodes[0], &bs_htlc_timeout_claim[0]);
927         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
928                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
929                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
930                         confirmation_height: node_a_commitment_claimable,
931                 }, Balance::MaybePreimageClaimableHTLC {
932                         claimable_amount_satoshis: 20_000,
933                         expiry_height: htlc_cltv_timeout,
934                 }, Balance::ClaimableAwaitingConfirmations {
935                         claimable_amount_satoshis: 10_000,
936                         confirmation_height: as_timeout_claimable_height,
937                 }]),
938                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
939
940         // Once as_htlc_timeout_claim[0] reaches ANTI_REORG_DELAY confirmations, we should get a
941         // payment failure event.
942         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
943         expect_payment_failed!(nodes[0], to_b_failed_payment_hash, false);
944
945         connect_blocks(&nodes[0], 1);
946         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
947                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
948                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
949                         confirmation_height: node_a_commitment_claimable,
950                 }, Balance::ClaimableAwaitingConfirmations {
951                         claimable_amount_satoshis: 10_000,
952                         confirmation_height: core::cmp::max(as_timeout_claimable_height, htlc_cltv_timeout),
953                 }]),
954                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
955
956         connect_blocks(&nodes[0], node_a_commitment_claimable - nodes[0].best_block_info().1);
957         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
958                         claimable_amount_satoshis: 10_000,
959                         confirmation_height: core::cmp::max(as_timeout_claimable_height, htlc_cltv_timeout),
960                 }],
961                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
962         test_spendable_output(&nodes[0], &as_txn[0]);
963
964         connect_blocks(&nodes[0], as_timeout_claimable_height - nodes[0].best_block_info().1);
965         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
966         test_spendable_output(&nodes[0], &as_htlc_timeout_claim[0]);
967
968         // The process for B should be completely identical as well, noting that the non-HTLC-balance
969         // was already claimed.
970         mine_transaction(&nodes[1], &bs_htlc_timeout_claim[0]);
971         let bs_timeout_claimable_height = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
972         assert_eq!(sorted_vec(vec![Balance::MaybePreimageClaimableHTLC {
973                         claimable_amount_satoshis: 10_000,
974                         expiry_height: htlc_cltv_timeout,
975                 }, Balance::ClaimableAwaitingConfirmations {
976                         claimable_amount_satoshis: 20_000,
977                         confirmation_height: bs_timeout_claimable_height,
978                 }]),
979                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
980
981         mine_transaction(&nodes[1], &as_htlc_timeout_claim[0]);
982         assert_eq!(sorted_vec(vec![Balance::MaybePreimageClaimableHTLC {
983                         claimable_amount_satoshis: 10_000,
984                         expiry_height: htlc_cltv_timeout,
985                 }, Balance::ClaimableAwaitingConfirmations {
986                         claimable_amount_satoshis: 20_000,
987                         confirmation_height: bs_timeout_claimable_height,
988                 }]),
989                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
990
991         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 2);
992         expect_payment_failed!(nodes[1], to_a_failed_payment_hash, false);
993
994         assert_eq!(vec![Balance::MaybePreimageClaimableHTLC {
995                         claimable_amount_satoshis: 10_000,
996                         expiry_height: htlc_cltv_timeout,
997                 }],
998                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
999         test_spendable_output(&nodes[1], &bs_htlc_timeout_claim[0]);
1000
1001         connect_blocks(&nodes[1], 1);
1002         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1003
1004         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
1005         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
1006         // monitor events or claimable balances.
1007         connect_blocks(&nodes[1], 6);
1008         connect_blocks(&nodes[1], 6);
1009         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1010         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1011 }
1012
1013 fn sorted_vec_with_additions<T: Ord + Clone>(v_orig: &Vec<T>, extra_ts: &[&T]) -> Vec<T> {
1014         let mut v = v_orig.clone();
1015         for t in extra_ts {
1016                 v.push((*t).clone());
1017         }
1018         v.sort_unstable();
1019         v
1020 }
1021
1022 fn do_test_revoked_counterparty_commitment_balances(confirm_htlc_spend_first: bool) {
1023         // Tests `get_claimable_balances` for revoked counterparty commitment transactions.
1024         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1025         // We broadcast a second-to-latest commitment transaction, without providing the revocation
1026         // secret to the counterparty. However, because we always immediately take the revocation
1027         // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
1028         // transaction which, from the point of view of our keys_manager, is revoked.
1029         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
1030         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1031         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1032         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1033
1034         let (_, _, chan_id, funding_tx) =
1035                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 100_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1036         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
1037         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
1038
1039         // We create five HTLCs for B to claim against A's revoked commitment transaction:
1040         //
1041         // (1) one for which A is the originator and B knows the preimage
1042         // (2) one for which B is the originator where the HTLC has since timed-out
1043         // (3) one for which B is the originator but where the HTLC has not yet timed-out
1044         // (4) one dust HTLC which is lost in the channel closure
1045         // (5) one that actually isn't in the revoked commitment transaction at all, but was added in
1046         //     later commitment transaction updates
1047         //
1048         // Though they could all be claimed in a single claim transaction, due to CLTV timeouts they
1049         // are all currently claimed in separate transactions, which helps us test as we can claim
1050         // HTLCs individually.
1051
1052         let (claimed_payment_preimage, claimed_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
1053         let timeout_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 4_000_000).1;
1054         let dust_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 3_000).1;
1055
1056         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1057
1058         connect_blocks(&nodes[0], 10);
1059         connect_blocks(&nodes[1], 10);
1060
1061         let live_htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1062         let live_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 5_000_000).1;
1063
1064         // Get the latest commitment transaction from A and then update the fee to revoke it
1065         let as_revoked_txn = get_local_commitment_txn!(nodes[0], chan_id);
1066         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
1067
1068         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
1069
1070         let missing_htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1071         let missing_htlc_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 2_000_000).1;
1072
1073         nodes[1].node.claim_funds(claimed_payment_preimage);
1074         expect_payment_claimed!(nodes[1], claimed_payment_hash, 3_000_000);
1075         check_added_monitors!(nodes[1], 1);
1076         let _b_htlc_msgs = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
1077
1078         connect_blocks(&nodes[0], htlc_cltv_timeout + 1 - 10);
1079         check_closed_broadcast!(nodes[0], true);
1080         check_added_monitors!(nodes[0], 1);
1081
1082         let mut events = nodes[0].node.get_and_clear_pending_events();
1083         assert_eq!(events.len(), 6);
1084         let mut failed_payments: HashSet<_> =
1085                 [timeout_payment_hash, dust_payment_hash, live_payment_hash, missing_htlc_payment_hash]
1086                 .iter().map(|a| *a).collect();
1087         events.retain(|ev| {
1088                 match ev {
1089                         Event::HTLCHandlingFailed { failed_next_destination: HTLCDestination::NextHopChannel { node_id, channel_id }, .. } => {
1090                                 assert_eq!(*channel_id, chan_id);
1091                                 assert_eq!(*node_id, Some(nodes[1].node.get_our_node_id()));
1092                                 false
1093                         },
1094                         Event::HTLCHandlingFailed { failed_next_destination: HTLCDestination::FailedPayment { payment_hash }, .. } => {
1095                                 assert!(failed_payments.remove(payment_hash));
1096                                 false
1097                         },
1098                         _ => true,
1099                 }
1100         });
1101         assert!(failed_payments.is_empty());
1102         if let Event::PendingHTLCsForwardable { .. } = events[0] {} else { panic!(); }
1103         match &events[1] {
1104                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
1105                 _ => panic!(),
1106         }
1107
1108         connect_blocks(&nodes[1], htlc_cltv_timeout + 1 - 10);
1109         check_closed_broadcast!(nodes[1], true);
1110         check_added_monitors!(nodes[1], 1);
1111         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
1112
1113         // Prior to channel closure, B considers the preimage HTLC as its own, and otherwise only
1114         // lists the two on-chain timeout-able HTLCs as claimable balances.
1115         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
1116                         claimable_amount_satoshis: 100_000 - 5_000 - 4_000 - 3 - 2_000 + 3_000,
1117                 }, Balance::MaybeTimeoutClaimableHTLC {
1118                         claimable_amount_satoshis: 2_000,
1119                         claimable_height: missing_htlc_cltv_timeout,
1120                 }, Balance::MaybeTimeoutClaimableHTLC {
1121                         claimable_amount_satoshis: 4_000,
1122                         claimable_height: htlc_cltv_timeout,
1123                 }, Balance::MaybeTimeoutClaimableHTLC {
1124                         claimable_amount_satoshis: 5_000,
1125                         claimable_height: live_htlc_cltv_timeout,
1126                 }]),
1127                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1128
1129         mine_transaction(&nodes[1], &as_revoked_txn[0]);
1130         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();
1131         // Currently the revoked commitment is claimed in four transactions as the HTLCs all expire
1132         // quite soon.
1133         assert_eq!(claim_txn.len(), 4);
1134         claim_txn.sort_unstable_by_key(|tx| tx.output.iter().map(|output| output.value).sum::<u64>());
1135
1136         // The following constants were determined experimentally
1137         const BS_TO_SELF_CLAIM_EXP_WEIGHT: usize = 483;
1138         const OUTBOUND_HTLC_CLAIM_EXP_WEIGHT: usize = 571;
1139         const INBOUND_HTLC_CLAIM_EXP_WEIGHT: usize = 578;
1140
1141         // Check that the weight is close to the expected weight. Note that signature sizes vary
1142         // somewhat so it may not always be exact.
1143         fuzzy_assert_eq(claim_txn[0].weight(), OUTBOUND_HTLC_CLAIM_EXP_WEIGHT);
1144         fuzzy_assert_eq(claim_txn[1].weight(), INBOUND_HTLC_CLAIM_EXP_WEIGHT);
1145         fuzzy_assert_eq(claim_txn[2].weight(), INBOUND_HTLC_CLAIM_EXP_WEIGHT);
1146         fuzzy_assert_eq(claim_txn[3].weight(), BS_TO_SELF_CLAIM_EXP_WEIGHT);
1147
1148         // The expected balance for the next three checks, with the largest-HTLC and to_self output
1149         // claim balances separated out.
1150         let expected_balance = vec![Balance::ClaimableAwaitingConfirmations {
1151                         // to_remote output in A's revoked commitment
1152                         claimable_amount_satoshis: 100_000 - 5_000 - 4_000 - 3,
1153                         confirmation_height: nodes[1].best_block_info().1 + 5,
1154                 }, Balance::CounterpartyRevokedOutputClaimable {
1155                         claimable_amount_satoshis: 3_000,
1156                 }, Balance::CounterpartyRevokedOutputClaimable {
1157                         claimable_amount_satoshis: 4_000,
1158                 }];
1159
1160         let to_self_unclaimed_balance = Balance::CounterpartyRevokedOutputClaimable {
1161                 claimable_amount_satoshis: 1_000_000 - 100_000 - 3_000 - chan_feerate *
1162                         (channel::commitment_tx_base_weight(opt_anchors) + 3 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1163         };
1164         let to_self_claimed_avail_height;
1165         let largest_htlc_unclaimed_balance = Balance::CounterpartyRevokedOutputClaimable {
1166                 claimable_amount_satoshis: 5_000,
1167         };
1168         let largest_htlc_claimed_avail_height;
1169
1170         // Once the channel has been closed by A, B now considers all of the commitment transactions'
1171         // outputs as `CounterpartyRevokedOutputClaimable`.
1172         assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_unclaimed_balance, &largest_htlc_unclaimed_balance]),
1173                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1174
1175         if confirm_htlc_spend_first {
1176                 mine_transaction(&nodes[1], &claim_txn[2]);
1177                 largest_htlc_claimed_avail_height = nodes[1].best_block_info().1 + 5;
1178                 to_self_claimed_avail_height = nodes[1].best_block_info().1 + 6; // will be claimed in the next block
1179         } else {
1180                 // Connect the to_self output claim, taking all of A's non-HTLC funds
1181                 mine_transaction(&nodes[1], &claim_txn[3]);
1182                 to_self_claimed_avail_height = nodes[1].best_block_info().1 + 5;
1183                 largest_htlc_claimed_avail_height = nodes[1].best_block_info().1 + 6; // will be claimed in the next block
1184         }
1185
1186         let largest_htlc_claimed_balance = Balance::ClaimableAwaitingConfirmations {
1187                 claimable_amount_satoshis: 5_000 - chan_feerate * INBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1188                 confirmation_height: largest_htlc_claimed_avail_height,
1189         };
1190         let to_self_claimed_balance = Balance::ClaimableAwaitingConfirmations {
1191                 claimable_amount_satoshis: 1_000_000 - 100_000 - 3_000 - chan_feerate *
1192                         (channel::commitment_tx_base_weight(opt_anchors) + 3 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000
1193                         - chan_feerate * claim_txn[3].weight() as u64 / 1000,
1194                 confirmation_height: to_self_claimed_avail_height,
1195         };
1196
1197         if confirm_htlc_spend_first {
1198                 assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_unclaimed_balance, &largest_htlc_claimed_balance]),
1199                         sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1200         } else {
1201                 assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_claimed_balance, &largest_htlc_unclaimed_balance]),
1202                         sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1203         }
1204
1205         if confirm_htlc_spend_first {
1206                 mine_transaction(&nodes[1], &claim_txn[3]);
1207         } else {
1208                 mine_transaction(&nodes[1], &claim_txn[2]);
1209         }
1210         assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_claimed_balance, &largest_htlc_claimed_balance]),
1211                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1212
1213         // Finally, connect the last two remaining HTLC spends and check that they move to
1214         // `ClaimableAwaitingConfirmations`
1215         mine_transaction(&nodes[1], &claim_txn[0]);
1216         mine_transaction(&nodes[1], &claim_txn[1]);
1217
1218         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1219                         // to_remote output in A's revoked commitment
1220                         claimable_amount_satoshis: 100_000 - 5_000 - 4_000 - 3,
1221                         confirmation_height: nodes[1].best_block_info().1 + 1,
1222                 }, Balance::ClaimableAwaitingConfirmations {
1223                         claimable_amount_satoshis: 1_000_000 - 100_000 - 3_000 - chan_feerate *
1224                                 (channel::commitment_tx_base_weight(opt_anchors) + 3 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000
1225                                 - chan_feerate * claim_txn[3].weight() as u64 / 1000,
1226                         confirmation_height: to_self_claimed_avail_height,
1227                 }, Balance::ClaimableAwaitingConfirmations {
1228                         claimable_amount_satoshis: 3_000 - chan_feerate * OUTBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1229                         confirmation_height: nodes[1].best_block_info().1 + 4,
1230                 }, Balance::ClaimableAwaitingConfirmations {
1231                         claimable_amount_satoshis: 4_000 - chan_feerate * INBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1232                         confirmation_height: nodes[1].best_block_info().1 + 5,
1233                 }, Balance::ClaimableAwaitingConfirmations {
1234                         claimable_amount_satoshis: 5_000 - chan_feerate * INBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1235                         confirmation_height: largest_htlc_claimed_avail_height,
1236                 }]),
1237                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1238
1239         connect_blocks(&nodes[1], 1);
1240         test_spendable_output(&nodes[1], &as_revoked_txn[0]);
1241
1242         let mut payment_failed_events = nodes[1].node.get_and_clear_pending_events();
1243         expect_payment_failed_conditions_event(&nodes[1], payment_failed_events.pop().unwrap(),
1244                 dust_payment_hash, false, PaymentFailedConditions::new());
1245         expect_payment_failed_conditions_event(&nodes[1], payment_failed_events.pop().unwrap(),
1246                 missing_htlc_payment_hash, false, PaymentFailedConditions::new());
1247         assert!(payment_failed_events.is_empty());
1248
1249         connect_blocks(&nodes[1], 1);
1250         test_spendable_output(&nodes[1], &claim_txn[if confirm_htlc_spend_first { 2 } else { 3 }]);
1251         connect_blocks(&nodes[1], 1);
1252         test_spendable_output(&nodes[1], &claim_txn[if confirm_htlc_spend_first { 3 } else { 2 }]);
1253         expect_payment_failed!(nodes[1], live_payment_hash, false);
1254         connect_blocks(&nodes[1], 1);
1255         test_spendable_output(&nodes[1], &claim_txn[0]);
1256         connect_blocks(&nodes[1], 1);
1257         test_spendable_output(&nodes[1], &claim_txn[1]);
1258         expect_payment_failed!(nodes[1], timeout_payment_hash, false);
1259         assert_eq!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances(), Vec::new());
1260
1261         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
1262         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
1263         // monitor events or claimable balances.
1264         connect_blocks(&nodes[1], 6);
1265         connect_blocks(&nodes[1], 6);
1266         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1267         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1268 }
1269
1270 #[test]
1271 fn test_revoked_counterparty_commitment_balances() {
1272         do_test_revoked_counterparty_commitment_balances(true);
1273         do_test_revoked_counterparty_commitment_balances(false);
1274 }
1275
1276 #[test]
1277 fn test_revoked_counterparty_htlc_tx_balances() {
1278         // Tests `get_claimable_balances` for revocation spends of HTLC transactions.
1279         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1280         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
1281         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1282         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1283         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1284
1285         // Create some initial channels
1286         let (_, _, chan_id, funding_tx) =
1287                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 11_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1288         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
1289         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
1290
1291         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
1292         let failed_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 1_000_000).1;
1293         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_id);
1294         assert_eq!(revoked_local_txn[0].input.len(), 1);
1295         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, funding_tx.txid());
1296
1297         // The to-be-revoked commitment tx should have two HTLCs and an output for both sides
1298         assert_eq!(revoked_local_txn[0].output.len(), 4);
1299
1300         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
1301
1302         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
1303         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
1304
1305         // B will generate an HTLC-Success from its revoked commitment tx
1306         mine_transaction(&nodes[1], &revoked_local_txn[0]);
1307         check_closed_broadcast!(nodes[1], true);
1308         check_added_monitors!(nodes[1], 1);
1309         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
1310         let revoked_htlc_success_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1311
1312         assert_eq!(revoked_htlc_success_txn.len(), 2);
1313         assert_eq!(revoked_htlc_success_txn[0].input.len(), 1);
1314         assert_eq!(revoked_htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
1315         check_spends!(revoked_htlc_success_txn[0], revoked_local_txn[0]);
1316         check_spends!(revoked_htlc_success_txn[1], funding_tx);
1317
1318         connect_blocks(&nodes[1], TEST_FINAL_CLTV);
1319         let revoked_htlc_timeout_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1320         assert_eq!(revoked_htlc_timeout_txn.len(), 1);
1321         check_spends!(revoked_htlc_timeout_txn[0], revoked_local_txn[0]);
1322         assert_ne!(revoked_htlc_success_txn[0].input[0].previous_output, revoked_htlc_timeout_txn[0].input[0].previous_output);
1323         assert_eq!(revoked_htlc_success_txn[0].lock_time.0, 0);
1324         assert_ne!(revoked_htlc_timeout_txn[0].lock_time.0, 0);
1325
1326         // A will generate justice tx from B's revoked commitment/HTLC tx
1327         mine_transaction(&nodes[0], &revoked_local_txn[0]);
1328         check_closed_broadcast!(nodes[0], true);
1329         check_added_monitors!(nodes[0], 1);
1330         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1331         let to_remote_conf_height = nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1;
1332
1333         let as_commitment_claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1334         assert_eq!(as_commitment_claim_txn.len(), 2);
1335         check_spends!(as_commitment_claim_txn[0], revoked_local_txn[0]);
1336         check_spends!(as_commitment_claim_txn[1], funding_tx);
1337
1338         // The next two checks have the same balance set for A - even though we confirm a revoked HTLC
1339         // transaction our balance tracking doesn't use the on-chain value so the
1340         // `CounterpartyRevokedOutputClaimable` entry doesn't change.
1341         let as_balances = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1342                         // to_remote output in B's revoked commitment
1343                         claimable_amount_satoshis: 1_000_000 - 11_000 - 3_000 - chan_feerate *
1344                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1345                         confirmation_height: to_remote_conf_height,
1346                 }, Balance::CounterpartyRevokedOutputClaimable {
1347                         // to_self output in B's revoked commitment
1348                         claimable_amount_satoshis: 10_000,
1349                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1350                         claimable_amount_satoshis: 3_000,
1351                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1352                         claimable_amount_satoshis: 1_000,
1353                 }]);
1354         assert_eq!(as_balances,
1355                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1356
1357         mine_transaction(&nodes[0], &revoked_htlc_success_txn[0]);
1358         let as_htlc_claim_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1359         assert_eq!(as_htlc_claim_tx.len(), 2);
1360         check_spends!(as_htlc_claim_tx[0], revoked_htlc_success_txn[0]);
1361         check_spends!(as_htlc_claim_tx[1], revoked_local_txn[0]); // A has to generate a new claim for the remaining revoked
1362                                                                   // outputs (which no longer includes the spent HTLC output)
1363
1364         assert_eq!(as_balances,
1365                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1366
1367         assert_eq!(as_htlc_claim_tx[0].output.len(), 1);
1368         fuzzy_assert_eq(as_htlc_claim_tx[0].output[0].value,
1369                 3_000 - chan_feerate * (revoked_htlc_success_txn[0].weight() + as_htlc_claim_tx[0].weight()) as u64 / 1000);
1370
1371         mine_transaction(&nodes[0], &as_htlc_claim_tx[0]);
1372         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1373                         // to_remote output in B's revoked commitment
1374                         claimable_amount_satoshis: 1_000_000 - 11_000 - 3_000 - chan_feerate *
1375                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1376                         confirmation_height: to_remote_conf_height,
1377                 }, Balance::CounterpartyRevokedOutputClaimable {
1378                         // to_self output in B's revoked commitment
1379                         claimable_amount_satoshis: 10_000,
1380                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1381                         claimable_amount_satoshis: 1_000,
1382                 }, Balance::ClaimableAwaitingConfirmations {
1383                         claimable_amount_satoshis: as_htlc_claim_tx[0].output[0].value,
1384                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
1385                 }]),
1386                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1387
1388         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 3);
1389         test_spendable_output(&nodes[0], &revoked_local_txn[0]);
1390         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1391                         // to_self output to B
1392                         claimable_amount_satoshis: 10_000,
1393                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1394                         claimable_amount_satoshis: 1_000,
1395                 }, Balance::ClaimableAwaitingConfirmations {
1396                         claimable_amount_satoshis: as_htlc_claim_tx[0].output[0].value,
1397                         confirmation_height: nodes[0].best_block_info().1 + 2,
1398                 }]),
1399                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1400
1401         connect_blocks(&nodes[0], 2);
1402         test_spendable_output(&nodes[0], &as_htlc_claim_tx[0]);
1403         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1404                         // to_self output in B's revoked commitment
1405                         claimable_amount_satoshis: 10_000,
1406                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1407                         claimable_amount_satoshis: 1_000,
1408                 }]),
1409                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1410
1411         connect_blocks(&nodes[0], revoked_htlc_timeout_txn[0].lock_time.0 - nodes[0].best_block_info().1);
1412         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(&nodes[0],
1413                 [HTLCDestination::FailedPayment { payment_hash: failed_payment_hash }]);
1414         // As time goes on A may split its revocation claim transaction into multiple.
1415         let as_fewer_input_rbf = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1416         for tx in as_fewer_input_rbf.iter() {
1417                 check_spends!(tx, revoked_local_txn[0]);
1418         }
1419
1420         // Connect a number of additional blocks to ensure we don't forget the HTLC output needs
1421         // claiming.
1422         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
1423         let as_fewer_input_rbf = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1424         for tx in as_fewer_input_rbf.iter() {
1425                 check_spends!(tx, revoked_local_txn[0]);
1426         }
1427
1428         mine_transaction(&nodes[0], &revoked_htlc_timeout_txn[0]);
1429         let as_second_htlc_claim_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1430         assert_eq!(as_second_htlc_claim_tx.len(), 2);
1431
1432         check_spends!(as_second_htlc_claim_tx[0], revoked_htlc_timeout_txn[0]);
1433         check_spends!(as_second_htlc_claim_tx[1], revoked_local_txn[0]);
1434
1435         // Connect blocks to finalize the HTLC resolution with the HTLC-Timeout transaction. In a
1436         // previous iteration of the revoked balance handling this would result in us "forgetting" that
1437         // the revoked HTLC output still needed to be claimed.
1438         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
1439         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1440                         // to_self output in B's revoked commitment
1441                         claimable_amount_satoshis: 10_000,
1442                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1443                         claimable_amount_satoshis: 1_000,
1444                 }]),
1445                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1446
1447         mine_transaction(&nodes[0], &as_second_htlc_claim_tx[0]);
1448         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1449                         // to_self output in B's revoked commitment
1450                         claimable_amount_satoshis: 10_000,
1451                 }, Balance::ClaimableAwaitingConfirmations {
1452                         claimable_amount_satoshis: as_second_htlc_claim_tx[0].output[0].value,
1453                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
1454                 }]),
1455                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1456
1457         mine_transaction(&nodes[0], &as_second_htlc_claim_tx[1]);
1458         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1459                         // to_self output in B's revoked commitment
1460                         claimable_amount_satoshis: as_second_htlc_claim_tx[1].output[0].value,
1461                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
1462                 }, Balance::ClaimableAwaitingConfirmations {
1463                         claimable_amount_satoshis: as_second_htlc_claim_tx[0].output[0].value,
1464                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 2,
1465                 }]),
1466                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1467
1468         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
1469         test_spendable_output(&nodes[0], &as_second_htlc_claim_tx[0]);
1470         connect_blocks(&nodes[0], 1);
1471         test_spendable_output(&nodes[0], &as_second_htlc_claim_tx[1]);
1472
1473         assert_eq!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances(), Vec::new());
1474
1475         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
1476         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
1477         // monitor events or claimable balances.
1478         connect_blocks(&nodes[0], 6);
1479         connect_blocks(&nodes[0], 6);
1480         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1481         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1482 }
1483
1484 #[test]
1485 fn test_revoked_counterparty_aggregated_claims() {
1486         // Tests `get_claimable_balances` for revoked counterparty commitment transactions when
1487         // claiming with an aggregated claim transaction.
1488         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1489         // We broadcast a second-to-latest commitment transaction, without providing the revocation
1490         // secret to the counterparty. However, because we always immediately take the revocation
1491         // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
1492         // transaction which, from the point of view of our keys_manager, is revoked.
1493         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
1494         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1495         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1496         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1497
1498         let (_, _, chan_id, funding_tx) =
1499                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 100_000_000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1500         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
1501         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
1502
1503         // We create two HTLCs, one which we will give A the preimage to to generate an HTLC-Success
1504         // transaction, and one which we will not, allowing B to claim the HTLC output in an aggregated
1505         // revocation-claim transaction.
1506
1507         let (claimed_payment_preimage, claimed_payment_hash, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
1508         let revoked_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 4_000_000).1;
1509
1510         let htlc_cltv_timeout = nodes[1].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1511
1512         // Cheat by giving A's ChannelMonitor the preimage to the to-be-claimed HTLC so that we have an
1513         // HTLC-claim transaction on the to-be-revoked state.
1514         get_monitor!(nodes[0], chan_id).provide_payment_preimage(&claimed_payment_hash, &claimed_payment_preimage,
1515                 &node_cfgs[0].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[0].fee_estimator), &nodes[0].logger);
1516
1517         // Now get the latest commitment transaction from A and then update the fee to revoke it
1518         let as_revoked_txn = get_local_commitment_txn!(nodes[0], chan_id);
1519
1520         assert_eq!(as_revoked_txn.len(), 2);
1521         check_spends!(as_revoked_txn[0], funding_tx);
1522         check_spends!(as_revoked_txn[1], as_revoked_txn[0]); // The HTLC-Claim transaction
1523
1524         let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
1525         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
1526
1527         {
1528                 let mut feerate = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1529                 *feerate += 1;
1530         }
1531         nodes[0].node.timer_tick_occurred();
1532         check_added_monitors!(nodes[0], 1);
1533
1534         let fee_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1535         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &fee_update.update_fee.unwrap());
1536         commitment_signed_dance!(nodes[1], nodes[0], fee_update.commitment_signed, false);
1537
1538         nodes[0].node.claim_funds(claimed_payment_preimage);
1539         expect_payment_claimed!(nodes[0], claimed_payment_hash, 3_000_000);
1540         check_added_monitors!(nodes[0], 1);
1541         let _a_htlc_msgs = get_htlc_update_msgs!(&nodes[0], nodes[1].node.get_our_node_id());
1542
1543         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
1544                         claimable_amount_satoshis: 100_000 - 4_000 - 3_000,
1545                 }, Balance::MaybeTimeoutClaimableHTLC {
1546                         claimable_amount_satoshis: 4_000,
1547                         claimable_height: htlc_cltv_timeout,
1548                 }, Balance::MaybeTimeoutClaimableHTLC {
1549                         claimable_amount_satoshis: 3_000,
1550                         claimable_height: htlc_cltv_timeout,
1551                 }]),
1552                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1553
1554         mine_transaction(&nodes[1], &as_revoked_txn[0]);
1555         check_closed_broadcast!(nodes[1], true);
1556         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
1557         check_added_monitors!(nodes[1], 1);
1558
1559         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();
1560         // Currently the revoked commitment outputs are all claimed in one aggregated transaction
1561         assert_eq!(claim_txn.len(), 1);
1562         assert_eq!(claim_txn[0].input.len(), 3);
1563         check_spends!(claim_txn[0], as_revoked_txn[0]);
1564
1565         let to_remote_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1566
1567         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1568                         // to_remote output in A's revoked commitment
1569                         claimable_amount_satoshis: 100_000 - 4_000 - 3_000,
1570                         confirmation_height: to_remote_maturity,
1571                 }, Balance::CounterpartyRevokedOutputClaimable {
1572                         // to_self output in A's revoked commitment
1573                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1574                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1575                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1576                         claimable_amount_satoshis: 4_000,
1577                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1578                         claimable_amount_satoshis: 3_000,
1579                 }]),
1580                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1581
1582         // Confirm A's HTLC-Success tranasction which presumably raced B's claim, causing B to create a
1583         // new claim.
1584         mine_transaction(&nodes[1], &as_revoked_txn[1]);
1585         expect_payment_sent!(nodes[1], claimed_payment_preimage);
1586         let mut claim_txn_2: Vec<_> = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1587         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 });
1588         // Once B sees the HTLC-Success transaction it splits its claim transaction into two, though in
1589         // theory it could re-aggregate the claims as well.
1590         assert_eq!(claim_txn_2.len(), 2);
1591         assert_eq!(claim_txn_2[0].input.len(), 2);
1592         check_spends!(claim_txn_2[0], as_revoked_txn[0]);
1593         assert_eq!(claim_txn_2[1].input.len(), 1);
1594         check_spends!(claim_txn_2[1], as_revoked_txn[1]);
1595
1596         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1597                         // to_remote output in A's revoked commitment
1598                         claimable_amount_satoshis: 100_000 - 4_000 - 3_000,
1599                         confirmation_height: to_remote_maturity,
1600                 }, Balance::CounterpartyRevokedOutputClaimable {
1601                         // to_self output in A's revoked commitment
1602                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1603                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1604                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1605                         claimable_amount_satoshis: 4_000,
1606                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1607                         // The amount here is a bit of a misnomer, really its been reduced by the HTLC
1608                         // transaction fee, but the claimable amount is always a bit of an overshoot for HTLCs
1609                         // anyway, so its not a big change.
1610                         claimable_amount_satoshis: 3_000,
1611                 }]),
1612                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1613
1614         connect_blocks(&nodes[1], 5);
1615         test_spendable_output(&nodes[1], &as_revoked_txn[0]);
1616
1617         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1618                         // to_self output in A's revoked commitment
1619                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1620                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1621                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1622                         claimable_amount_satoshis: 4_000,
1623                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1624                         // The amount here is a bit of a misnomer, really its been reduced by the HTLC
1625                         // transaction fee, but the claimable amount is always a bit of an overshoot for HTLCs
1626                         // anyway, so its not a big change.
1627                         claimable_amount_satoshis: 3_000,
1628                 }]),
1629                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1630
1631         mine_transaction(&nodes[1], &claim_txn_2[1]);
1632         let htlc_2_claim_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1633
1634         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1635                         // to_self output in A's revoked commitment
1636                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1637                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1638                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1639                         claimable_amount_satoshis: 4_000,
1640                 }, Balance::ClaimableAwaitingConfirmations { // HTLC 2
1641                         claimable_amount_satoshis: claim_txn_2[1].output[0].value,
1642                         confirmation_height: htlc_2_claim_maturity,
1643                 }]),
1644                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1645
1646         connect_blocks(&nodes[1], 5);
1647         test_spendable_output(&nodes[1], &claim_txn_2[1]);
1648
1649         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1650                         // to_self output in A's revoked commitment
1651                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1652                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1653                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1654                         claimable_amount_satoshis: 4_000,
1655                 }]),
1656                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1657
1658         mine_transaction(&nodes[1], &claim_txn_2[0]);
1659         let rest_claim_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1660
1661         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
1662                         claimable_amount_satoshis: claim_txn_2[0].output[0].value,
1663                         confirmation_height: rest_claim_maturity,
1664                 }],
1665                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
1666
1667         assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); // We shouldn't fail the payment until we spend the output
1668
1669         connect_blocks(&nodes[1], 5);
1670         expect_payment_failed!(nodes[1], revoked_payment_hash, false);
1671         test_spendable_output(&nodes[1], &claim_txn_2[0]);
1672         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1673
1674         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
1675         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
1676         // monitor events or claimable balances.
1677         connect_blocks(&nodes[1], 6);
1678         connect_blocks(&nodes[1], 6);
1679         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1680         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1681 }