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