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