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