]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/monitor_tests.rs
Add payment preimage and hash to `ContentiousClaimable`
[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 #[cfg(anchors)]
13 use crate::chain::keysinterface::{ChannelSigner, EcdsaChannelSigner};
14 #[cfg(anchors)]
15 use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS;
16 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, Balance};
17 use crate::chain::transaction::OutPoint;
18 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
19 #[cfg(anchors)]
20 use crate::events::bump_transaction::BumpTransactionEvent;
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
22 use crate::ln::channel;
23 #[cfg(anchors)]
24 use crate::ln::chan_utils;
25 #[cfg(anchors)]
26 use crate::ln::channelmanager::ChannelManager;
27 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, PaymentId, RecipientOnionFields};
28 use crate::ln::msgs::ChannelMessageHandler;
29 #[cfg(anchors)]
30 use crate::util::config::UserConfig;
31 #[cfg(anchors)]
32 use crate::util::crypto::sign;
33 use crate::util::ser::Writeable;
34 use crate::util::test_utils;
35
36 #[cfg(anchors)]
37 use bitcoin::blockdata::transaction::EcdsaSighashType;
38 use bitcoin::blockdata::script::Builder;
39 use bitcoin::blockdata::opcodes;
40 use bitcoin::secp256k1::Secp256k1;
41 #[cfg(anchors)]
42 use bitcoin::secp256k1::SecretKey;
43 #[cfg(anchors)]
44 use bitcoin::{Amount, PublicKey, Script, TxIn, TxOut, PackedLockTime, Witness};
45 use bitcoin::Transaction;
46 #[cfg(anchors)]
47 use bitcoin::util::sighash::SighashCache;
48
49 use crate::prelude::*;
50
51 use crate::ln::functional_test_utils::*;
52
53 #[test]
54 fn chanmon_fail_from_stale_commitment() {
55         // If we forward an HTLC to our counterparty, but we force-closed the channel before our
56         // counterparty provides us an updated commitment transaction, we'll end up with a commitment
57         // transaction that does not contain the HTLC which we attempted to forward. In this case, we
58         // need to wait `ANTI_REORG_DELAY` blocks and then fail back the HTLC as there is no way for us
59         // to learn the preimage and the confirmed commitment transaction paid us the value of the
60         // HTLC.
61         //
62         // However, previously, we did not do this, ignoring the HTLC entirely.
63         //
64         // This could lead to channel closure if the sender we received the HTLC from decides to go on
65         // chain to get their HTLC back before it times out.
66         //
67         // Here, we check exactly this case, forwarding a payment from A, through B, to C, before B
68         // broadcasts its latest commitment transaction, which should result in it eventually failing
69         // the HTLC back off-chain to A.
70         let chanmon_cfgs = create_chanmon_cfgs(3);
71         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
72         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
73         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
74
75         create_announced_chan_between_nodes(&nodes, 0, 1);
76         let (update_a, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
77
78         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
79         nodes[0].node.send_payment_with_route(&route, payment_hash,
80                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
81         check_added_monitors!(nodes[0], 1);
82
83         let bs_txn = get_local_commitment_txn!(nodes[1], chan_id_2);
84
85         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
86         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
87         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
88
89         expect_pending_htlcs_forwardable!(nodes[1]);
90         get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
91         check_added_monitors!(nodes[1], 1);
92
93         // Don't bother delivering the new HTLC add/commits, instead confirming the pre-HTLC commitment
94         // transaction for nodes[1].
95         mine_transaction(&nodes[1], &bs_txn[0]);
96         check_added_monitors!(nodes[1], 1);
97         check_closed_broadcast!(nodes[1], true);
98         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
99         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
100
101         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
102         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 }]);
103         check_added_monitors!(nodes[1], 1);
104         let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
105
106         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
107         commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, true, true);
108         expect_payment_failed_with_update!(nodes[0], payment_hash, false, update_a.contents.short_channel_id, true);
109 }
110
111 fn test_spendable_output<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, spendable_tx: &Transaction) {
112         let mut spendable = node.chain_monitor.chain_monitor.get_and_clear_pending_events();
113         assert_eq!(spendable.len(), 1);
114         if let Event::SpendableOutputs { outputs } = spendable.pop().unwrap() {
115                 assert_eq!(outputs.len(), 1);
116                 let spend_tx = node.keys_manager.backing.spend_spendable_outputs(&[&outputs[0]], Vec::new(),
117                         Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &Secp256k1::new()).unwrap();
118                 check_spends!(spend_tx, spendable_tx);
119         } else { panic!(); }
120 }
121
122 #[test]
123 fn revoked_output_htlc_resolution_timing() {
124         // Tests that HTLCs which were present in a broadcasted remote revoked commitment transaction
125         // are resolved only after a spend of the HTLC output reaches six confirmations. Preivously
126         // they would resolve after the revoked commitment transaction itself reaches six
127         // confirmations.
128         let chanmon_cfgs = create_chanmon_cfgs(2);
129         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
130         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
131         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
132
133         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
134
135         let payment_hash_1 = route_payment(&nodes[1], &[&nodes[0]], 1_000_000).1;
136
137         // Get a commitment transaction which contains the HTLC we care about, but which we'll revoke
138         // before forwarding.
139         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
140         assert_eq!(revoked_local_txn.len(), 1);
141
142         // Route a dust payment to revoke the above commitment transaction
143         route_payment(&nodes[0], &[&nodes[1]], 1_000);
144
145         // Confirm the revoked commitment transaction, closing the channel.
146         mine_transaction(&nodes[1], &revoked_local_txn[0]);
147         check_added_monitors!(nodes[1], 1);
148         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
149         check_closed_broadcast!(nodes[1], true);
150
151         let bs_spend_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
152         assert_eq!(bs_spend_txn.len(), 1);
153         check_spends!(bs_spend_txn[0], revoked_local_txn[0]);
154
155         // After the commitment transaction confirms, we should still wait on the HTLC spend
156         // transaction to confirm before resolving the HTLC.
157         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
158         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
159         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
160
161         // Spend the HTLC output, generating a HTLC failure event after ANTI_REORG_DELAY confirmations.
162         mine_transaction(&nodes[1], &bs_spend_txn[0]);
163         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
164         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
165
166         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
167         expect_payment_failed!(nodes[1], payment_hash_1, false);
168 }
169
170 #[test]
171 fn chanmon_claim_value_coop_close() {
172         // Tests `get_claimable_balances` returns the correct values across a simple cooperative claim.
173         // Specifically, this tests that the channel non-HTLC balances show up in
174         // `get_claimable_balances` until the cooperative claims have confirmed and generated a
175         // `SpendableOutputs` event, and no longer.
176         let chanmon_cfgs = create_chanmon_cfgs(2);
177         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
178         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
179         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
180
181         let (_, _, chan_id, funding_tx) =
182                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000);
183         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
184         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
185
186         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
187         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_id);
188
189         assert_eq!(vec![Balance::ClaimableOnChannelClose {
190                         claimable_amount_satoshis: 1_000_000 - 1_000 - chan_feerate * channel::commitment_tx_base_weight(opt_anchors) / 1000
191                 }],
192                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
193         assert_eq!(vec![Balance::ClaimableOnChannelClose { claimable_amount_satoshis: 1_000, }],
194                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
195
196         nodes[0].node.close_channel(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
197         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
198         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
199         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
200         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
201
202         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
203         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
204         let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
205         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
206         let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
207         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
208         let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
209         assert!(node_1_none.is_none());
210
211         let shutdown_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
212         assert_eq!(shutdown_tx, nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0));
213         assert_eq!(shutdown_tx.len(), 1);
214
215         mine_transaction(&nodes[0], &shutdown_tx[0]);
216         mine_transaction(&nodes[1], &shutdown_tx[0]);
217
218         assert!(nodes[0].node.list_channels().is_empty());
219         assert!(nodes[1].node.list_channels().is_empty());
220
221         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
222         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
223
224         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
225                         claimable_amount_satoshis: 1_000_000 - 1_000 - chan_feerate * channel::commitment_tx_base_weight(opt_anchors) / 1000,
226                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
227                 }],
228                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
229         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
230                         claimable_amount_satoshis: 1000,
231                         confirmation_height: nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1,
232                 }],
233                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
234
235         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
236         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
237
238         assert_eq!(Vec::<Balance>::new(),
239                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
240         assert_eq!(Vec::<Balance>::new(),
241                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
242
243         test_spendable_output(&nodes[0], &shutdown_tx[0]);
244         test_spendable_output(&nodes[1], &shutdown_tx[0]);
245
246         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
247         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
248 }
249
250 fn sorted_vec<T: Ord>(mut v: Vec<T>) -> Vec<T> {
251         v.sort_unstable();
252         v
253 }
254
255 /// Asserts that `a` and `b` are close, but maybe off by up to 5.
256 /// This is useful when checking fees and weights on transactions as things may vary by a few based
257 /// on signature size and signature size estimation being non-exact.
258 fn fuzzy_assert_eq<V: core::convert::TryInto<u64>>(a: V, b: V) {
259         let a_u64 = a.try_into().map_err(|_| ()).unwrap();
260         let b_u64 = b.try_into().map_err(|_| ()).unwrap();
261         eprintln!("Checking {} and {} for fuzzy equality", a_u64, b_u64);
262         assert!(a_u64 >= b_u64 - 5);
263         assert!(b_u64 >= a_u64 - 5);
264 }
265
266 fn do_test_claim_value_force_close(prev_commitment_tx: bool) {
267         // Tests `get_claimable_balances` with an HTLC across a force-close.
268         // We build a channel with an HTLC pending, then force close the channel and check that the
269         // `get_claimable_balances` return value is correct as transactions confirm on-chain.
270         let mut chanmon_cfgs = create_chanmon_cfgs(2);
271         if prev_commitment_tx {
272                 // We broadcast a second-to-latest commitment transaction, without providing the revocation
273                 // secret to the counterparty. However, because we always immediately take the revocation
274                 // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
275                 // transaction which, from the point of view of our keys_manager, is revoked.
276                 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
277         }
278         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
279         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
280         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
281
282         let (_, _, chan_id, funding_tx) =
283                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000);
284         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
285         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
286
287         // This HTLC is immediately claimed, giving node B the preimage
288         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
289         // This HTLC is allowed to time out, letting A claim it. However, in order to test claimable
290         // balances more fully we also give B the preimage for this HTLC.
291         let (timeout_payment_preimage, timeout_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 4_000_000);
292         // This HTLC will be dust, and not be claimable at all:
293         let (dust_payment_preimage, dust_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000);
294
295         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
296
297         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
298         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_id);
299
300         let remote_txn = get_local_commitment_txn!(nodes[1], chan_id);
301         let sent_htlc_balance = Balance::MaybeTimeoutClaimableHTLC {
302                 claimable_amount_satoshis: 3_000,
303                 claimable_height: htlc_cltv_timeout,
304         };
305         let sent_htlc_timeout_balance = Balance::MaybeTimeoutClaimableHTLC {
306                 claimable_amount_satoshis: 4_000,
307                 claimable_height: htlc_cltv_timeout,
308         };
309         let received_htlc_balance = Balance::MaybePreimageClaimableHTLC {
310                 claimable_amount_satoshis: 3_000,
311                 expiry_height: htlc_cltv_timeout,
312         };
313         let received_htlc_timeout_balance = Balance::MaybePreimageClaimableHTLC {
314                 claimable_amount_satoshis: 4_000,
315                 expiry_height: htlc_cltv_timeout,
316         };
317         let received_htlc_claiming_balance = Balance::ContentiousClaimable {
318                 claimable_amount_satoshis: 3_000,
319                 timeout_height: htlc_cltv_timeout,
320                 payment_hash,
321                 payment_preimage,
322         };
323         let received_htlc_timeout_claiming_balance = Balance::ContentiousClaimable {
324                 claimable_amount_satoshis: 4_000,
325                 timeout_height: htlc_cltv_timeout,
326                 payment_hash: timeout_payment_hash,
327                 payment_preimage: timeout_payment_preimage,
328         };
329
330         // Before B receives the payment preimage, it only suggests the push_msat value of 1_000 sats
331         // as claimable. A lists both its to-self balance and the (possibly-claimable) HTLCs.
332         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
333                         claimable_amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - chan_feerate *
334                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
335                 }, sent_htlc_balance.clone(), sent_htlc_timeout_balance.clone()]),
336                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
337         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
338                         claimable_amount_satoshis: 1_000,
339                 }, received_htlc_balance.clone(), received_htlc_timeout_balance.clone()]),
340                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
341
342         nodes[1].node.claim_funds(payment_preimage);
343         check_added_monitors!(nodes[1], 1);
344         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
345
346         let b_htlc_msgs = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
347         // We claim the dust payment here as well, but it won't impact our claimable balances as its
348         // dust and thus doesn't appear on chain at all.
349         nodes[1].node.claim_funds(dust_payment_preimage);
350         check_added_monitors!(nodes[1], 1);
351         expect_payment_claimed!(nodes[1], dust_payment_hash, 3_000);
352
353         nodes[1].node.claim_funds(timeout_payment_preimage);
354         check_added_monitors!(nodes[1], 1);
355         expect_payment_claimed!(nodes[1], timeout_payment_hash, 4_000_000);
356
357         if prev_commitment_tx {
358                 // To build a previous commitment transaction, deliver one round of commitment messages.
359                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.update_fulfill_htlcs[0]);
360                 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
361                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.commitment_signed);
362                 check_added_monitors!(nodes[0], 1);
363                 let (as_raa, as_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
364                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
365                 let _htlc_updates = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
366                 check_added_monitors!(nodes[1], 1);
367                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs);
368                 let _bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
369                 check_added_monitors!(nodes[1], 1);
370         }
371
372         // Once B has received the payment preimage, it includes the value of the HTLC in its
373         // "claimable if you were to close the channel" balance.
374         let mut a_expected_balances = vec![Balance::ClaimableOnChannelClose {
375                         claimable_amount_satoshis: 1_000_000 - // Channel funding value in satoshis
376                                 4_000 - // The to-be-failed HTLC value in satoshis
377                                 3_000 - // The claimed HTLC value in satoshis
378                                 1_000 - // The push_msat value in satoshis
379                                 3 - // The dust HTLC value in satoshis
380                                 // The commitment transaction fee with two HTLC outputs:
381                                 chan_feerate * (channel::commitment_tx_base_weight(opt_anchors) +
382                                                                 if prev_commitment_tx { 1 } else { 2 } *
383                                                                 channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
384                 }, sent_htlc_timeout_balance.clone()];
385         if !prev_commitment_tx {
386                 a_expected_balances.push(sent_htlc_balance.clone());
387         }
388         assert_eq!(sorted_vec(a_expected_balances),
389                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
390         assert_eq!(vec![Balance::ClaimableOnChannelClose {
391                         claimable_amount_satoshis: 1_000 + 3_000 + 4_000,
392                 }],
393                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
394
395         // Broadcast the closing transaction (which has both pending HTLCs in it) and get B's
396         // broadcasted HTLC claim transaction with preimage.
397         let node_b_commitment_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
398         mine_transaction(&nodes[0], &remote_txn[0]);
399         mine_transaction(&nodes[1], &remote_txn[0]);
400
401         let b_broadcast_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
402         assert_eq!(b_broadcast_txn.len(), 2);
403         // b_broadcast_txn should spend the HTLCs output of the commitment tx for 3_000 and 4_000 sats
404         check_spends!(b_broadcast_txn[0], remote_txn[0]);
405         check_spends!(b_broadcast_txn[1], remote_txn[0]);
406         assert_eq!(b_broadcast_txn[0].input.len(), 1);
407         assert_eq!(b_broadcast_txn[1].input.len(), 1);
408         assert_eq!(remote_txn[0].output[b_broadcast_txn[0].input[0].previous_output.vout as usize].value, 3_000);
409         assert_eq!(remote_txn[0].output[b_broadcast_txn[1].input[0].previous_output.vout as usize].value, 4_000);
410
411         assert!(nodes[0].node.list_channels().is_empty());
412         check_closed_broadcast!(nodes[0], true);
413         check_added_monitors!(nodes[0], 1);
414         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
415         assert!(nodes[1].node.list_channels().is_empty());
416         check_closed_broadcast!(nodes[1], true);
417         check_added_monitors!(nodes[1], 1);
418         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
419         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
420         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
421
422         // Once the commitment transaction confirms, we will wait until ANTI_REORG_DELAY until we
423         // generate any `SpendableOutputs` events. Thus, the same balances will still be listed
424         // available in `get_claimable_balances`. However, both will swap from `ClaimableOnClose` to
425         // other Balance variants, as close has already happened.
426         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
427         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
428
429         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
430                         claimable_amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - chan_feerate *
431                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
432                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
433                 }, sent_htlc_balance.clone(), sent_htlc_timeout_balance.clone()]),
434                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
435         // The main non-HTLC balance is just awaiting confirmations, but the claimable height is the
436         // CSV delay, not ANTI_REORG_DELAY.
437         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
438                         claimable_amount_satoshis: 1_000,
439                         confirmation_height: node_b_commitment_claimable,
440                 },
441                 // Both HTLC balances are "contentious" as our counterparty could claim them if we wait too
442                 // long.
443                 received_htlc_claiming_balance.clone(), received_htlc_timeout_claiming_balance.clone()]),
444                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
445
446         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
447         expect_payment_failed!(nodes[0], dust_payment_hash, false);
448         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
449
450         // After ANTI_REORG_DELAY, A will consider its balance fully spendable and generate a
451         // `SpendableOutputs` event. However, B still has to wait for the CSV delay.
452         assert_eq!(sorted_vec(vec![sent_htlc_balance.clone(), sent_htlc_timeout_balance.clone()]),
453                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
454         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
455                         claimable_amount_satoshis: 1_000,
456                         confirmation_height: node_b_commitment_claimable,
457                 }, received_htlc_claiming_balance.clone(), received_htlc_timeout_claiming_balance.clone()]),
458                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
459
460         test_spendable_output(&nodes[0], &remote_txn[0]);
461         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
462
463         // After broadcasting the HTLC claim transaction, node A will still consider the HTLC
464         // possibly-claimable up to ANTI_REORG_DELAY, at which point it will drop it.
465         mine_transaction(&nodes[0], &b_broadcast_txn[0]);
466         if prev_commitment_tx {
467                 expect_payment_path_successful!(nodes[0]);
468         } else {
469                 expect_payment_sent!(nodes[0], payment_preimage);
470         }
471         assert_eq!(sorted_vec(vec![sent_htlc_balance.clone(), sent_htlc_timeout_balance.clone()]),
472                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
473         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
474         assert_eq!(vec![sent_htlc_timeout_balance.clone()],
475                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
476
477         // When the HTLC timeout output is spendable in the next block, A should broadcast it
478         connect_blocks(&nodes[0], htlc_cltv_timeout - nodes[0].best_block_info().1 - 1);
479         let a_broadcast_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
480         assert_eq!(a_broadcast_txn.len(), 2);
481         assert_eq!(a_broadcast_txn[0].input.len(), 1);
482         check_spends!(a_broadcast_txn[0], remote_txn[0]);
483         assert_eq!(a_broadcast_txn[1].input.len(), 1);
484         check_spends!(a_broadcast_txn[1], remote_txn[0]);
485         assert_ne!(a_broadcast_txn[0].input[0].previous_output.vout,
486                    a_broadcast_txn[1].input[0].previous_output.vout);
487         // a_broadcast_txn [0] and [1] should spend the HTLC outputs of the commitment tx
488         assert_eq!(remote_txn[0].output[a_broadcast_txn[0].input[0].previous_output.vout as usize].value, 3_000);
489         assert_eq!(remote_txn[0].output[a_broadcast_txn[1].input[0].previous_output.vout as usize].value, 4_000);
490
491         // Once the HTLC-Timeout transaction confirms, A will no longer consider the HTLC
492         // "MaybeClaimable", but instead move it to "AwaitingConfirmations".
493         mine_transaction(&nodes[0], &a_broadcast_txn[1]);
494         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
495         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
496                         claimable_amount_satoshis: 4_000,
497                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
498                 }],
499                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
500         // After ANTI_REORG_DELAY, A will generate a SpendableOutputs event and drop the claimable
501         // balance entry.
502         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
503         assert_eq!(Vec::<Balance>::new(),
504                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
505         expect_payment_failed!(nodes[0], timeout_payment_hash, false);
506
507         test_spendable_output(&nodes[0], &a_broadcast_txn[1]);
508
509         // Node B will no longer consider the HTLC "contentious" after the HTLC claim transaction
510         // confirms, and consider it simply "awaiting confirmations". Note that it has to wait for the
511         // standard revocable transaction CSV delay before receiving a `SpendableOutputs`.
512         let node_b_htlc_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
513         mine_transaction(&nodes[1], &b_broadcast_txn[0]);
514
515         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
516                         claimable_amount_satoshis: 1_000,
517                         confirmation_height: node_b_commitment_claimable,
518                 }, Balance::ClaimableAwaitingConfirmations {
519                         claimable_amount_satoshis: 3_000,
520                         confirmation_height: node_b_htlc_claimable,
521                 }, received_htlc_timeout_claiming_balance.clone()]),
522                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
523
524         // After reaching the commitment output CSV, we'll get a SpendableOutputs event for it and have
525         // only the HTLCs claimable on node B.
526         connect_blocks(&nodes[1], node_b_commitment_claimable - nodes[1].best_block_info().1);
527         test_spendable_output(&nodes[1], &remote_txn[0]);
528
529         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
530                         claimable_amount_satoshis: 3_000,
531                         confirmation_height: node_b_htlc_claimable,
532                 }, received_htlc_timeout_claiming_balance.clone()]),
533                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
534
535         // After reaching the claimed HTLC output CSV, we'll get a SpendableOutptus event for it and
536         // have only one HTLC output left spendable.
537         connect_blocks(&nodes[1], node_b_htlc_claimable - nodes[1].best_block_info().1);
538         test_spendable_output(&nodes[1], &b_broadcast_txn[0]);
539
540         assert_eq!(vec![received_htlc_timeout_claiming_balance.clone()],
541                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
542
543         // Finally, mine the HTLC timeout transaction that A broadcasted (even though B should be able
544         // to claim this HTLC with the preimage it knows!). It will remain listed as a claimable HTLC
545         // until ANTI_REORG_DELAY confirmations on the spend.
546         mine_transaction(&nodes[1], &a_broadcast_txn[1]);
547         assert_eq!(vec![received_htlc_timeout_claiming_balance.clone()],
548                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
549         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
550         assert_eq!(Vec::<Balance>::new(),
551                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
552
553         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
554         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
555         // monitor events or claimable balances.
556         for node in nodes.iter() {
557                 connect_blocks(node, 6);
558                 connect_blocks(node, 6);
559                 assert!(node.chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
560                 assert!(node.chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
561         }
562 }
563
564 #[test]
565 fn test_claim_value_force_close() {
566         do_test_claim_value_force_close(true);
567         do_test_claim_value_force_close(false);
568 }
569
570 #[test]
571 fn test_balances_on_local_commitment_htlcs() {
572         // Previously, when handling the broadcast of a local commitment transactions (with associated
573         // CSV delays prior to spendability), we incorrectly handled the CSV delays on HTLC
574         // transactions. This caused us to miss spendable outputs for HTLCs which were awaiting a CSV
575         // delay prior to spendability.
576         //
577         // Further, because of this, we could hit an assertion as `get_claimable_balances` asserted
578         // that HTLCs were resolved after the funding spend was resolved, which was not true if the
579         // HTLC did not have a CSV delay attached (due to the above bug or due to it being an HTLC
580         // claim by our counterparty).
581         let chanmon_cfgs = create_chanmon_cfgs(2);
582         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
583         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
584         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
585
586         // Create a single channel with two pending HTLCs from nodes[0] to nodes[1], one which nodes[1]
587         // knows the preimage for, one which it does not.
588         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
589         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
590
591         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000_000);
592         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
593         nodes[0].node.send_payment_with_route(&route, payment_hash,
594                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
595         check_added_monitors!(nodes[0], 1);
596
597         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
598         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
599         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
600
601         expect_pending_htlcs_forwardable!(nodes[1]);
602         expect_payment_claimable!(nodes[1], payment_hash, payment_secret, 10_000_000);
603
604         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 20_000_000);
605         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
606                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
607         check_added_monitors!(nodes[0], 1);
608
609         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
610         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
611         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
612
613         expect_pending_htlcs_forwardable!(nodes[1]);
614         expect_payment_claimable!(nodes[1], payment_hash_2, payment_secret_2, 20_000_000);
615         nodes[1].node.claim_funds(payment_preimage_2);
616         get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
617         check_added_monitors!(nodes[1], 1);
618         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000_000);
619
620         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
621         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_id);
622
623         // Get nodes[0]'s commitment transaction and HTLC-Timeout transactions
624         let as_txn = get_local_commitment_txn!(nodes[0], chan_id);
625         assert_eq!(as_txn.len(), 3);
626         check_spends!(as_txn[1], as_txn[0]);
627         check_spends!(as_txn[2], as_txn[0]);
628         check_spends!(as_txn[0], funding_tx);
629
630         // First confirm the commitment transaction on nodes[0], which should leave us with three
631         // claimable balances.
632         let node_a_commitment_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
633         mine_transaction(&nodes[0], &as_txn[0]);
634         check_added_monitors!(nodes[0], 1);
635         check_closed_broadcast!(nodes[0], true);
636         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
637
638         let htlc_balance_known_preimage = Balance::MaybeTimeoutClaimableHTLC {
639                 claimable_amount_satoshis: 10_000,
640                 claimable_height: htlc_cltv_timeout,
641         };
642         let htlc_balance_unknown_preimage = Balance::MaybeTimeoutClaimableHTLC {
643                 claimable_amount_satoshis: 20_000,
644                 claimable_height: htlc_cltv_timeout,
645         };
646
647         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
648                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
649                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
650                         confirmation_height: node_a_commitment_claimable,
651                 }, htlc_balance_known_preimage.clone(), htlc_balance_unknown_preimage.clone()]),
652                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
653
654         // Get nodes[1]'s HTLC claim tx for the second HTLC
655         mine_transaction(&nodes[1], &as_txn[0]);
656         check_added_monitors!(nodes[1], 1);
657         check_closed_broadcast!(nodes[1], true);
658         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
659         let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
660         assert_eq!(bs_htlc_claim_txn.len(), 1);
661         check_spends!(bs_htlc_claim_txn[0], as_txn[0]);
662
663         // Connect blocks until the HTLCs expire, allowing us to (validly) broadcast the HTLC-Timeout
664         // transaction.
665         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
666         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
667                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
668                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
669                         confirmation_height: node_a_commitment_claimable,
670                 }, htlc_balance_known_preimage.clone(), htlc_balance_unknown_preimage.clone()]),
671                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
672         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
673
674         // Now confirm nodes[0]'s HTLC-Timeout transaction, which changes the claimable balance to an
675         // "awaiting confirmations" one.
676         let node_a_htlc_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
677         mine_transaction(&nodes[0], &as_txn[1]);
678         // Note that prior to the fix in the commit which introduced this test, this (and the next
679         // balance) check failed. With this check removed, the code panicked in the `connect_blocks`
680         // call, as described, two hunks down.
681         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
682                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
683                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
684                         confirmation_height: node_a_commitment_claimable,
685                 }, Balance::ClaimableAwaitingConfirmations {
686                         claimable_amount_satoshis: 10_000,
687                         confirmation_height: node_a_htlc_claimable,
688                 }, htlc_balance_unknown_preimage.clone()]),
689                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
690
691         // Now confirm nodes[1]'s HTLC claim, giving nodes[0] the preimage. Note that the "maybe
692         // claimable" balance remains until we see ANTI_REORG_DELAY blocks.
693         mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
694         expect_payment_sent!(nodes[0], payment_preimage_2);
695         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
696                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
697                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
698                         confirmation_height: node_a_commitment_claimable,
699                 }, Balance::ClaimableAwaitingConfirmations {
700                         claimable_amount_satoshis: 10_000,
701                         confirmation_height: node_a_htlc_claimable,
702                 }, htlc_balance_unknown_preimage.clone()]),
703                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
704
705         // Finally make the HTLC transactions have ANTI_REORG_DELAY blocks. This call previously
706         // panicked as described in the test introduction. This will remove the "maybe claimable"
707         // spendable output as nodes[1] has fully claimed the second HTLC.
708         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
709         expect_payment_failed!(nodes[0], payment_hash, false);
710
711         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
712                         claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
713                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
714                         confirmation_height: node_a_commitment_claimable,
715                 }, Balance::ClaimableAwaitingConfirmations {
716                         claimable_amount_satoshis: 10_000,
717                         confirmation_height: node_a_htlc_claimable,
718                 }]),
719                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
720
721         // Connect blocks until the commitment transaction's CSV expires, providing us the relevant
722         // `SpendableOutputs` event and removing the claimable balance entry.
723         connect_blocks(&nodes[0], node_a_commitment_claimable - nodes[0].best_block_info().1);
724         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
725                         claimable_amount_satoshis: 10_000,
726                         confirmation_height: node_a_htlc_claimable,
727                 }],
728                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
729         test_spendable_output(&nodes[0], &as_txn[0]);
730
731         // Connect blocks until the HTLC-Timeout's CSV expires, providing us the relevant
732         // `SpendableOutputs` event and removing the claimable balance entry.
733         connect_blocks(&nodes[0], node_a_htlc_claimable - nodes[0].best_block_info().1);
734         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
735         test_spendable_output(&nodes[0], &as_txn[1]);
736
737         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
738         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
739         // monitor events or claimable balances.
740         connect_blocks(&nodes[0], 6);
741         connect_blocks(&nodes[0], 6);
742         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
743         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
744 }
745
746 #[test]
747 fn test_no_preimage_inbound_htlc_balances() {
748         // Tests that MaybePreimageClaimableHTLC are generated for inbound HTLCs for which we do not
749         // have a preimage.
750         let chanmon_cfgs = create_chanmon_cfgs(2);
751         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
752         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
753         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
754
755         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
756         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
757
758         // Send two HTLCs, one from A to B, and one from B to A.
759         let to_b_failed_payment_hash = route_payment(&nodes[0], &[&nodes[1]], 10_000_000).1;
760         let to_a_failed_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 20_000_000).1;
761         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
762
763         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
764         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_id);
765
766         let a_sent_htlc_balance = Balance::MaybeTimeoutClaimableHTLC {
767                 claimable_amount_satoshis: 10_000,
768                 claimable_height: htlc_cltv_timeout,
769         };
770         let a_received_htlc_balance = Balance::MaybePreimageClaimableHTLC {
771                 claimable_amount_satoshis: 20_000,
772                 expiry_height: htlc_cltv_timeout,
773         };
774         let b_received_htlc_balance = Balance::MaybePreimageClaimableHTLC {
775                 claimable_amount_satoshis: 10_000,
776                 expiry_height: htlc_cltv_timeout,
777         };
778         let b_sent_htlc_balance = Balance::MaybeTimeoutClaimableHTLC {
779                 claimable_amount_satoshis: 20_000,
780                 claimable_height: htlc_cltv_timeout,
781         };
782
783         // Both A and B will have an HTLC that's claimable on timeout and one that's claimable if they
784         // receive the preimage. These will remain the same through the channel closure and until the
785         // HTLC output is spent.
786
787         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
788                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
789                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
790                 }, a_received_htlc_balance.clone(), a_sent_htlc_balance.clone()]),
791                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
792
793         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
794                         claimable_amount_satoshis: 500_000 - 20_000,
795                 }, b_received_htlc_balance.clone(), b_sent_htlc_balance.clone()]),
796                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
797
798         // Get nodes[0]'s commitment transaction and HTLC-Timeout transaction
799         let as_txn = get_local_commitment_txn!(nodes[0], chan_id);
800         assert_eq!(as_txn.len(), 2);
801         check_spends!(as_txn[1], as_txn[0]);
802         check_spends!(as_txn[0], funding_tx);
803
804         // Now close the channel by confirming A's commitment transaction on both nodes, checking the
805         // claimable balances remain the same except for the non-HTLC balance changing variant.
806         let node_a_commitment_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
807         let as_pre_spend_claims = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
808                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
809                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
810                         confirmation_height: node_a_commitment_claimable,
811                 }, a_received_htlc_balance.clone(), a_sent_htlc_balance.clone()]);
812
813         mine_transaction(&nodes[0], &as_txn[0]);
814         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
815         check_added_monitors!(nodes[0], 1);
816         check_closed_broadcast!(nodes[0], true);
817         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
818
819         assert_eq!(as_pre_spend_claims,
820                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
821
822         mine_transaction(&nodes[1], &as_txn[0]);
823         check_added_monitors!(nodes[1], 1);
824         check_closed_broadcast!(nodes[1], true);
825         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
826
827         let node_b_commitment_claimable = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
828         let mut bs_pre_spend_claims = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
829                         claimable_amount_satoshis: 500_000 - 20_000,
830                         confirmation_height: node_b_commitment_claimable,
831                 }, b_received_htlc_balance.clone(), b_sent_htlc_balance.clone()]);
832         assert_eq!(bs_pre_spend_claims,
833                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
834
835         // We'll broadcast the HTLC-Timeout transaction one block prior to the htlc's expiration (as it
836         // is confirmable in the next block), but will still include the same claimable balances as no
837         // HTLC has been spent, even after the HTLC expires. We'll also fail the inbound HTLC, but it
838         // won't do anything as the channel is already closed.
839
840         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
841         let as_htlc_timeout_claim = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
842         assert_eq!(as_htlc_timeout_claim.len(), 1);
843         check_spends!(as_htlc_timeout_claim[0], as_txn[0]);
844         expect_pending_htlcs_forwardable_conditions!(nodes[0],
845                 [HTLCDestination::FailedPayment { payment_hash: to_a_failed_payment_hash }]);
846
847         assert_eq!(as_pre_spend_claims,
848                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
849
850         connect_blocks(&nodes[0], 1);
851         assert_eq!(as_pre_spend_claims,
852                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
853
854         // For node B, we'll get the non-HTLC funds claimable after ANTI_REORG_DELAY confirmations
855         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
856         test_spendable_output(&nodes[1], &as_txn[0]);
857         bs_pre_spend_claims.retain(|e| if let Balance::ClaimableAwaitingConfirmations { .. } = e { false } else { true });
858
859         // The next few blocks for B look the same as for A, though for the opposite HTLC
860         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
861         connect_blocks(&nodes[1], TEST_FINAL_CLTV - (ANTI_REORG_DELAY - 1) - 1);
862         expect_pending_htlcs_forwardable_conditions!(nodes[1],
863                 [HTLCDestination::FailedPayment { payment_hash: to_b_failed_payment_hash }]);
864         let bs_htlc_timeout_claim = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
865         assert_eq!(bs_htlc_timeout_claim.len(), 1);
866         check_spends!(bs_htlc_timeout_claim[0], as_txn[0]);
867
868         assert_eq!(bs_pre_spend_claims,
869                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
870
871         connect_blocks(&nodes[1], 1);
872         assert_eq!(bs_pre_spend_claims,
873                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
874
875         // Now confirm the two HTLC timeout transactions for A, checking that the inbound HTLC resolves
876         // after ANTI_REORG_DELAY confirmations and the other takes BREAKDOWN_TIMEOUT confirmations.
877         mine_transaction(&nodes[0], &as_htlc_timeout_claim[0]);
878         let as_timeout_claimable_height = nodes[0].best_block_info().1 + (BREAKDOWN_TIMEOUT as u32) - 1;
879         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
880                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
881                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
882                         confirmation_height: node_a_commitment_claimable,
883                 }, a_received_htlc_balance.clone(), Balance::ClaimableAwaitingConfirmations {
884                         claimable_amount_satoshis: 10_000,
885                         confirmation_height: as_timeout_claimable_height,
886                 }]),
887                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
888
889         mine_transaction(&nodes[0], &bs_htlc_timeout_claim[0]);
890         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
891                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
892                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
893                         confirmation_height: node_a_commitment_claimable,
894                 }, a_received_htlc_balance.clone(), Balance::ClaimableAwaitingConfirmations {
895                         claimable_amount_satoshis: 10_000,
896                         confirmation_height: as_timeout_claimable_height,
897                 }]),
898                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
899
900         // Once as_htlc_timeout_claim[0] reaches ANTI_REORG_DELAY confirmations, we should get a
901         // payment failure event.
902         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
903         expect_payment_failed!(nodes[0], to_b_failed_payment_hash, false);
904
905         connect_blocks(&nodes[0], 1);
906         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
907                         claimable_amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
908                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
909                         confirmation_height: node_a_commitment_claimable,
910                 }, Balance::ClaimableAwaitingConfirmations {
911                         claimable_amount_satoshis: 10_000,
912                         confirmation_height: core::cmp::max(as_timeout_claimable_height, htlc_cltv_timeout),
913                 }]),
914                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
915
916         connect_blocks(&nodes[0], node_a_commitment_claimable - nodes[0].best_block_info().1);
917         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
918                         claimable_amount_satoshis: 10_000,
919                         confirmation_height: core::cmp::max(as_timeout_claimable_height, htlc_cltv_timeout),
920                 }],
921                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
922         test_spendable_output(&nodes[0], &as_txn[0]);
923
924         connect_blocks(&nodes[0], as_timeout_claimable_height - nodes[0].best_block_info().1);
925         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
926         test_spendable_output(&nodes[0], &as_htlc_timeout_claim[0]);
927
928         // The process for B should be completely identical as well, noting that the non-HTLC-balance
929         // was already claimed.
930         mine_transaction(&nodes[1], &bs_htlc_timeout_claim[0]);
931         let bs_timeout_claimable_height = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
932         assert_eq!(sorted_vec(vec![b_received_htlc_balance.clone(), Balance::ClaimableAwaitingConfirmations {
933                         claimable_amount_satoshis: 20_000,
934                         confirmation_height: bs_timeout_claimable_height,
935                 }]),
936                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
937
938         mine_transaction(&nodes[1], &as_htlc_timeout_claim[0]);
939         assert_eq!(sorted_vec(vec![b_received_htlc_balance.clone(), Balance::ClaimableAwaitingConfirmations {
940                         claimable_amount_satoshis: 20_000,
941                         confirmation_height: bs_timeout_claimable_height,
942                 }]),
943                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
944
945         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 2);
946         expect_payment_failed!(nodes[1], to_a_failed_payment_hash, false);
947
948         assert_eq!(vec![b_received_htlc_balance.clone()],
949                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
950         test_spendable_output(&nodes[1], &bs_htlc_timeout_claim[0]);
951
952         connect_blocks(&nodes[1], 1);
953         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
954
955         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
956         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
957         // monitor events or claimable balances.
958         connect_blocks(&nodes[1], 6);
959         connect_blocks(&nodes[1], 6);
960         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
961         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
962 }
963
964 fn sorted_vec_with_additions<T: Ord + Clone>(v_orig: &Vec<T>, extra_ts: &[&T]) -> Vec<T> {
965         let mut v = v_orig.clone();
966         for t in extra_ts {
967                 v.push((*t).clone());
968         }
969         v.sort_unstable();
970         v
971 }
972
973 fn do_test_revoked_counterparty_commitment_balances(confirm_htlc_spend_first: bool) {
974         // Tests `get_claimable_balances` for revoked counterparty commitment transactions.
975         let mut chanmon_cfgs = create_chanmon_cfgs(2);
976         // We broadcast a second-to-latest commitment transaction, without providing the revocation
977         // secret to the counterparty. However, because we always immediately take the revocation
978         // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
979         // transaction which, from the point of view of our keys_manager, is revoked.
980         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
981         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
982         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
983         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
984
985         let (_, _, chan_id, funding_tx) =
986                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 100_000_000);
987         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
988         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
989
990         // We create five HTLCs for B to claim against A's revoked commitment transaction:
991         //
992         // (1) one for which A is the originator and B knows the preimage
993         // (2) one for which B is the originator where the HTLC has since timed-out
994         // (3) one for which B is the originator but where the HTLC has not yet timed-out
995         // (4) one dust HTLC which is lost in the channel closure
996         // (5) one that actually isn't in the revoked commitment transaction at all, but was added in
997         //     later commitment transaction updates
998         //
999         // Though they could all be claimed in a single claim transaction, due to CLTV timeouts they
1000         // are all currently claimed in separate transactions, which helps us test as we can claim
1001         // HTLCs individually.
1002
1003         let (claimed_payment_preimage, claimed_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
1004         let timeout_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 4_000_000).1;
1005         let dust_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 3_000).1;
1006
1007         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1008
1009         connect_blocks(&nodes[0], 10);
1010         connect_blocks(&nodes[1], 10);
1011
1012         let live_htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1013         let live_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 5_000_000).1;
1014
1015         // Get the latest commitment transaction from A and then update the fee to revoke it
1016         let as_revoked_txn = get_local_commitment_txn!(nodes[0], chan_id);
1017         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_id);
1018
1019         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
1020
1021         let missing_htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1022         let missing_htlc_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 2_000_000).1;
1023
1024         nodes[1].node.claim_funds(claimed_payment_preimage);
1025         expect_payment_claimed!(nodes[1], claimed_payment_hash, 3_000_000);
1026         check_added_monitors!(nodes[1], 1);
1027         let _b_htlc_msgs = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
1028
1029         connect_blocks(&nodes[0], htlc_cltv_timeout + 1 - 10);
1030         check_closed_broadcast!(nodes[0], true);
1031         check_added_monitors!(nodes[0], 1);
1032
1033         let mut events = nodes[0].node.get_and_clear_pending_events();
1034         assert_eq!(events.len(), 6);
1035         let mut failed_payments: HashSet<_> =
1036                 [timeout_payment_hash, dust_payment_hash, live_payment_hash, missing_htlc_payment_hash]
1037                 .iter().map(|a| *a).collect();
1038         events.retain(|ev| {
1039                 match ev {
1040                         Event::HTLCHandlingFailed { failed_next_destination: HTLCDestination::NextHopChannel { node_id, channel_id }, .. } => {
1041                                 assert_eq!(*channel_id, chan_id);
1042                                 assert_eq!(*node_id, Some(nodes[1].node.get_our_node_id()));
1043                                 false
1044                         },
1045                         Event::HTLCHandlingFailed { failed_next_destination: HTLCDestination::FailedPayment { payment_hash }, .. } => {
1046                                 assert!(failed_payments.remove(payment_hash));
1047                                 false
1048                         },
1049                         _ => true,
1050                 }
1051         });
1052         assert!(failed_payments.is_empty());
1053         if let Event::PendingHTLCsForwardable { .. } = events[0] {} else { panic!(); }
1054         match &events[1] {
1055                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
1056                 _ => panic!(),
1057         }
1058
1059         connect_blocks(&nodes[1], htlc_cltv_timeout + 1 - 10);
1060         check_closed_broadcast!(nodes[1], true);
1061         check_added_monitors!(nodes[1], 1);
1062         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
1063
1064         // Prior to channel closure, B considers the preimage HTLC as its own, and otherwise only
1065         // lists the two on-chain timeout-able HTLCs as claimable balances.
1066         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
1067                         claimable_amount_satoshis: 100_000 - 5_000 - 4_000 - 3 - 2_000 + 3_000,
1068                 }, Balance::MaybeTimeoutClaimableHTLC {
1069                         claimable_amount_satoshis: 2_000,
1070                         claimable_height: missing_htlc_cltv_timeout,
1071                 }, Balance::MaybeTimeoutClaimableHTLC {
1072                         claimable_amount_satoshis: 4_000,
1073                         claimable_height: htlc_cltv_timeout,
1074                 }, Balance::MaybeTimeoutClaimableHTLC {
1075                         claimable_amount_satoshis: 5_000,
1076                         claimable_height: live_htlc_cltv_timeout,
1077                 }]),
1078                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1079
1080         mine_transaction(&nodes[1], &as_revoked_txn[0]);
1081         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();
1082         // Currently the revoked commitment is claimed in four transactions as the HTLCs all expire
1083         // quite soon.
1084         assert_eq!(claim_txn.len(), 4);
1085         claim_txn.sort_unstable_by_key(|tx| tx.output.iter().map(|output| output.value).sum::<u64>());
1086
1087         // The following constants were determined experimentally
1088         const BS_TO_SELF_CLAIM_EXP_WEIGHT: usize = 483;
1089         const OUTBOUND_HTLC_CLAIM_EXP_WEIGHT: usize = 571;
1090         const INBOUND_HTLC_CLAIM_EXP_WEIGHT: usize = 578;
1091
1092         // Check that the weight is close to the expected weight. Note that signature sizes vary
1093         // somewhat so it may not always be exact.
1094         fuzzy_assert_eq(claim_txn[0].weight(), OUTBOUND_HTLC_CLAIM_EXP_WEIGHT);
1095         fuzzy_assert_eq(claim_txn[1].weight(), INBOUND_HTLC_CLAIM_EXP_WEIGHT);
1096         fuzzy_assert_eq(claim_txn[2].weight(), INBOUND_HTLC_CLAIM_EXP_WEIGHT);
1097         fuzzy_assert_eq(claim_txn[3].weight(), BS_TO_SELF_CLAIM_EXP_WEIGHT);
1098
1099         // The expected balance for the next three checks, with the largest-HTLC and to_self output
1100         // claim balances separated out.
1101         let expected_balance = vec![Balance::ClaimableAwaitingConfirmations {
1102                         // to_remote output in A's revoked commitment
1103                         claimable_amount_satoshis: 100_000 - 5_000 - 4_000 - 3,
1104                         confirmation_height: nodes[1].best_block_info().1 + 5,
1105                 }, Balance::CounterpartyRevokedOutputClaimable {
1106                         claimable_amount_satoshis: 3_000,
1107                 }, Balance::CounterpartyRevokedOutputClaimable {
1108                         claimable_amount_satoshis: 4_000,
1109                 }];
1110
1111         let to_self_unclaimed_balance = Balance::CounterpartyRevokedOutputClaimable {
1112                 claimable_amount_satoshis: 1_000_000 - 100_000 - 3_000 - chan_feerate *
1113                         (channel::commitment_tx_base_weight(opt_anchors) + 3 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1114         };
1115         let to_self_claimed_avail_height;
1116         let largest_htlc_unclaimed_balance = Balance::CounterpartyRevokedOutputClaimable {
1117                 claimable_amount_satoshis: 5_000,
1118         };
1119         let largest_htlc_claimed_avail_height;
1120
1121         // Once the channel has been closed by A, B now considers all of the commitment transactions'
1122         // outputs as `CounterpartyRevokedOutputClaimable`.
1123         assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_unclaimed_balance, &largest_htlc_unclaimed_balance]),
1124                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1125
1126         if confirm_htlc_spend_first {
1127                 mine_transaction(&nodes[1], &claim_txn[2]);
1128                 largest_htlc_claimed_avail_height = nodes[1].best_block_info().1 + 5;
1129                 to_self_claimed_avail_height = nodes[1].best_block_info().1 + 6; // will be claimed in the next block
1130         } else {
1131                 // Connect the to_self output claim, taking all of A's non-HTLC funds
1132                 mine_transaction(&nodes[1], &claim_txn[3]);
1133                 to_self_claimed_avail_height = nodes[1].best_block_info().1 + 5;
1134                 largest_htlc_claimed_avail_height = nodes[1].best_block_info().1 + 6; // will be claimed in the next block
1135         }
1136
1137         let largest_htlc_claimed_balance = Balance::ClaimableAwaitingConfirmations {
1138                 claimable_amount_satoshis: 5_000 - chan_feerate * INBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1139                 confirmation_height: largest_htlc_claimed_avail_height,
1140         };
1141         let to_self_claimed_balance = Balance::ClaimableAwaitingConfirmations {
1142                 claimable_amount_satoshis: 1_000_000 - 100_000 - 3_000 - chan_feerate *
1143                         (channel::commitment_tx_base_weight(opt_anchors) + 3 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000
1144                         - chan_feerate * claim_txn[3].weight() as u64 / 1000,
1145                 confirmation_height: to_self_claimed_avail_height,
1146         };
1147
1148         if confirm_htlc_spend_first {
1149                 assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_unclaimed_balance, &largest_htlc_claimed_balance]),
1150                         sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1151         } else {
1152                 assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_claimed_balance, &largest_htlc_unclaimed_balance]),
1153                         sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1154         }
1155
1156         if confirm_htlc_spend_first {
1157                 mine_transaction(&nodes[1], &claim_txn[3]);
1158         } else {
1159                 mine_transaction(&nodes[1], &claim_txn[2]);
1160         }
1161         assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_claimed_balance, &largest_htlc_claimed_balance]),
1162                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1163
1164         // Finally, connect the last two remaining HTLC spends and check that they move to
1165         // `ClaimableAwaitingConfirmations`
1166         mine_transaction(&nodes[1], &claim_txn[0]);
1167         mine_transaction(&nodes[1], &claim_txn[1]);
1168
1169         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1170                         // to_remote output in A's revoked commitment
1171                         claimable_amount_satoshis: 100_000 - 5_000 - 4_000 - 3,
1172                         confirmation_height: nodes[1].best_block_info().1 + 1,
1173                 }, Balance::ClaimableAwaitingConfirmations {
1174                         claimable_amount_satoshis: 1_000_000 - 100_000 - 3_000 - chan_feerate *
1175                                 (channel::commitment_tx_base_weight(opt_anchors) + 3 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000
1176                                 - chan_feerate * claim_txn[3].weight() as u64 / 1000,
1177                         confirmation_height: to_self_claimed_avail_height,
1178                 }, Balance::ClaimableAwaitingConfirmations {
1179                         claimable_amount_satoshis: 3_000 - chan_feerate * OUTBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1180                         confirmation_height: nodes[1].best_block_info().1 + 4,
1181                 }, Balance::ClaimableAwaitingConfirmations {
1182                         claimable_amount_satoshis: 4_000 - chan_feerate * INBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1183                         confirmation_height: nodes[1].best_block_info().1 + 5,
1184                 }, Balance::ClaimableAwaitingConfirmations {
1185                         claimable_amount_satoshis: 5_000 - chan_feerate * INBOUND_HTLC_CLAIM_EXP_WEIGHT as u64 / 1000,
1186                         confirmation_height: largest_htlc_claimed_avail_height,
1187                 }]),
1188                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1189
1190         connect_blocks(&nodes[1], 1);
1191         test_spendable_output(&nodes[1], &as_revoked_txn[0]);
1192
1193         let mut payment_failed_events = nodes[1].node.get_and_clear_pending_events();
1194         expect_payment_failed_conditions_event(payment_failed_events[..2].to_vec(),
1195                 missing_htlc_payment_hash, false, PaymentFailedConditions::new());
1196         expect_payment_failed_conditions_event(payment_failed_events[2..].to_vec(),
1197                 dust_payment_hash, false, PaymentFailedConditions::new());
1198
1199         connect_blocks(&nodes[1], 1);
1200         test_spendable_output(&nodes[1], &claim_txn[if confirm_htlc_spend_first { 2 } else { 3 }]);
1201         connect_blocks(&nodes[1], 1);
1202         test_spendable_output(&nodes[1], &claim_txn[if confirm_htlc_spend_first { 3 } else { 2 }]);
1203         expect_payment_failed!(nodes[1], live_payment_hash, false);
1204         connect_blocks(&nodes[1], 1);
1205         test_spendable_output(&nodes[1], &claim_txn[0]);
1206         connect_blocks(&nodes[1], 1);
1207         test_spendable_output(&nodes[1], &claim_txn[1]);
1208         expect_payment_failed!(nodes[1], timeout_payment_hash, false);
1209         assert_eq!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances(), Vec::new());
1210
1211         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
1212         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
1213         // monitor events or claimable balances.
1214         connect_blocks(&nodes[1], 6);
1215         connect_blocks(&nodes[1], 6);
1216         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1217         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1218 }
1219
1220 #[test]
1221 fn test_revoked_counterparty_commitment_balances() {
1222         do_test_revoked_counterparty_commitment_balances(true);
1223         do_test_revoked_counterparty_commitment_balances(false);
1224 }
1225
1226 #[test]
1227 fn test_revoked_counterparty_htlc_tx_balances() {
1228         // Tests `get_claimable_balances` for revocation spends of HTLC transactions.
1229         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1230         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
1231         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1232         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1233         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1234
1235         // Create some initial channels
1236         let (_, _, chan_id, funding_tx) =
1237                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 11_000_000);
1238         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
1239         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
1240
1241         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
1242         let failed_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 1_000_000).1;
1243         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_id);
1244         assert_eq!(revoked_local_txn[0].input.len(), 1);
1245         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, funding_tx.txid());
1246
1247         // The to-be-revoked commitment tx should have two HTLCs and an output for both sides
1248         assert_eq!(revoked_local_txn[0].output.len(), 4);
1249
1250         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
1251
1252         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
1253         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_id);
1254
1255         // B will generate an HTLC-Success from its revoked commitment tx
1256         mine_transaction(&nodes[1], &revoked_local_txn[0]);
1257         check_closed_broadcast!(nodes[1], true);
1258         check_added_monitors!(nodes[1], 1);
1259         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
1260         let revoked_htlc_success = {
1261                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
1262                 assert_eq!(txn.len(), 1);
1263                 assert_eq!(txn[0].input.len(), 1);
1264                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
1265                 check_spends!(txn[0], revoked_local_txn[0]);
1266                 txn.pop().unwrap()
1267         };
1268
1269         connect_blocks(&nodes[1], TEST_FINAL_CLTV);
1270         let revoked_htlc_timeout = {
1271                 let mut txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
1272                 assert_eq!(txn.len(), 2);
1273                 if txn[0].input[0].previous_output == revoked_htlc_success.input[0].previous_output {
1274                         txn.remove(1)
1275                 } else {
1276                         txn.remove(0)
1277                 }
1278         };
1279         check_spends!(revoked_htlc_timeout, revoked_local_txn[0]);
1280         assert_ne!(revoked_htlc_success.input[0].previous_output, revoked_htlc_timeout.input[0].previous_output);
1281         assert_eq!(revoked_htlc_success.lock_time.0, 0);
1282         assert_ne!(revoked_htlc_timeout.lock_time.0, 0);
1283
1284         // A will generate justice tx from B's revoked commitment/HTLC tx
1285         mine_transaction(&nodes[0], &revoked_local_txn[0]);
1286         check_closed_broadcast!(nodes[0], true);
1287         check_added_monitors!(nodes[0], 1);
1288         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1289         let to_remote_conf_height = nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1;
1290
1291         let as_commitment_claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1292         assert_eq!(as_commitment_claim_txn.len(), 1);
1293         check_spends!(as_commitment_claim_txn[0], revoked_local_txn[0]);
1294
1295         // The next two checks have the same balance set for A - even though we confirm a revoked HTLC
1296         // transaction our balance tracking doesn't use the on-chain value so the
1297         // `CounterpartyRevokedOutputClaimable` entry doesn't change.
1298         let as_balances = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1299                         // to_remote output in B's revoked commitment
1300                         claimable_amount_satoshis: 1_000_000 - 11_000 - 3_000 - chan_feerate *
1301                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1302                         confirmation_height: to_remote_conf_height,
1303                 }, Balance::CounterpartyRevokedOutputClaimable {
1304                         // to_self output in B's revoked commitment
1305                         claimable_amount_satoshis: 10_000,
1306                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1307                         claimable_amount_satoshis: 3_000,
1308                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1309                         claimable_amount_satoshis: 1_000,
1310                 }]);
1311         assert_eq!(as_balances,
1312                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1313
1314         mine_transaction(&nodes[0], &revoked_htlc_success);
1315         let as_htlc_claim_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1316         assert_eq!(as_htlc_claim_tx.len(), 2);
1317         check_spends!(as_htlc_claim_tx[0], revoked_htlc_success);
1318         check_spends!(as_htlc_claim_tx[1], revoked_local_txn[0]); // A has to generate a new claim for the remaining revoked
1319                                                                   // outputs (which no longer includes the spent HTLC output)
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         assert_eq!(as_htlc_claim_tx[0].output.len(), 1);
1325         fuzzy_assert_eq(as_htlc_claim_tx[0].output[0].value,
1326                 3_000 - chan_feerate * (revoked_htlc_success.weight() + as_htlc_claim_tx[0].weight()) as u64 / 1000);
1327
1328         mine_transaction(&nodes[0], &as_htlc_claim_tx[0]);
1329         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1330                         // to_remote output in B's revoked commitment
1331                         claimable_amount_satoshis: 1_000_000 - 11_000 - 3_000 - chan_feerate *
1332                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1333                         confirmation_height: to_remote_conf_height,
1334                 }, Balance::CounterpartyRevokedOutputClaimable {
1335                         // to_self output in B's revoked commitment
1336                         claimable_amount_satoshis: 10_000,
1337                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1338                         claimable_amount_satoshis: 1_000,
1339                 }, Balance::ClaimableAwaitingConfirmations {
1340                         claimable_amount_satoshis: as_htlc_claim_tx[0].output[0].value,
1341                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
1342                 }]),
1343                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1344
1345         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 3);
1346         test_spendable_output(&nodes[0], &revoked_local_txn[0]);
1347         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1348                         // to_self output to B
1349                         claimable_amount_satoshis: 10_000,
1350                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1351                         claimable_amount_satoshis: 1_000,
1352                 }, Balance::ClaimableAwaitingConfirmations {
1353                         claimable_amount_satoshis: as_htlc_claim_tx[0].output[0].value,
1354                         confirmation_height: nodes[0].best_block_info().1 + 2,
1355                 }]),
1356                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1357
1358         connect_blocks(&nodes[0], 2);
1359         test_spendable_output(&nodes[0], &as_htlc_claim_tx[0]);
1360         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1361                         // to_self output in B's revoked commitment
1362                         claimable_amount_satoshis: 10_000,
1363                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1364                         claimable_amount_satoshis: 1_000,
1365                 }]),
1366                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1367
1368         connect_blocks(&nodes[0], revoked_htlc_timeout.lock_time.0 - nodes[0].best_block_info().1);
1369         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(&nodes[0],
1370                 [HTLCDestination::FailedPayment { payment_hash: failed_payment_hash }]);
1371         // As time goes on A may split its revocation claim transaction into multiple.
1372         let as_fewer_input_rbf = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1373         for tx in as_fewer_input_rbf.iter() {
1374                 check_spends!(tx, revoked_local_txn[0]);
1375         }
1376
1377         // Connect a number of additional blocks to ensure we don't forget the HTLC output needs
1378         // claiming.
1379         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
1380         let as_fewer_input_rbf = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1381         for tx in as_fewer_input_rbf.iter() {
1382                 check_spends!(tx, revoked_local_txn[0]);
1383         }
1384
1385         mine_transaction(&nodes[0], &revoked_htlc_timeout);
1386         let as_second_htlc_claim_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1387         assert_eq!(as_second_htlc_claim_tx.len(), 2);
1388
1389         check_spends!(as_second_htlc_claim_tx[0], revoked_htlc_timeout);
1390         check_spends!(as_second_htlc_claim_tx[1], revoked_local_txn[0]);
1391
1392         // Connect blocks to finalize the HTLC resolution with the HTLC-Timeout transaction. In a
1393         // previous iteration of the revoked balance handling this would result in us "forgetting" that
1394         // the revoked HTLC output still needed to be claimed.
1395         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
1396         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1397                         // to_self output in B's revoked commitment
1398                         claimable_amount_satoshis: 10_000,
1399                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1400                         claimable_amount_satoshis: 1_000,
1401                 }]),
1402                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1403
1404         mine_transaction(&nodes[0], &as_second_htlc_claim_tx[0]);
1405         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1406                         // to_self output in B's revoked commitment
1407                         claimable_amount_satoshis: 10_000,
1408                 }, Balance::ClaimableAwaitingConfirmations {
1409                         claimable_amount_satoshis: as_second_htlc_claim_tx[0].output[0].value,
1410                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
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[1]);
1415         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1416                         // to_self output in B's revoked commitment
1417                         claimable_amount_satoshis: as_second_htlc_claim_tx[1].output[0].value,
1418                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
1419                 }, Balance::ClaimableAwaitingConfirmations {
1420                         claimable_amount_satoshis: as_second_htlc_claim_tx[0].output[0].value,
1421                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 2,
1422                 }]),
1423                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1424
1425         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
1426         test_spendable_output(&nodes[0], &as_second_htlc_claim_tx[0]);
1427         connect_blocks(&nodes[0], 1);
1428         test_spendable_output(&nodes[0], &as_second_htlc_claim_tx[1]);
1429
1430         assert_eq!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances(), Vec::new());
1431
1432         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
1433         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
1434         // monitor events or claimable balances.
1435         connect_blocks(&nodes[0], 6);
1436         connect_blocks(&nodes[0], 6);
1437         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1438         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1439 }
1440
1441 #[test]
1442 fn test_revoked_counterparty_aggregated_claims() {
1443         // Tests `get_claimable_balances` for revoked counterparty commitment transactions when
1444         // claiming with an aggregated claim transaction.
1445         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1446         // We broadcast a second-to-latest commitment transaction, without providing the revocation
1447         // secret to the counterparty. However, because we always immediately take the revocation
1448         // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
1449         // transaction which, from the point of view of our keys_manager, is revoked.
1450         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
1451         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1452         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1453         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1454
1455         let (_, _, chan_id, funding_tx) =
1456                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 100_000_000);
1457         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
1458         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
1459
1460         // We create two HTLCs, one which we will give A the preimage to to generate an HTLC-Success
1461         // transaction, and one which we will not, allowing B to claim the HTLC output in an aggregated
1462         // revocation-claim transaction.
1463
1464         let (claimed_payment_preimage, claimed_payment_hash, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
1465         let revoked_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 4_000_000).1;
1466
1467         let htlc_cltv_timeout = nodes[1].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1468
1469         // Cheat by giving A's ChannelMonitor the preimage to the to-be-claimed HTLC so that we have an
1470         // HTLC-claim transaction on the to-be-revoked state.
1471         get_monitor!(nodes[0], chan_id).provide_payment_preimage(&claimed_payment_hash, &claimed_payment_preimage,
1472                 &node_cfgs[0].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[0].fee_estimator), &nodes[0].logger);
1473
1474         // Now get the latest commitment transaction from A and then update the fee to revoke it
1475         let as_revoked_txn = get_local_commitment_txn!(nodes[0], chan_id);
1476
1477         assert_eq!(as_revoked_txn.len(), 2);
1478         check_spends!(as_revoked_txn[0], funding_tx);
1479         check_spends!(as_revoked_txn[1], as_revoked_txn[0]); // The HTLC-Claim transaction
1480
1481         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_id);
1482         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
1483
1484         {
1485                 let mut feerate = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1486                 *feerate += 1;
1487         }
1488         nodes[0].node.timer_tick_occurred();
1489         check_added_monitors!(nodes[0], 1);
1490
1491         let fee_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1492         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &fee_update.update_fee.unwrap());
1493         commitment_signed_dance!(nodes[1], nodes[0], fee_update.commitment_signed, false);
1494
1495         nodes[0].node.claim_funds(claimed_payment_preimage);
1496         expect_payment_claimed!(nodes[0], claimed_payment_hash, 3_000_000);
1497         check_added_monitors!(nodes[0], 1);
1498         let _a_htlc_msgs = get_htlc_update_msgs!(&nodes[0], nodes[1].node.get_our_node_id());
1499
1500         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
1501                         claimable_amount_satoshis: 100_000 - 4_000 - 3_000,
1502                 }, Balance::MaybeTimeoutClaimableHTLC {
1503                         claimable_amount_satoshis: 4_000,
1504                         claimable_height: htlc_cltv_timeout,
1505                 }, Balance::MaybeTimeoutClaimableHTLC {
1506                         claimable_amount_satoshis: 3_000,
1507                         claimable_height: htlc_cltv_timeout,
1508                 }]),
1509                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1510
1511         mine_transaction(&nodes[1], &as_revoked_txn[0]);
1512         check_closed_broadcast!(nodes[1], true);
1513         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
1514         check_added_monitors!(nodes[1], 1);
1515
1516         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();
1517         // Currently the revoked commitment outputs are all claimed in one aggregated transaction
1518         assert_eq!(claim_txn.len(), 1);
1519         assert_eq!(claim_txn[0].input.len(), 3);
1520         check_spends!(claim_txn[0], as_revoked_txn[0]);
1521
1522         let to_remote_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1523
1524         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1525                         // to_remote output in A's revoked commitment
1526                         claimable_amount_satoshis: 100_000 - 4_000 - 3_000,
1527                         confirmation_height: to_remote_maturity,
1528                 }, Balance::CounterpartyRevokedOutputClaimable {
1529                         // to_self output in A's revoked commitment
1530                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1531                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1532                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1533                         claimable_amount_satoshis: 4_000,
1534                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1535                         claimable_amount_satoshis: 3_000,
1536                 }]),
1537                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1538
1539         // Confirm A's HTLC-Success tranasction which presumably raced B's claim, causing B to create a
1540         // new claim.
1541         mine_transaction(&nodes[1], &as_revoked_txn[1]);
1542         expect_payment_sent!(nodes[1], claimed_payment_preimage);
1543         let mut claim_txn_2: Vec<_> = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1544         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 });
1545         // Once B sees the HTLC-Success transaction it splits its claim transaction into two, though in
1546         // theory it could re-aggregate the claims as well.
1547         assert_eq!(claim_txn_2.len(), 2);
1548         assert_eq!(claim_txn_2[0].input.len(), 2);
1549         check_spends!(claim_txn_2[0], as_revoked_txn[0]);
1550         assert_eq!(claim_txn_2[1].input.len(), 1);
1551         check_spends!(claim_txn_2[1], as_revoked_txn[1]);
1552
1553         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1554                         // to_remote output in A's revoked commitment
1555                         claimable_amount_satoshis: 100_000 - 4_000 - 3_000,
1556                         confirmation_height: to_remote_maturity,
1557                 }, Balance::CounterpartyRevokedOutputClaimable {
1558                         // to_self output in A's revoked commitment
1559                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1560                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1561                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1562                         claimable_amount_satoshis: 4_000,
1563                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1564                         // The amount here is a bit of a misnomer, really its been reduced by the HTLC
1565                         // transaction fee, but the claimable amount is always a bit of an overshoot for HTLCs
1566                         // anyway, so its not a big change.
1567                         claimable_amount_satoshis: 3_000,
1568                 }]),
1569                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1570
1571         connect_blocks(&nodes[1], 5);
1572         test_spendable_output(&nodes[1], &as_revoked_txn[0]);
1573
1574         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1575                         // to_self output in A's revoked commitment
1576                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1577                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1578                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1579                         claimable_amount_satoshis: 4_000,
1580                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1581                         // The amount here is a bit of a misnomer, really its been reduced by the HTLC
1582                         // transaction fee, but the claimable amount is always a bit of an overshoot for HTLCs
1583                         // anyway, so its not a big change.
1584                         claimable_amount_satoshis: 3_000,
1585                 }]),
1586                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1587
1588         mine_transaction(&nodes[1], &claim_txn_2[1]);
1589         let htlc_2_claim_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1590
1591         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1592                         // to_self output in A's revoked commitment
1593                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1594                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1595                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1596                         claimable_amount_satoshis: 4_000,
1597                 }, Balance::ClaimableAwaitingConfirmations { // HTLC 2
1598                         claimable_amount_satoshis: claim_txn_2[1].output[0].value,
1599                         confirmation_height: htlc_2_claim_maturity,
1600                 }]),
1601                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1602
1603         connect_blocks(&nodes[1], 5);
1604         test_spendable_output(&nodes[1], &claim_txn_2[1]);
1605
1606         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1607                         // to_self output in A's revoked commitment
1608                         claimable_amount_satoshis: 1_000_000 - 100_000 - chan_feerate *
1609                                 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1610                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1611                         claimable_amount_satoshis: 4_000,
1612                 }]),
1613                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1614
1615         mine_transaction(&nodes[1], &claim_txn_2[0]);
1616         let rest_claim_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1617
1618         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
1619                         claimable_amount_satoshis: claim_txn_2[0].output[0].value,
1620                         confirmation_height: rest_claim_maturity,
1621                 }],
1622                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
1623
1624         assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); // We shouldn't fail the payment until we spend the output
1625
1626         connect_blocks(&nodes[1], 5);
1627         expect_payment_failed!(nodes[1], revoked_payment_hash, false);
1628         test_spendable_output(&nodes[1], &claim_txn_2[0]);
1629         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1630
1631         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
1632         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
1633         // monitor events or claimable balances.
1634         connect_blocks(&nodes[1], 6);
1635         connect_blocks(&nodes[1], 6);
1636         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1637         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1638 }
1639
1640 fn do_test_restored_packages_retry(check_old_monitor_retries_after_upgrade: bool) {
1641         // Tests that we'll retry packages that were previously timelocked after we've restored them.
1642         let persister;
1643         let new_chain_monitor;
1644         let node_deserialized;
1645
1646         let chanmon_cfgs = create_chanmon_cfgs(2);
1647         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1648         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1649         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1650
1651         // Open a channel, lock in an HTLC, and immediately broadcast the commitment transaction. This
1652         // ensures that the HTLC timeout package is held until we reach its expiration height.
1653         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 50_000_000);
1654         route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
1655
1656         nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
1657         check_added_monitors(&nodes[0], 1);
1658         check_closed_broadcast(&nodes[0], 1, true);
1659         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false);
1660
1661         let commitment_tx = {
1662                 let mut txn = nodes[0].tx_broadcaster.txn_broadcast();
1663                 assert_eq!(txn.len(), 1);
1664                 assert_eq!(txn[0].output.len(), 3);
1665                 check_spends!(txn[0], funding_tx);
1666                 txn.pop().unwrap()
1667         };
1668
1669         mine_transaction(&nodes[0], &commitment_tx);
1670
1671         // Connect blocks until the HTLC's expiration is met, expecting a transaction broadcast.
1672         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
1673         let htlc_timeout_tx = {
1674                 let mut txn = nodes[0].tx_broadcaster.txn_broadcast();
1675                 assert_eq!(txn.len(), 1);
1676                 check_spends!(txn[0], commitment_tx);
1677                 txn.pop().unwrap()
1678         };
1679
1680         // Check that we can still rebroadcast these packages/transactions if we're upgrading from an
1681         // old `ChannelMonitor` that did not exercise said rebroadcasting logic.
1682         if check_old_monitor_retries_after_upgrade {
1683                 let serialized_monitor = hex::decode(
1684                         "0101fffffffffffffffff9550f22c95100160014d5a9aa98b89acc215fc3d23d6fec0ad59ca3665f00002200204c5f18e5e95b184f34d02ba6de8a2a4e36ae3d4ec87299ad81f3284dc7195c6302d7dde8e10a5a22c9bd0d7ef5494d85683ac050253b917615d4f97af633f0a8e2035f5e9d58b4328566223c107d86cf853e6b9fae1d26ff6d969be0178d1423c4ea0016001467822698d782e8421ebdf96d010de99382b7ec2300160014caf6d80fe2bab80473b021f57588a9c384bf23170000000000000000000000004d49e5da0000000000000000000000000000002a0270b20ad0f2c2bb30a55590fc77778495bc1b38c96476901145dda57491237f0f74c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e00000022002034c0cc0ad0dd5fe61dcf7ef58f995e3d34f8dbd24aa2a6fae68fefe102bf025c21391732ce658e1fe167300bb689a81e7db5399b9ee4095e217b0e997e8dd3d17a0000000000000000004a002103adde8029d3ee281a32e9db929b39f503ff9d7e93cd308eb157955344dc6def84022103205087e2dc1f6b9937e887dfa712c5bdfa950b01dbda3ebac4c85efdde48ee6a04020090004752210307a78def56cba9fc4db22a25928181de538ee59ba1a475ae113af7790acd0db32103c21e841cbc0b48197d060c71e116c185fa0ac281b7d0aa5924f535154437ca3b52ae00000000000186a0ffffffffffff0291e7c0a3232fb8650a6b4089568a81062b48a768780e5a74bb4a4a74e33aec2c029d5760248ec86c4a76d9df8308555785a06a65472fb995f5b392d520bbd000650090c1c94b11625690c9d84c5daa67b6ad19fcc7f9f23e194384140b08fcab9e8e810000ffffffffffff000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000002391732ce658e1fe167300bb689a81e7db5399b9ee4095e217b0e997e8dd3d17a00000000000000010000000000009896800000005166687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f292505000000009c009900202d704fbfe342a9ff6eaca14d80a24aaed0e680bbbdd36157b6f2798c61d906910120f9fe5e552aa0fc45020f0505efde432a4e373e5d393863973a6899f8c26d33d10208000000000098968004494800210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23020500030241000408000001000000000006020000080800000000009896800a0400000046167c86cc0e598a6b541f7c9bf9ef17222e4a76f636e2d22185aeadd2b02d029c00000000000000000000000000000000000000000000000166687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925fffffffffffe01e3002004f8eda5676356f539169a8e9a1e86c7f125283328d6f4bded1b939b52a6a7e30108000000000000c299022103a1f98e85886df54add6908b4fc1ff515e44aedefe9eb9c02879c89994298fa79042103a650bf03971df0176c7b412247390ef717853e8bd487b204dccc2fe2078bb75206210390bbbcebe9f70ba5dfd98866a79f72f75e0a6ea550ef73b202dd87cd6477350a08210284152d57908488e666e872716a286eb670b3d06cbeebf3f2e4ad350e01ec5e5b0a2102295e2de39eb3dcc2882f8cc266df7882a8b6d2c32aa08799f49b693aad3be28e0c04000000fd0e00fd01fe002045cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d01080000000000009b5e0221035f5e9d58b4328566223c107d86cf853e6b9fae1d26ff6d969be0178d1423c4ea04210230fde9c031f487db95ff55b7c0acbe0c7c26a8d82615e9184416bd350101616706210225afb4e88eac8b47b67adeaf085f5eb5d37d936f56138f0848de3d104edf113208210208e4687a95c172b86b920c3bc5dbd5f023094ec2cb0abdb74f9b624f45740df90a2102d7dde8e10a5a22c9bd0d7ef5494d85683ac050253b917615d4f97af633f0a8e20c04000000fd0efd01193b00010102080000000000989680040400000051062066687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925080400000000417e2650c201383711eed2a7cb8652c3e77ee6a395e81849c5c222217ed68b333c0ca9f1e900662ae68a7359efa7ef9d90613f2a62f7c3ff90f8c25e2cc974c9d39c009900202d704fbfe342a9ff6eaca14d80a24aaed0e680bbbdd36157b6f2798c61d906910120f9fe5e552aa0fc45020f0505efde432a4e373e5d393863973a6899f8c26d33d10208000000000098968004494800210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c23020500030241000408000001000000000006020000080800000000009896800a0400000046fffffffffffefffffffffffe000000000000000000000000000000000000000000000000ffe099e83ae3761c7f1b781d22613bd1f6977e9ad59fae12b3eba34462ee8a3d000000500000000000000002fd01da002045cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d01fd01840200000000010174c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e00000000000f55f9800310270000000000002200208309b406e3b96e76cde414fbb8f5159f5b25b24075656c6382cec797854d53495e9b0000000000002200204c5f18e5e95b184f34d02ba6de8a2a4e36ae3d4ec87299ad81f3284dc7195c6350c300000000000016001425df8ec4a074f80579fed67d4707d5ec8ed7e8d304004730440220671c9badf26bd3a1ebd2d17020c6be20587d7822530daacc52c28839875eaec602204b575a21729ed27311f6d79fdf6fe8702b0a798f7d842e39ede1b56f249a613401473044022016a0da36f70cbf5d889586af88f238982889dc161462c56557125c7acfcb69e9022036ae10c6cc8cbc3b27d9e9ef6babb556086585bc819f252208bd175286699fdd014752210307a78def56cba9fc4db22a25928181de538ee59ba1a475ae113af7790acd0db32103c21e841cbc0b48197d060c71e116c185fa0ac281b7d0aa5924f535154437ca3b52ae50c9222002040000000b03209452ca8c90d4c78928b80ec41398f2a890324d8ad6e6c81408a0cb9b8d977b070406030400020090fd02a1002045cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d01fd01840200000000010174c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e00000000000f55f9800310270000000000002200208309b406e3b96e76cde414fbb8f5159f5b25b24075656c6382cec797854d53495e9b0000000000002200204c5f18e5e95b184f34d02ba6de8a2a4e36ae3d4ec87299ad81f3284dc7195c6350c300000000000016001425df8ec4a074f80579fed67d4707d5ec8ed7e8d304004730440220671c9badf26bd3a1ebd2d17020c6be20587d7822530daacc52c28839875eaec602204b575a21729ed27311f6d79fdf6fe8702b0a798f7d842e39ede1b56f249a613401473044022016a0da36f70cbf5d889586af88f238982889dc161462c56557125c7acfcb69e9022036ae10c6cc8cbc3b27d9e9ef6babb556086585bc819f252208bd175286699fdd014752210307a78def56cba9fc4db22a25928181de538ee59ba1a475ae113af7790acd0db32103c21e841cbc0b48197d060c71e116c185fa0ac281b7d0aa5924f535154437ca3b52ae50c9222002040000000b03209452ca8c90d4c78928b80ec41398f2a890324d8ad6e6c81408a0cb9b8d977b0704cd01cb00c901c7002245cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d0001022102d7dde8e10a5a22c9bd0d7ef5494d85683ac050253b917615d4f97af633f0a8e204020090062b5e9b0000000000002200204c5f18e5e95b184f34d02ba6de8a2a4e36ae3d4ec87299ad81f3284dc7195c630821035f5e9d58b4328566223c107d86cf853e6b9fae1d26ff6d969be0178d1423c4ea0a200000000000000000000000004d49e5da0000000000000000000000000000002a0c0800000000000186a0000000000000000274c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e0000000000000001000000000022002034c0cc0ad0dd5fe61dcf7ef58f995e3d34f8dbd24aa2a6fae68fefe102bf025c45cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d000000000000000100000000002200208309b406e3b96e76cde414fbb8f5159f5b25b24075656c6382cec797854d5349010100160014d5a9aa98b89acc215fc3d23d6fec0ad59ca3665ffd027100fd01e6fd01e300080000fffffffffffe02080000000000009b5e0408000000000000c3500604000000fd08b0af002102d7dde8e10a5a22c9bd0d7ef5494d85683ac050253b917615d4f97af633f0a8e20221035f5e9d58b4328566223c107d86cf853e6b9fae1d26ff6d969be0178d1423c4ea04210230fde9c031f487db95ff55b7c0acbe0c7c26a8d82615e9184416bd350101616706210225afb4e88eac8b47b67adeaf085f5eb5d37d936f56138f0848de3d104edf113208210208e4687a95c172b86b920c3bc5dbd5f023094ec2cb0abdb74f9b624f45740df90acdcc00a8020000000174c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e00000000000f55f9800310270000000000002200208309b406e3b96e76cde414fbb8f5159f5b25b24075656c6382cec797854d53495e9b0000000000002200204c5f18e5e95b184f34d02ba6de8a2a4e36ae3d4ec87299ad81f3284dc7195c6350c300000000000016001425df8ec4a074f80579fed67d4707d5ec8ed7e8d350c92220022045cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d0c3c3b00010102080000000000989680040400000051062066687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f29250804000000000240671c9badf26bd3a1ebd2d17020c6be20587d7822530daacc52c28839875eaec64b575a21729ed27311f6d79fdf6fe8702b0a798f7d842e39ede1b56f249a613404010006407e2650c201383711eed2a7cb8652c3e77ee6a395e81849c5c222217ed68b333c0ca9f1e900662ae68a7359efa7ef9d90613f2a62f7c3ff90f8c25e2cc974c9d3010000000000000001010000000000000000090b2a953d93a124c600ecb1a0ccfed420169cdd37f538ad94a3e4e6318c93c14adf59cdfbb40bdd40950c9f8dd547d29d75a173e1376a7850743394c46dea2dfd01cefd01ca00fd017ffd017c00080000ffffffffffff0208000000000000c2990408000000000000c3500604000000fd08b0af002102295e2de39eb3dcc2882f8cc266df7882a8b6d2c32aa08799f49b693aad3be28e022103a1f98e85886df54add6908b4fc1ff515e44aedefe9eb9c02879c89994298fa79042103a650bf03971df0176c7b412247390ef717853e8bd487b204dccc2fe2078bb75206210390bbbcebe9f70ba5dfd98866a79f72f75e0a6ea550ef73b202dd87cd6477350a08210284152d57908488e666e872716a286eb670b3d06cbeebf3f2e4ad350e01ec5e5b0aa2a1007d020000000174c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e00000000000f55f9800299c2000000000000220020740e108cfbc93967b6ab242a351ebee7de51814cf78d366adefd78b10281f17e50c300000000000016001425df8ec4a074f80579fed67d4707d5ec8ed7e8d351c92220022004f8eda5676356f539169a8e9a1e86c7f125283328d6f4bded1b939b52a6a7e30c00024045cb2485594bb1ec08e7bb6af4f89c912bd53f006d7876ea956773e04a4aad4a40e2b8d4fc612102f0b54061b3c1239fb78783053e8e6f9d92b1b99f81ae9ec2040100060000fd019600b0af002103c21e841cbc0b48197d060c71e116c185fa0ac281b7d0aa5924f535154437ca3b02210270b20ad0f2c2bb30a55590fc77778495bc1b38c96476901145dda57491237f0f042103b4e59df102747edc3a3e2283b42b88a8c8218ffd0dcfb52f2524b371d64cadaa062103d902b7b8b3434076d2b210e912c76645048b71e28995aad227a465a65ccd817608210301e9a52f923c157941de4a7692e601f758660969dcf5abdb67817efe84cce2ef0202009004010106b7b600b0af00210307a78def56cba9fc4db22a25928181de538ee59ba1a475ae113af7790acd0db30221034d0f817cb19b4a3bd144b615459bd06cbab3b4bdc96d73e18549a992cee80e8104210380542b59a9679890cba529fe155a9508ef57dac7416d035b23666e3fb98c3814062103adde8029d3ee281a32e9db929b39f503ff9d7e93cd308eb157955344dc6def84082103205087e2dc1f6b9937e887dfa712c5bdfa950b01dbda3ebac4c85efdde48ee6a02020090082274c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e000000000287010108d30df34e3a1e00ecdd03a2c843db062479a81752c4dfd0cc4baef0f81e7bc7ef8820990daf8d8e8d30a3b4b08af12c9f5cd71e45c7238103e0c80ca13850862e4fd2c56b69b7195312518de1bfe9aed63c80bb7760d70b2a870d542d815895fd12423d11e2adb0cdf55d776dac8f487c9b3b7ea12f1b150eb15889cf41333ade465692bf1cdc360b9c2a19bf8c1ca4fed7639d8bc953d36c10d8c6c9a8c0a57608788979bcf145e61b308006896e21d03e92084f93bd78740c20639134a7a8fd019afd019600b0af002103c21e841cbc0b48197d060c71e116c185fa0ac281b7d0aa5924f535154437ca3b02210270b20ad0f2c2bb30a55590fc77778495bc1b38c96476901145dda57491237f0f042103b4e59df102747edc3a3e2283b42b88a8c8218ffd0dcfb52f2524b371d64cadaa062103d902b7b8b3434076d2b210e912c76645048b71e28995aad227a465a65ccd817608210301e9a52f923c157941de4a7692e601f758660969dcf5abdb67817efe84cce2ef0202009004010106b7b600b0af00210307a78def56cba9fc4db22a25928181de538ee59ba1a475ae113af7790acd0db30221034d0f817cb19b4a3bd144b615459bd06cbab3b4bdc96d73e18549a992cee80e8104210380542b59a9679890cba529fe155a9508ef57dac7416d035b23666e3fb98c3814062103adde8029d3ee281a32e9db929b39f503ff9d7e93cd308eb157955344dc6def84082103205087e2dc1f6b9937e887dfa712c5bdfa950b01dbda3ebac4c85efdde48ee6a02020090082274c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e000000000000000186a00000000000000000000000004d49e5da0000000000000000000000000000002a000000000000000001b77b61346a2a408afdb01743a2230cb36e55771a0790f67a0910e207fd223fc8000000000000000145cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d00000000041000080000000000989680020400000051160004000000510208000000000000000004040000000b000000000000000145cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d00000000b77b61346a2a408afdb01743a2230cb36e55771a0790f67a0910e207fd223fc80000005000000000000000000000000000000000000101300300050007010109210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c230d000f020000",
1685                 ).unwrap();
1686                 reload_node!(nodes[0], &nodes[0].node.encode(), &[&serialized_monitor], persister, new_chain_monitor, node_deserialized);
1687         }
1688
1689         // Connecting more blocks should result in the HTLC transactions being rebroadcast.
1690         connect_blocks(&nodes[0], 6);
1691         if check_old_monitor_retries_after_upgrade {
1692                 check_added_monitors(&nodes[0], 1);
1693         }
1694         {
1695                 let txn = nodes[0].tx_broadcaster.txn_broadcast();
1696                 if !nodes[0].connect_style.borrow().skips_blocks() {
1697                         assert_eq!(txn.len(), 6);
1698                 } else {
1699                         assert!(txn.len() < 6);
1700                 }
1701                 for tx in txn {
1702                         assert_eq!(tx.input.len(), htlc_timeout_tx.input.len());
1703                         assert_eq!(tx.output.len(), htlc_timeout_tx.output.len());
1704                         assert_eq!(tx.input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
1705                         assert_eq!(tx.output[0], htlc_timeout_tx.output[0]);
1706                 }
1707         }
1708 }
1709
1710 #[test]
1711 fn test_restored_packages_retry() {
1712         do_test_restored_packages_retry(false);
1713         do_test_restored_packages_retry(true);
1714 }
1715
1716 #[cfg(anchors)]
1717 #[test]
1718 fn test_yield_anchors_events() {
1719         // Tests that two parties supporting anchor outputs can open a channel, route payments over
1720         // it, and finalize its resolution uncooperatively. Once the HTLCs are locked in, one side will
1721         // force close once the HTLCs expire. The force close should stem from an event emitted by LDK,
1722         // allowing the consumer to provide additional fees to the commitment transaction to be
1723         // broadcast. Once the commitment transaction confirms, events for the HTLC resolution should be
1724         // emitted by LDK, such that the consumer can attach fees to the zero fee HTLC transactions.
1725         let secp = Secp256k1::new();
1726         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1727         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1728         let mut anchors_config = UserConfig::default();
1729         anchors_config.channel_handshake_config.announced_channel = true;
1730         anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
1731         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config), Some(anchors_config)]);
1732         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1733
1734         let chan_id = create_announced_chan_between_nodes_with_value(
1735                 &nodes, 0, 1, 1_000_000, 500_000_000
1736         ).2;
1737         route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
1738         let (payment_preimage, payment_hash, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1739
1740         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1741
1742         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
1743         check_closed_broadcast!(&nodes[0], true);
1744         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
1745
1746         get_monitor!(nodes[0], chan_id).provide_payment_preimage(
1747                 &payment_hash, &payment_preimage, &node_cfgs[0].tx_broadcaster,
1748                 &LowerBoundedFeeEstimator::new(node_cfgs[0].fee_estimator), &nodes[0].logger
1749         );
1750
1751         let mut holder_events = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
1752         assert_eq!(holder_events.len(), 1);
1753         let (commitment_tx, anchor_tx) = match holder_events.pop().unwrap() {
1754                 Event::BumpTransaction(BumpTransactionEvent::ChannelClose { commitment_tx, anchor_descriptor, .. })  => {
1755                         assert_eq!(commitment_tx.input.len(), 1);
1756                         assert_eq!(commitment_tx.output.len(), 6);
1757                         let mut anchor_tx = Transaction {
1758                                 version: 2,
1759                                 lock_time: PackedLockTime::ZERO,
1760                                 input: vec![
1761                                         TxIn { previous_output: anchor_descriptor.outpoint, ..Default::default() },
1762                                         TxIn { ..Default::default() },
1763                                 ],
1764                                 output: vec![TxOut {
1765                                         value: Amount::ONE_BTC.to_sat(),
1766                                         script_pubkey: Script::new_op_return(&[]),
1767                                 }],
1768                         };
1769                         let signer = nodes[0].keys_manager.derive_channel_keys(
1770                                 anchor_descriptor.channel_value_satoshis, &anchor_descriptor.channel_keys_id,
1771                         );
1772                         let funding_sig = signer.sign_holder_anchor_input(&mut anchor_tx, 0, &secp).unwrap();
1773                         anchor_tx.input[0].witness = chan_utils::build_anchor_input_witness(
1774                                 &signer.pubkeys().funding_pubkey, &funding_sig
1775                         );
1776                         (commitment_tx, anchor_tx)
1777                 },
1778                 _ => panic!("Unexpected event"),
1779         };
1780
1781         mine_transactions(&nodes[0], &[&commitment_tx, &anchor_tx]);
1782         check_added_monitors!(nodes[0], 1);
1783
1784         let mut holder_events = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
1785         // Certain block `ConnectStyle`s cause an extra `ChannelClose` event to be emitted since the
1786         // best block is updated before the confirmed transactions are notified.
1787         match *nodes[0].connect_style.borrow() {
1788                 ConnectStyle::BestBlockFirst|ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::BestBlockFirstSkippingBlocks => {
1789                         assert_eq!(holder_events.len(), 3);
1790                         if let Event::BumpTransaction(BumpTransactionEvent::ChannelClose { .. }) = holder_events.remove(0) {}
1791                         else { panic!("unexpected event"); }
1792
1793                 },
1794                 _ => assert_eq!(holder_events.len(), 2),
1795         };
1796         let mut htlc_txs = Vec::with_capacity(2);
1797         for event in holder_events {
1798                 match event {
1799                         Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, tx_lock_time, .. }) => {
1800                                 assert_eq!(htlc_descriptors.len(), 1);
1801                                 let htlc_descriptor = &htlc_descriptors[0];
1802                                 let signer = nodes[0].keys_manager.derive_channel_keys(
1803                                         htlc_descriptor.channel_value_satoshis, &htlc_descriptor.channel_keys_id
1804                                 );
1805                                 let per_commitment_point = signer.get_per_commitment_point(htlc_descriptor.per_commitment_number, &secp);
1806                                 let mut htlc_tx = Transaction {
1807                                         version: 2,
1808                                         lock_time: tx_lock_time,
1809                                         input: vec![
1810                                                 htlc_descriptor.unsigned_tx_input(), // HTLC input
1811                                                 TxIn { ..Default::default() } // Fee input
1812                                         ],
1813                                         output: vec![
1814                                                 htlc_descriptor.tx_output(&per_commitment_point, &secp), // HTLC output
1815                                                 TxOut { // Fee input change
1816                                                         value: Amount::ONE_BTC.to_sat(),
1817                                                         script_pubkey: Script::new_op_return(&[]),
1818                                                 }
1819                                         ]
1820                                 };
1821                                 let our_sig = signer.sign_holder_htlc_transaction(&mut htlc_tx, 0, htlc_descriptor, &secp).unwrap();
1822                                 let witness_script = htlc_descriptor.witness_script(&per_commitment_point, &secp);
1823                                 htlc_tx.input[0].witness = htlc_descriptor.tx_input_witness(&our_sig, &witness_script);
1824                                 htlc_txs.push(htlc_tx);
1825                         },
1826                         _ => panic!("Unexpected event"),
1827                 }
1828         }
1829
1830         mine_transactions(&nodes[0], &[&htlc_txs[0], &htlc_txs[1]]);
1831         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
1832
1833         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1834
1835         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32);
1836
1837         let holder_events = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
1838         assert_eq!(holder_events.len(), 3);
1839         for event in holder_events {
1840                 match event {
1841                         Event::SpendableOutputs { .. } => {},
1842                         _ => panic!("Unexpected event"),
1843                 }
1844         }
1845
1846         // Clear the remaining events as they're not relevant to what we're testing.
1847         nodes[0].node.get_and_clear_pending_events();
1848 }
1849
1850 #[cfg(anchors)]
1851 #[test]
1852 fn test_anchors_aggregated_revoked_htlc_tx() {
1853         // Test that `ChannelMonitor`s can properly detect and claim funds from a counterparty claiming
1854         // multiple HTLCs from multiple channels in a single transaction via the success path from a
1855         // revoked commitment.
1856         let secp = Secp256k1::new();
1857         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1858         // Required to sign a revoked commitment transaction
1859         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
1860         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1861         let mut anchors_config = UserConfig::default();
1862         anchors_config.channel_handshake_config.announced_channel = true;
1863         anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
1864         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config), Some(anchors_config)]);
1865
1866         let bob_persister: test_utils::TestPersister;
1867         let bob_chain_monitor: test_utils::TestChainMonitor;
1868         let bob_deserialized: ChannelManager<
1869                 &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface,
1870                 &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator,
1871                 &test_utils::TestRouter, &test_utils::TestLogger,
1872         >;
1873
1874         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1875
1876         let chan_a = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 20_000_000);
1877         let chan_b = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 20_000_000);
1878
1879         // Serialize Bob with the initial state of both channels, which we'll use later.
1880         let bob_serialized = nodes[1].node.encode();
1881
1882         // Route two payments for each channel from Alice to Bob to lock in the HTLCs.
1883         let payment_a = route_payment(&nodes[0], &[&nodes[1]], 50_000_000);
1884         let payment_b = route_payment(&nodes[0], &[&nodes[1]], 50_000_000);
1885         let payment_c = route_payment(&nodes[0], &[&nodes[1]], 50_000_000);
1886         let payment_d = route_payment(&nodes[0], &[&nodes[1]], 50_000_000);
1887
1888         // Serialize Bob's monitors with the HTLCs locked in. We'll restart Bob later on with the state
1889         // at this point such that he broadcasts a revoked commitment transaction with the HTLCs
1890         // present.
1891         let bob_serialized_monitor_a = get_monitor!(nodes[1], chan_a.2).encode();
1892         let bob_serialized_monitor_b = get_monitor!(nodes[1], chan_b.2).encode();
1893
1894         // Bob claims all the HTLCs...
1895         claim_payment(&nodes[0], &[&nodes[1]], payment_a.0);
1896         claim_payment(&nodes[0], &[&nodes[1]], payment_b.0);
1897         claim_payment(&nodes[0], &[&nodes[1]], payment_c.0);
1898         claim_payment(&nodes[0], &[&nodes[1]], payment_d.0);
1899
1900         // ...and sends one back through each channel such that he has a motive to broadcast his
1901         // revoked state.
1902         send_payment(&nodes[1], &[&nodes[0]], 30_000_000);
1903         send_payment(&nodes[1], &[&nodes[0]], 30_000_000);
1904
1905         // Restart Bob with the revoked state and provide the HTLC preimages he claimed.
1906         reload_node!(
1907                 nodes[1], anchors_config, bob_serialized, &[&bob_serialized_monitor_a, &bob_serialized_monitor_b],
1908                 bob_persister, bob_chain_monitor, bob_deserialized
1909         );
1910         for chan_id in [chan_a.2, chan_b.2].iter() {
1911                 let monitor = get_monitor!(nodes[1], chan_id);
1912                 for payment in [payment_a, payment_b, payment_c, payment_d].iter() {
1913                         monitor.provide_payment_preimage(
1914                                 &payment.1, &payment.0, &node_cfgs[1].tx_broadcaster,
1915                                 &LowerBoundedFeeEstimator::new(node_cfgs[1].fee_estimator), &nodes[1].logger
1916                         );
1917                 }
1918         }
1919
1920         // Bob force closes by restarting with the outdated state, prompting the ChannelMonitors to
1921         // broadcast the latest commitment transaction known to them, which in our case is the one with
1922         // the HTLCs still pending.
1923         nodes[1].node.timer_tick_occurred();
1924         check_added_monitors(&nodes[1], 2);
1925         check_closed_event!(&nodes[1], 2, ClosureReason::OutdatedChannelManager);
1926         let (revoked_commitment_a, revoked_commitment_b) = {
1927                 let txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1928                 assert_eq!(txn.len(), 2);
1929                 assert_eq!(txn[0].output.len(), 6); // 2 HTLC outputs + 1 to_self output + 1 to_remote output + 2 anchor outputs
1930                 assert_eq!(txn[1].output.len(), 6); // 2 HTLC outputs + 1 to_self output + 1 to_remote output + 2 anchor outputs
1931                 if txn[0].input[0].previous_output.txid == chan_a.3.txid() {
1932                         check_spends!(&txn[0], &chan_a.3);
1933                         check_spends!(&txn[1], &chan_b.3);
1934                         (txn[0].clone(), txn[1].clone())
1935                 } else {
1936                         check_spends!(&txn[1], &chan_a.3);
1937                         check_spends!(&txn[0], &chan_b.3);
1938                         (txn[1].clone(), txn[0].clone())
1939                 }
1940         };
1941
1942         // Bob should now receive two events to bump his revoked commitment transaction fees.
1943         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1944         let events = nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events();
1945         assert_eq!(events.len(), 2);
1946         let anchor_tx = {
1947                 let secret_key = SecretKey::from_slice(&[1; 32]).unwrap();
1948                 let public_key = PublicKey::new(secret_key.public_key(&secp));
1949                 let fee_utxo_script = Script::new_v0_p2wpkh(&public_key.wpubkey_hash().unwrap());
1950                 let coinbase_tx = Transaction {
1951                         version: 2,
1952                         lock_time: PackedLockTime::ZERO,
1953                         input: vec![TxIn { ..Default::default() }],
1954                         output: vec![TxOut { // UTXO to attach fees to `anchor_tx`
1955                                 value: Amount::ONE_BTC.to_sat(),
1956                                 script_pubkey: fee_utxo_script.clone(),
1957                         }],
1958                 };
1959                 let mut anchor_tx = Transaction {
1960                         version: 2,
1961                         lock_time: PackedLockTime::ZERO,
1962                         input: vec![
1963                                 TxIn { // Fee input
1964                                         previous_output: bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 },
1965                                         ..Default::default()
1966                                 },
1967                         ],
1968                         output: vec![TxOut { // Fee input change
1969                                 value: coinbase_tx.output[0].value / 2 ,
1970                                 script_pubkey: Script::new_op_return(&[]),
1971                         }],
1972                 };
1973                 let mut signers = Vec::with_capacity(2);
1974                 for event in events {
1975                         match event {
1976                                 Event::BumpTransaction(BumpTransactionEvent::ChannelClose { anchor_descriptor, .. })  => {
1977                                         anchor_tx.input.push(TxIn {
1978                                                 previous_output: anchor_descriptor.outpoint,
1979                                                 ..Default::default()
1980                                         });
1981                                         let signer = nodes[1].keys_manager.derive_channel_keys(
1982                                                 anchor_descriptor.channel_value_satoshis, &anchor_descriptor.channel_keys_id,
1983                                         );
1984                                         signers.push(signer);
1985                                 },
1986                                 _ => panic!("Unexpected event"),
1987                         }
1988                 }
1989                 for (i, signer) in signers.into_iter().enumerate() {
1990                         let anchor_idx = i + 1;
1991                         let funding_sig = signer.sign_holder_anchor_input(&mut anchor_tx, anchor_idx, &secp).unwrap();
1992                         anchor_tx.input[anchor_idx].witness = chan_utils::build_anchor_input_witness(
1993                                 &signer.pubkeys().funding_pubkey, &funding_sig
1994                         );
1995                 }
1996                 let fee_utxo_sig = {
1997                         let witness_script = Script::new_p2pkh(&public_key.pubkey_hash());
1998                         let sighash = hash_to_message!(&SighashCache::new(&anchor_tx).segwit_signature_hash(
1999                                 0, &witness_script, coinbase_tx.output[0].value, EcdsaSighashType::All
2000                         ).unwrap()[..]);
2001                         let sig = sign(&secp, &sighash, &secret_key);
2002                         let mut sig = sig.serialize_der().to_vec();
2003                         sig.push(EcdsaSighashType::All as u8);
2004                         sig
2005                 };
2006                 anchor_tx.input[0].witness = Witness::from_vec(vec![fee_utxo_sig, public_key.to_bytes()]);
2007                 check_spends!(anchor_tx, coinbase_tx, revoked_commitment_a, revoked_commitment_b);
2008                 anchor_tx
2009         };
2010
2011         for node in &nodes {
2012                 mine_transactions(node, &[&revoked_commitment_a, &revoked_commitment_b, &anchor_tx]);
2013         }
2014         check_added_monitors!(&nodes[0], 2);
2015         check_closed_broadcast(&nodes[0], 2, true);
2016         check_closed_event!(&nodes[0], 2, ClosureReason::CommitmentTxConfirmed);
2017
2018         // Alice should detect the confirmed revoked commitments, and attempt to claim all of the
2019         // revoked outputs.
2020         {
2021                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2022                 assert_eq!(txn.len(), 2);
2023
2024                 let (revoked_claim_a, revoked_claim_b) = if txn[0].input[0].previous_output.txid == revoked_commitment_a.txid() {
2025                         (&txn[0], &txn[1])
2026                 } else {
2027                         (&txn[1], &txn[0])
2028                 };
2029
2030                 // TODO: to_self claim must be separate from HTLC claims
2031                 assert_eq!(revoked_claim_a.input.len(), 3); // Spends both HTLC outputs and to_self output
2032                 assert_eq!(revoked_claim_a.output.len(), 1);
2033                 check_spends!(revoked_claim_a, revoked_commitment_a);
2034                 assert_eq!(revoked_claim_b.input.len(), 3); // Spends both HTLC outputs and to_self output
2035                 assert_eq!(revoked_claim_b.output.len(), 1);
2036                 check_spends!(revoked_claim_b, revoked_commitment_b);
2037         }
2038
2039         // Since Bob was able to confirm his revoked commitment, he'll now try to claim the HTLCs
2040         // through the success path.
2041         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2042         let mut events = nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events();
2043         // Certain block `ConnectStyle`s cause an extra `ChannelClose` event to be emitted since the
2044         // best block is updated before the confirmed transactions are notified.
2045         match *nodes[1].connect_style.borrow() {
2046                 ConnectStyle::BestBlockFirst|ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::BestBlockFirstSkippingBlocks => {
2047                         assert_eq!(events.len(), 4);
2048                         if let Event::BumpTransaction(BumpTransactionEvent::ChannelClose { .. }) = events.remove(0) {}
2049                         else { panic!("unexpected event"); }
2050                         if let Event::BumpTransaction(BumpTransactionEvent::ChannelClose { .. }) = events.remove(1) {}
2051                         else { panic!("unexpected event"); }
2052
2053                 },
2054                 _ => assert_eq!(events.len(), 2),
2055         };
2056         let htlc_tx = {
2057                 let secret_key = SecretKey::from_slice(&[1; 32]).unwrap();
2058                 let public_key = PublicKey::new(secret_key.public_key(&secp));
2059                 let fee_utxo_script = Script::new_v0_p2wpkh(&public_key.wpubkey_hash().unwrap());
2060                 let coinbase_tx = Transaction {
2061                         version: 2,
2062                         lock_time: PackedLockTime::ZERO,
2063                         input: vec![TxIn { ..Default::default() }],
2064                         output: vec![TxOut { // UTXO to attach fees to `htlc_tx`
2065                                 value: Amount::ONE_BTC.to_sat(),
2066                                 script_pubkey: fee_utxo_script.clone(),
2067                         }],
2068                 };
2069                 let mut htlc_tx = Transaction {
2070                         version: 2,
2071                         lock_time: PackedLockTime::ZERO,
2072                         input: vec![TxIn { // Fee input
2073                                 previous_output: bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 },
2074                                 ..Default::default()
2075                         }],
2076                         output: vec![TxOut { // Fee input change
2077                                 value: coinbase_tx.output[0].value / 2 ,
2078                                 script_pubkey: Script::new_op_return(&[]),
2079                         }],
2080                 };
2081                 let mut descriptors = Vec::with_capacity(4);
2082                 for event in events {
2083                         if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, tx_lock_time, .. }) = event {
2084                                 assert_eq!(htlc_descriptors.len(), 2);
2085                                 for htlc_descriptor in &htlc_descriptors {
2086                                         assert!(!htlc_descriptor.htlc.offered);
2087                                         let signer = nodes[1].keys_manager.derive_channel_keys(
2088                                                 htlc_descriptor.channel_value_satoshis, &htlc_descriptor.channel_keys_id
2089                                         );
2090                                         let per_commitment_point = signer.get_per_commitment_point(htlc_descriptor.per_commitment_number, &secp);
2091                                         htlc_tx.input.push(htlc_descriptor.unsigned_tx_input());
2092                                         htlc_tx.output.push(htlc_descriptor.tx_output(&per_commitment_point, &secp));
2093                                 }
2094                                 descriptors.append(&mut htlc_descriptors);
2095                                 htlc_tx.lock_time = tx_lock_time;
2096                         } else {
2097                                 panic!("Unexpected event");
2098                         }
2099                 }
2100                 for (idx, htlc_descriptor) in descriptors.into_iter().enumerate() {
2101                         let htlc_input_idx = idx + 1;
2102                         let signer = nodes[1].keys_manager.derive_channel_keys(
2103                                 htlc_descriptor.channel_value_satoshis, &htlc_descriptor.channel_keys_id
2104                         );
2105                         let our_sig = signer.sign_holder_htlc_transaction(&htlc_tx, htlc_input_idx, &htlc_descriptor, &secp).unwrap();
2106                         let per_commitment_point = signer.get_per_commitment_point(htlc_descriptor.per_commitment_number, &secp);
2107                         let witness_script = htlc_descriptor.witness_script(&per_commitment_point, &secp);
2108                         htlc_tx.input[htlc_input_idx].witness = htlc_descriptor.tx_input_witness(&our_sig, &witness_script);
2109                 }
2110                 let fee_utxo_sig = {
2111                         let witness_script = Script::new_p2pkh(&public_key.pubkey_hash());
2112                         let sighash = hash_to_message!(&SighashCache::new(&htlc_tx).segwit_signature_hash(
2113                                 0, &witness_script, coinbase_tx.output[0].value, EcdsaSighashType::All
2114                         ).unwrap()[..]);
2115                         let sig = sign(&secp, &sighash, &secret_key);
2116                         let mut sig = sig.serialize_der().to_vec();
2117                         sig.push(EcdsaSighashType::All as u8);
2118                         sig
2119                 };
2120                 htlc_tx.input[0].witness = Witness::from_vec(vec![fee_utxo_sig, public_key.to_bytes()]);
2121                 check_spends!(htlc_tx, coinbase_tx, revoked_commitment_a, revoked_commitment_b);
2122                 htlc_tx
2123         };
2124
2125         for node in &nodes {
2126                 mine_transaction(node, &htlc_tx);
2127         }
2128
2129         // Alice should see that Bob is trying to claim to HTLCs, so she should now try to claim them at
2130         // the second level instead.
2131         let revoked_claims = {
2132                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2133                 assert_eq!(txn.len(), 4);
2134
2135                 let revoked_to_self_claim_a = txn.iter().find(|tx|
2136                         tx.input.len() == 1 &&
2137                         tx.output.len() == 1 &&
2138                         tx.input[0].previous_output.txid == revoked_commitment_a.txid()
2139                 ).unwrap();
2140                 check_spends!(revoked_to_self_claim_a, revoked_commitment_a);
2141
2142                 let revoked_to_self_claim_b = txn.iter().find(|tx|
2143                         tx.input.len() == 1 &&
2144                         tx.output.len() == 1 &&
2145                         tx.input[0].previous_output.txid == revoked_commitment_b.txid()
2146                 ).unwrap();
2147                 check_spends!(revoked_to_self_claim_b, revoked_commitment_b);
2148
2149                 let revoked_htlc_claims = txn.iter().filter(|tx|
2150                         tx.input.len() == 2 &&
2151                         tx.output.len() == 1 &&
2152                         tx.input[0].previous_output.txid == htlc_tx.txid()
2153                 ).collect::<Vec<_>>();
2154                 assert_eq!(revoked_htlc_claims.len(), 2);
2155                 for revoked_htlc_claim in revoked_htlc_claims {
2156                         check_spends!(revoked_htlc_claim, htlc_tx);
2157                 }
2158
2159                 txn
2160         };
2161         for node in &nodes {
2162                 mine_transactions(node, &revoked_claims.iter().collect::<Vec<_>>());
2163         }
2164
2165
2166         // Connect one block to make sure the HTLC events are not yielded while ANTI_REORG_DELAY has not
2167         // been reached.
2168         connect_blocks(&nodes[0], 1);
2169         connect_blocks(&nodes[1], 1);
2170
2171         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2172         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2173
2174         // Connect the remaining blocks to reach ANTI_REORG_DELAY.
2175         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
2176         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 2);
2177
2178         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2179         let spendable_output_events = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
2180         assert_eq!(spendable_output_events.len(), 4);
2181         for (idx, event) in spendable_output_events.iter().enumerate() {
2182                 if let Event::SpendableOutputs { outputs } = event {
2183                         assert_eq!(outputs.len(), 1);
2184                         let spend_tx = nodes[0].keys_manager.backing.spend_spendable_outputs(
2185                                 &[&outputs[0]], Vec::new(), Script::new_op_return(&[]), 253, &Secp256k1::new(),
2186                         ).unwrap();
2187                         check_spends!(spend_tx, revoked_claims[idx]);
2188                 } else {
2189                         panic!("unexpected event");
2190                 }
2191         }
2192
2193         assert!(nodes[0].node.list_channels().is_empty());
2194         assert!(nodes[1].node.list_channels().is_empty());
2195         assert!(nodes[0].chain_monitor.chain_monitor.get_claimable_balances(&[]).is_empty());
2196         // TODO: From Bob's PoV, he still thinks he can claim the outputs from his revoked commitment.
2197         // This needs to be fixed before we enable pruning `ChannelMonitor`s once they don't have any
2198         // balances to claim.
2199         //
2200         // The 6 claimable balances correspond to his `to_self` outputs and the 2 HTLC outputs in each
2201         // revoked commitment which Bob has the preimage for.
2202         assert_eq!(nodes[1].chain_monitor.chain_monitor.get_claimable_balances(&[]).len(), 6);
2203 }