Update default dust exposure limit and the documentation thereof
[rust-lightning] / lightning / src / ln / monitor_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Further functional tests which test blockchain reorganizations.
11
12 use crate::sign::{ecdsa::EcdsaChannelSigner, OutputSpender, SpendableOutputDescriptor};
13 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, LATENCY_GRACE_PERIOD_BLOCKS, Balance};
14 use crate::chain::transaction::OutPoint;
15 use crate::chain::chaininterface::{LowerBoundedFeeEstimator, compute_feerate_sat_per_1000_weight};
16 use crate::events::bump_transaction::{BumpTransactionEvent, WalletSource};
17 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
18 use crate::ln::{channel, ChannelId};
19 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, PaymentId, RecipientOnionFields};
20 use crate::ln::msgs::ChannelMessageHandler;
21 use crate::crypto::utils::sign;
22 use crate::util::ser::Writeable;
23 use crate::util::scid_utils::block_from_scid;
24 use crate::util::test_utils;
25
26 use bitcoin::{Amount, PublicKey, ScriptBuf, Transaction, TxIn, TxOut, Witness};
27 use bitcoin::blockdata::locktime::absolute::LockTime;
28 use bitcoin::blockdata::script::Builder;
29 use bitcoin::blockdata::opcodes;
30 use bitcoin::hashes::hex::FromHex;
31 use bitcoin::secp256k1::{Secp256k1, SecretKey};
32 use bitcoin::sighash::{SighashCache, EcdsaSighashType};
33
34 use crate::prelude::*;
35
36 use crate::ln::functional_test_utils::*;
37
38 #[test]
39 fn chanmon_fail_from_stale_commitment() {
40         // If we forward an HTLC to our counterparty, but we force-closed the channel before our
41         // counterparty provides us an updated commitment transaction, we'll end up with a commitment
42         // transaction that does not contain the HTLC which we attempted to forward. In this case, we
43         // need to wait `ANTI_REORG_DELAY` blocks and then fail back the HTLC as there is no way for us
44         // to learn the preimage and the confirmed commitment transaction paid us the value of the
45         // HTLC.
46         //
47         // However, previously, we did not do this, ignoring the HTLC entirely.
48         //
49         // This could lead to channel closure if the sender we received the HTLC from decides to go on
50         // chain to get their HTLC back before it times out.
51         //
52         // Here, we check exactly this case, forwarding a payment from A, through B, to C, before B
53         // broadcasts its latest commitment transaction, which should result in it eventually failing
54         // the HTLC back off-chain to A.
55         let chanmon_cfgs = create_chanmon_cfgs(3);
56         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
57         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
58         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
59
60         create_announced_chan_between_nodes(&nodes, 0, 1);
61         let (update_a, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
62
63         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
64         nodes[0].node.send_payment_with_route(&route, payment_hash,
65                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
66         check_added_monitors!(nodes[0], 1);
67
68         let bs_txn = get_local_commitment_txn!(nodes[1], chan_id_2);
69
70         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
71         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
72         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
73
74         expect_pending_htlcs_forwardable!(nodes[1]);
75         get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
76         check_added_monitors!(nodes[1], 1);
77
78         // Don't bother delivering the new HTLC add/commits, instead confirming the pre-HTLC commitment
79         // transaction for nodes[1].
80         mine_transaction(&nodes[1], &bs_txn[0]);
81         check_added_monitors!(nodes[1], 1);
82         check_closed_broadcast!(nodes[1], true);
83         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
84         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
85
86         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
87         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 }]);
88         check_added_monitors!(nodes[1], 1);
89         let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
90
91         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
92         commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, true, true);
93         expect_payment_failed_with_update!(nodes[0], payment_hash, false, update_a.contents.short_channel_id, true);
94 }
95
96 fn test_spendable_output<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, spendable_tx: &Transaction, has_anchors_htlc_event: bool) -> Vec<SpendableOutputDescriptor> {
97         let mut spendable = node.chain_monitor.chain_monitor.get_and_clear_pending_events();
98         assert_eq!(spendable.len(), if has_anchors_htlc_event { 2 } else { 1 });
99         if has_anchors_htlc_event {
100                 if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { .. }) = spendable.pop().unwrap() {}
101                 else { panic!(); }
102         }
103         if let Event::SpendableOutputs { outputs, .. } = spendable.pop().unwrap() {
104                 assert_eq!(outputs.len(), 1);
105                 let spend_tx = node.keys_manager.backing.spend_spendable_outputs(&[&outputs[0]], Vec::new(),
106                         Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &Secp256k1::new()).unwrap();
107                 check_spends!(spend_tx, spendable_tx);
108                 outputs
109         } else { panic!(); }
110 }
111
112 #[test]
113 fn revoked_output_htlc_resolution_timing() {
114         // Tests that HTLCs which were present in a broadcasted remote revoked commitment transaction
115         // are resolved only after a spend of the HTLC output reaches six confirmations. Preivously
116         // they would resolve after the revoked commitment transaction itself reaches six
117         // confirmations.
118         let chanmon_cfgs = create_chanmon_cfgs(2);
119         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
120         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
121         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
122
123         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
124
125         let payment_hash_1 = route_payment(&nodes[1], &[&nodes[0]], 1_000_000).1;
126
127         // Get a commitment transaction which contains the HTLC we care about, but which we'll revoke
128         // before forwarding.
129         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
130         assert_eq!(revoked_local_txn.len(), 1);
131
132         // Route a dust payment to revoke the above commitment transaction
133         route_payment(&nodes[0], &[&nodes[1]], 1_000);
134
135         // Confirm the revoked commitment transaction, closing the channel.
136         mine_transaction(&nodes[1], &revoked_local_txn[0]);
137         check_added_monitors!(nodes[1], 1);
138         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
139         check_closed_broadcast!(nodes[1], true);
140
141         let bs_spend_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
142         assert_eq!(bs_spend_txn.len(), 1);
143         check_spends!(bs_spend_txn[0], revoked_local_txn[0]);
144
145         // After the commitment transaction confirms, we should still wait on the HTLC spend
146         // transaction to confirm before resolving the HTLC.
147         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
148         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
149         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
150
151         // Spend the HTLC output, generating a HTLC failure event after ANTI_REORG_DELAY confirmations.
152         mine_transaction(&nodes[1], &bs_spend_txn[0]);
153         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
154         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
155
156         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
157         expect_payment_failed!(nodes[1], payment_hash_1, false);
158 }
159
160 #[test]
161 fn archive_fully_resolved_monitors() {
162         // Test we can archive fully resolved channel monitor.
163         let chanmon_cfgs = create_chanmon_cfgs(2);
164         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
165         let mut user_config = test_default_channel_config();
166         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config), Some(user_config)]);
167         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
168
169         let (_, _, chan_id, funding_tx) =
170                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000);
171
172         nodes[0].node.close_channel(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
173         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
174         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
175         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
176         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
177
178         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
179         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
180         let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
181         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
182         let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
183         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
184         let (_, _) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
185
186         let shutdown_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
187
188         mine_transaction(&nodes[0], &shutdown_tx[0]);
189         mine_transaction(&nodes[1], &shutdown_tx[0]);
190
191         connect_blocks(&nodes[0], 6);
192         connect_blocks(&nodes[1], 6);
193
194         check_closed_event!(nodes[0], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
195         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
196
197         assert_eq!(nodes[0].chain_monitor.chain_monitor.list_monitors().len(), 1);
198         // First archive should set balances_empty_height to current block height
199         nodes[0].chain_monitor.chain_monitor.archive_fully_resolved_channel_monitors(); 
200         assert_eq!(nodes[0].chain_monitor.chain_monitor.list_monitors().len(), 1);
201         connect_blocks(&nodes[0], 4032);
202         // Second call after 4032 blocks, should archive the monitor
203         nodes[0].chain_monitor.chain_monitor.archive_fully_resolved_channel_monitors();
204         // Should have no monitors left
205         assert_eq!(nodes[0].chain_monitor.chain_monitor.list_monitors().len(), 0);
206         // Remove the corresponding outputs and transactions the chain source is
207         // watching. This is to make sure the `Drop` function assertions pass.
208         nodes.get_mut(0).unwrap().chain_source.remove_watched_txn_and_outputs(
209                 OutPoint { txid: funding_tx.txid(), index: 0 },
210                 funding_tx.output[0].script_pubkey.clone()
211         );
212 }
213
214 fn do_chanmon_claim_value_coop_close(anchors: bool) {
215         // Tests `get_claimable_balances` returns the correct values across a simple cooperative claim.
216         // Specifically, this tests that the channel non-HTLC balances show up in
217         // `get_claimable_balances` until the cooperative claims have confirmed and generated a
218         // `SpendableOutputs` event, and no longer.
219         let chanmon_cfgs = create_chanmon_cfgs(2);
220         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
221         let mut user_config = test_default_channel_config();
222         if anchors {
223                 user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
224                 user_config.manually_accept_inbound_channels = true;
225         }
226         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config), Some(user_config)]);
227         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
228
229         let (_, _, chan_id, funding_tx) =
230                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000);
231         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
232         assert_eq!(ChannelId::v1_from_funding_outpoint(funding_outpoint), chan_id);
233
234         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
235         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_id);
236
237         let commitment_tx_fee = chan_feerate * channel::commitment_tx_base_weight(&channel_type_features) / 1000;
238         let anchor_outputs_value = if anchors { channel::ANCHOR_OUTPUT_VALUE_SATOSHI * 2 } else { 0 };
239         assert_eq!(vec![Balance::ClaimableOnChannelClose {
240                         amount_satoshis: 1_000_000 - 1_000 - commitment_tx_fee - anchor_outputs_value
241                 }],
242                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
243         assert_eq!(vec![Balance::ClaimableOnChannelClose { amount_satoshis: 1_000, }],
244                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
245
246         nodes[0].node.close_channel(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
247         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
248         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
249         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
250         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
251
252         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
253         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
254         let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
255         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
256         let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
257         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
258         let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
259         assert!(node_1_none.is_none());
260
261         let shutdown_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
262         assert_eq!(shutdown_tx, nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0));
263         assert_eq!(shutdown_tx.len(), 1);
264
265         let shutdown_tx_conf_height_a = block_from_scid(mine_transaction(&nodes[0], &shutdown_tx[0]));
266         let shutdown_tx_conf_height_b = block_from_scid(mine_transaction(&nodes[1], &shutdown_tx[0]));
267
268         assert!(nodes[0].node.list_channels().is_empty());
269         assert!(nodes[1].node.list_channels().is_empty());
270
271         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
272         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
273
274         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
275                         amount_satoshis: 1_000_000 - 1_000 - commitment_tx_fee - anchor_outputs_value,
276                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
277                 }],
278                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
279         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
280                         amount_satoshis: 1000,
281                         confirmation_height: nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1,
282                 }],
283                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
284
285         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
286         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 2);
287
288         assert!(get_monitor!(nodes[0], chan_id)
289                 .get_spendable_outputs(&shutdown_tx[0], shutdown_tx_conf_height_a).is_empty());
290         assert!(get_monitor!(nodes[1], chan_id)
291                 .get_spendable_outputs(&shutdown_tx[0], shutdown_tx_conf_height_b).is_empty());
292
293         connect_blocks(&nodes[0], 1);
294         connect_blocks(&nodes[1], 1);
295
296         assert_eq!(Vec::<Balance>::new(),
297                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
298         assert_eq!(Vec::<Balance>::new(),
299                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
300
301         let spendable_outputs_a = test_spendable_output(&nodes[0], &shutdown_tx[0], false);
302         assert_eq!(
303                 get_monitor!(nodes[0], chan_id).get_spendable_outputs(&shutdown_tx[0], shutdown_tx_conf_height_a),
304                 spendable_outputs_a
305         );
306
307         let spendable_outputs_b = test_spendable_output(&nodes[1], &shutdown_tx[0], false);
308         assert_eq!(
309                 get_monitor!(nodes[1], chan_id).get_spendable_outputs(&shutdown_tx[0], shutdown_tx_conf_height_b),
310                 spendable_outputs_b
311         );
312
313         check_closed_event!(nodes[0], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
314         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
315 }
316
317 #[test]
318 fn chanmon_claim_value_coop_close() {
319         do_chanmon_claim_value_coop_close(false);
320         do_chanmon_claim_value_coop_close(true);
321 }
322
323 fn sorted_vec<T: Ord>(mut v: Vec<T>) -> Vec<T> {
324         v.sort_unstable();
325         v
326 }
327
328 /// Asserts that `a` and `b` are close, but maybe off by up to 5.
329 /// This is useful when checking fees and weights on transactions as things may vary by a few based
330 /// on signature size and signature size estimation being non-exact.
331 fn fuzzy_assert_eq<V: core::convert::TryInto<u64>>(a: V, b: V) {
332         let a_u64 = a.try_into().map_err(|_| ()).unwrap();
333         let b_u64 = b.try_into().map_err(|_| ()).unwrap();
334         eprintln!("Checking {} and {} for fuzzy equality", a_u64, b_u64);
335         assert!(a_u64 >= b_u64 - 5);
336         assert!(b_u64 >= a_u64 - 5);
337 }
338
339 fn do_test_claim_value_force_close(anchors: bool, prev_commitment_tx: bool) {
340         // Tests `get_claimable_balances` with an HTLC across a force-close.
341         // We build a channel with an HTLC pending, then force close the channel and check that the
342         // `get_claimable_balances` return value is correct as transactions confirm on-chain.
343         let mut chanmon_cfgs = create_chanmon_cfgs(2);
344         if prev_commitment_tx {
345                 // We broadcast a second-to-latest commitment transaction, without providing the revocation
346                 // secret to the counterparty. However, because we always immediately take the revocation
347                 // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
348                 // transaction which, from the point of view of our keys_manager, is revoked.
349                 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
350         }
351         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
352         let mut user_config = test_default_channel_config();
353         if anchors {
354                 user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
355                 user_config.manually_accept_inbound_channels = true;
356         }
357         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config), Some(user_config)]);
358         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
359
360         let coinbase_tx = Transaction {
361                 version: 2,
362                 lock_time: LockTime::ZERO,
363                 input: vec![TxIn { ..Default::default() }],
364                 output: vec![
365                         TxOut {
366                                 value: Amount::ONE_BTC.to_sat(),
367                                 script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
368                         },
369                         TxOut {
370                                 value: Amount::ONE_BTC.to_sat(),
371                                 script_pubkey: nodes[1].wallet_source.get_change_script().unwrap(),
372                         },
373                 ],
374         };
375         if anchors {
376                 nodes[0].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 }, coinbase_tx.output[0].value);
377                 nodes[1].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 1 }, coinbase_tx.output[1].value);
378         }
379
380         let (_, _, chan_id, funding_tx) =
381                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000);
382         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
383         assert_eq!(ChannelId::v1_from_funding_outpoint(funding_outpoint), chan_id);
384
385         // This HTLC is immediately claimed, giving node B the preimage
386         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
387         // This HTLC is allowed to time out, letting A claim it. However, in order to test claimable
388         // balances more fully we also give B the preimage for this HTLC.
389         let (timeout_payment_preimage, timeout_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 4_000_000);
390         // This HTLC will be dust, and not be claimable at all:
391         let (dust_payment_preimage, dust_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000);
392
393         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
394
395         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id);
396         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_id);
397
398         let remote_txn = get_local_commitment_txn!(nodes[1], chan_id);
399         let sent_htlc_balance = Balance::MaybeTimeoutClaimableHTLC {
400                 amount_satoshis: 3_000,
401                 claimable_height: htlc_cltv_timeout,
402                 payment_hash,
403         };
404         let sent_htlc_timeout_balance = Balance::MaybeTimeoutClaimableHTLC {
405                 amount_satoshis: 4_000,
406                 claimable_height: htlc_cltv_timeout,
407                 payment_hash: timeout_payment_hash,
408         };
409         let received_htlc_balance = Balance::MaybePreimageClaimableHTLC {
410                 amount_satoshis: 3_000,
411                 expiry_height: htlc_cltv_timeout,
412                 payment_hash,
413         };
414         let received_htlc_timeout_balance = Balance::MaybePreimageClaimableHTLC {
415                 amount_satoshis: 4_000,
416                 expiry_height: htlc_cltv_timeout,
417                 payment_hash: timeout_payment_hash,
418         };
419         let received_htlc_claiming_balance = Balance::ContentiousClaimable {
420                 amount_satoshis: 3_000,
421                 timeout_height: htlc_cltv_timeout,
422                 payment_hash,
423                 payment_preimage,
424         };
425         let received_htlc_timeout_claiming_balance = Balance::ContentiousClaimable {
426                 amount_satoshis: 4_000,
427                 timeout_height: htlc_cltv_timeout,
428                 payment_hash: timeout_payment_hash,
429                 payment_preimage: timeout_payment_preimage,
430         };
431
432         // Before B receives the payment preimage, it only suggests the push_msat value of 1_000 sats
433         // as claimable. A lists both its to-self balance and the (possibly-claimable) HTLCs.
434         let commitment_tx_fee = chan_feerate as u64 *
435                 (channel::commitment_tx_base_weight(&channel_type_features) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
436         let anchor_outputs_value = if anchors { 2 * channel::ANCHOR_OUTPUT_VALUE_SATOSHI } else { 0 };
437         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
438                         amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - commitment_tx_fee - anchor_outputs_value,
439                 }, sent_htlc_balance.clone(), sent_htlc_timeout_balance.clone()]),
440                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
441         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
442                         amount_satoshis: 1_000,
443                 }, received_htlc_balance.clone(), received_htlc_timeout_balance.clone()]),
444                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
445
446         nodes[1].node.claim_funds(payment_preimage);
447         check_added_monitors!(nodes[1], 1);
448         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
449
450         let b_htlc_msgs = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
451         // We claim the dust payment here as well, but it won't impact our claimable balances as its
452         // dust and thus doesn't appear on chain at all.
453         nodes[1].node.claim_funds(dust_payment_preimage);
454         check_added_monitors!(nodes[1], 1);
455         expect_payment_claimed!(nodes[1], dust_payment_hash, 3_000);
456
457         nodes[1].node.claim_funds(timeout_payment_preimage);
458         check_added_monitors!(nodes[1], 1);
459         expect_payment_claimed!(nodes[1], timeout_payment_hash, 4_000_000);
460
461         if prev_commitment_tx {
462                 // To build a previous commitment transaction, deliver one round of commitment messages.
463                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.update_fulfill_htlcs[0]);
464                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
465                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.commitment_signed);
466                 check_added_monitors!(nodes[0], 1);
467                 let (as_raa, as_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
468                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
469                 let _htlc_updates = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
470                 check_added_monitors!(nodes[1], 1);
471                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs);
472                 let _bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
473                 check_added_monitors!(nodes[1], 1);
474         }
475
476         // Once B has received the payment preimage, it includes the value of the HTLC in its
477         // "claimable if you were to close the channel" balance.
478         let commitment_tx_fee = chan_feerate as u64 *
479                 (channel::commitment_tx_base_weight(&channel_type_features) +
480                 if prev_commitment_tx { 1 } else { 2 } * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
481         let mut a_expected_balances = vec![Balance::ClaimableOnChannelClose {
482                         amount_satoshis: 1_000_000 - // Channel funding value in satoshis
483                                 4_000 - // The to-be-failed HTLC value in satoshis
484                                 3_000 - // The claimed HTLC value in satoshis
485                                 1_000 - // The push_msat value in satoshis
486                                 3 - // The dust HTLC value in satoshis
487                                 commitment_tx_fee - // The commitment transaction fee with two HTLC outputs
488                                 anchor_outputs_value, // The anchor outputs value in satoshis
489                 }, sent_htlc_timeout_balance.clone()];
490         if !prev_commitment_tx {
491                 a_expected_balances.push(sent_htlc_balance.clone());
492         }
493         assert_eq!(sorted_vec(a_expected_balances),
494                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
495         assert_eq!(vec![Balance::ClaimableOnChannelClose {
496                         amount_satoshis: 1_000 + 3_000 + 4_000,
497                 }],
498                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
499
500         // Broadcast the closing transaction (which has both pending HTLCs in it) and get B's
501         // broadcasted HTLC claim transaction with preimage.
502         let node_b_commitment_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
503         mine_transaction(&nodes[0], &remote_txn[0]);
504         mine_transaction(&nodes[1], &remote_txn[0]);
505
506         if anchors {
507                 let mut events = nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events();
508                 assert_eq!(events.len(), 1);
509                 match events.pop().unwrap() {
510                         Event::BumpTransaction(bump_event) => {
511                                 let mut first_htlc_event = bump_event.clone();
512                                 if let BumpTransactionEvent::HTLCResolution { ref mut htlc_descriptors, .. } = &mut first_htlc_event {
513                                         htlc_descriptors.remove(1);
514                                 } else {
515                                         panic!("Unexpected event");
516                                 }
517                                 let mut second_htlc_event = bump_event;
518                                 if let BumpTransactionEvent::HTLCResolution { ref mut htlc_descriptors, .. } = &mut second_htlc_event {
519                                         htlc_descriptors.remove(0);
520                                 } else {
521                                         panic!("Unexpected event");
522                                 }
523                                 nodes[1].bump_tx_handler.handle_event(&first_htlc_event);
524                                 nodes[1].bump_tx_handler.handle_event(&second_htlc_event);
525                         },
526                         _ => panic!("Unexpected event"),
527                 }
528         }
529
530         let b_broadcast_txn = nodes[1].tx_broadcaster.txn_broadcast();
531         assert_eq!(b_broadcast_txn.len(), 2);
532         // b_broadcast_txn should spend the HTLCs output of the commitment tx for 3_000 and 4_000 sats
533         check_spends!(b_broadcast_txn[0], remote_txn[0], coinbase_tx);
534         check_spends!(b_broadcast_txn[1], remote_txn[0], coinbase_tx);
535         assert_eq!(b_broadcast_txn[0].input.len(), if anchors { 2 } else { 1 });
536         assert_eq!(b_broadcast_txn[1].input.len(), if anchors { 2 } else { 1 });
537         assert_eq!(remote_txn[0].output[b_broadcast_txn[0].input[0].previous_output.vout as usize].value, 3_000);
538         assert_eq!(remote_txn[0].output[b_broadcast_txn[1].input[0].previous_output.vout as usize].value, 4_000);
539
540         assert!(nodes[0].node.list_channels().is_empty());
541         check_closed_broadcast!(nodes[0], true);
542         check_added_monitors!(nodes[0], 1);
543         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
544         assert!(nodes[1].node.list_channels().is_empty());
545         check_closed_broadcast!(nodes[1], true);
546         check_added_monitors!(nodes[1], 1);
547         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
548         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
549         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
550
551         // Once the commitment transaction confirms, we will wait until ANTI_REORG_DELAY until we
552         // generate any `SpendableOutputs` events. Thus, the same balances will still be listed
553         // available in `get_claimable_balances`. However, both will swap from `ClaimableOnClose` to
554         // other Balance variants, as close has already happened.
555         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
556         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
557         let commitment_tx_fee = chan_feerate as u64 *
558                 (channel::commitment_tx_base_weight(&channel_type_features) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
559         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
560                         amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - commitment_tx_fee - anchor_outputs_value,
561                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
562                 }, sent_htlc_balance.clone(), sent_htlc_timeout_balance.clone()]),
563                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
564         // The main non-HTLC balance is just awaiting confirmations, but the claimable height is the
565         // CSV delay, not ANTI_REORG_DELAY.
566         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
567                         amount_satoshis: 1_000,
568                         confirmation_height: node_b_commitment_claimable,
569                 },
570                 // Both HTLC balances are "contentious" as our counterparty could claim them if we wait too
571                 // long.
572                 received_htlc_claiming_balance.clone(), received_htlc_timeout_claiming_balance.clone()]),
573                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
574
575         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
576         expect_payment_failed!(nodes[0], dust_payment_hash, false);
577         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
578
579         // After ANTI_REORG_DELAY, A will consider its balance fully spendable and generate a
580         // `SpendableOutputs` event. However, B still has to wait for the CSV delay.
581         assert_eq!(sorted_vec(vec![sent_htlc_balance.clone(), sent_htlc_timeout_balance.clone()]),
582                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
583         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
584                         amount_satoshis: 1_000,
585                         confirmation_height: node_b_commitment_claimable,
586                 }, received_htlc_claiming_balance.clone(), received_htlc_timeout_claiming_balance.clone()]),
587                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
588
589         test_spendable_output(&nodes[0], &remote_txn[0], false);
590         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
591
592         // After broadcasting the HTLC claim transaction, node A will still consider the HTLC
593         // possibly-claimable up to ANTI_REORG_DELAY, at which point it will drop it.
594         mine_transaction(&nodes[0], &b_broadcast_txn[0]);
595         if prev_commitment_tx {
596                 expect_payment_path_successful!(nodes[0]);
597         } else {
598                 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
599         }
600         assert_eq!(sorted_vec(vec![sent_htlc_balance.clone(), sent_htlc_timeout_balance.clone()]),
601                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
602         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
603         assert_eq!(vec![sent_htlc_timeout_balance.clone()],
604                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
605
606         // When the HTLC timeout output is spendable in the next block, A should broadcast it
607         connect_blocks(&nodes[0], htlc_cltv_timeout - nodes[0].best_block_info().1);
608         let a_broadcast_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
609         assert_eq!(a_broadcast_txn.len(), 2);
610         assert_eq!(a_broadcast_txn[0].input.len(), 1);
611         check_spends!(a_broadcast_txn[0], remote_txn[0]);
612         assert_eq!(a_broadcast_txn[1].input.len(), 1);
613         check_spends!(a_broadcast_txn[1], remote_txn[0]);
614         assert_ne!(a_broadcast_txn[0].input[0].previous_output.vout,
615                    a_broadcast_txn[1].input[0].previous_output.vout);
616         // a_broadcast_txn [0] and [1] should spend the HTLC outputs of the commitment tx
617         assert_eq!(remote_txn[0].output[a_broadcast_txn[0].input[0].previous_output.vout as usize].value, 3_000);
618         assert_eq!(remote_txn[0].output[a_broadcast_txn[1].input[0].previous_output.vout as usize].value, 4_000);
619
620         // Once the HTLC-Timeout transaction confirms, A will no longer consider the HTLC
621         // "MaybeClaimable", but instead move it to "AwaitingConfirmations".
622         mine_transaction(&nodes[0], &a_broadcast_txn[1]);
623         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
624         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
625                         amount_satoshis: 4_000,
626                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
627                 }],
628                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
629         // After ANTI_REORG_DELAY, A will generate a SpendableOutputs event and drop the claimable
630         // balance entry.
631         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
632         assert_eq!(Vec::<Balance>::new(),
633                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
634         expect_payment_failed!(nodes[0], timeout_payment_hash, false);
635
636         test_spendable_output(&nodes[0], &a_broadcast_txn[1], false);
637
638         // Node B will no longer consider the HTLC "contentious" after the HTLC claim transaction
639         // confirms, and consider it simply "awaiting confirmations". Note that it has to wait for the
640         // standard revocable transaction CSV delay before receiving a `SpendableOutputs`.
641         let node_b_htlc_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
642         mine_transaction(&nodes[1], &b_broadcast_txn[0]);
643
644         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
645                         amount_satoshis: 1_000,
646                         confirmation_height: node_b_commitment_claimable,
647                 }, Balance::ClaimableAwaitingConfirmations {
648                         amount_satoshis: 3_000,
649                         confirmation_height: node_b_htlc_claimable,
650                 }, received_htlc_timeout_claiming_balance.clone()]),
651                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
652
653         // After reaching the commitment output CSV, we'll get a SpendableOutputs event for it and have
654         // only the HTLCs claimable on node B.
655         connect_blocks(&nodes[1], node_b_commitment_claimable - nodes[1].best_block_info().1);
656         test_spendable_output(&nodes[1], &remote_txn[0], anchors);
657
658         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
659                         amount_satoshis: 3_000,
660                         confirmation_height: node_b_htlc_claimable,
661                 }, received_htlc_timeout_claiming_balance.clone()]),
662                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
663
664         // After reaching the claimed HTLC output CSV, we'll get a SpendableOutptus event for it and
665         // have only one HTLC output left spendable.
666         connect_blocks(&nodes[1], node_b_htlc_claimable - nodes[1].best_block_info().1);
667         test_spendable_output(&nodes[1], &b_broadcast_txn[0], anchors);
668
669         assert_eq!(vec![received_htlc_timeout_claiming_balance.clone()],
670                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
671
672         // Finally, mine the HTLC timeout transaction that A broadcasted (even though B should be able
673         // to claim this HTLC with the preimage it knows!). It will remain listed as a claimable HTLC
674         // until ANTI_REORG_DELAY confirmations on the spend.
675         mine_transaction(&nodes[1], &a_broadcast_txn[1]);
676         assert_eq!(vec![received_htlc_timeout_claiming_balance.clone()],
677                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
678         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
679         assert_eq!(Vec::<Balance>::new(),
680                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
681
682         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
683         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
684         // monitor events or claimable balances.
685         for node in nodes.iter() {
686                 connect_blocks(node, 6);
687                 connect_blocks(node, 6);
688                 assert!(node.chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
689                 assert!(node.chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
690         }
691 }
692
693 #[test]
694 fn test_claim_value_force_close() {
695         do_test_claim_value_force_close(false, true);
696         do_test_claim_value_force_close(false, false);
697         do_test_claim_value_force_close(true, true);
698         do_test_claim_value_force_close(true, false);
699 }
700
701 fn do_test_balances_on_local_commitment_htlcs(anchors: bool) {
702         // Previously, when handling the broadcast of a local commitment transactions (with associated
703         // CSV delays prior to spendability), we incorrectly handled the CSV delays on HTLC
704         // transactions. This caused us to miss spendable outputs for HTLCs which were awaiting a CSV
705         // delay prior to spendability.
706         //
707         // Further, because of this, we could hit an assertion as `get_claimable_balances` asserted
708         // that HTLCs were resolved after the funding spend was resolved, which was not true if the
709         // HTLC did not have a CSV delay attached (due to the above bug or due to it being an HTLC
710         // claim by our counterparty).
711         let chanmon_cfgs = create_chanmon_cfgs(2);
712         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
713         let mut user_config = test_default_channel_config();
714         if anchors {
715                 user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
716                 user_config.manually_accept_inbound_channels = true;
717         }
718         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config), Some(user_config)]);
719         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
720
721         let coinbase_tx = Transaction {
722                 version: 2,
723                 lock_time: LockTime::ZERO,
724                 input: vec![TxIn { ..Default::default() }],
725                 output: vec![
726                         TxOut {
727                                 value: Amount::ONE_BTC.to_sat(),
728                                 script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
729                         },
730                         TxOut {
731                                 value: Amount::ONE_BTC.to_sat(),
732                                 script_pubkey: nodes[1].wallet_source.get_change_script().unwrap(),
733                         },
734                 ],
735         };
736         if anchors {
737                 nodes[0].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 }, coinbase_tx.output[0].value);
738                 nodes[1].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 1 }, coinbase_tx.output[1].value);
739         }
740
741         // Create a single channel with two pending HTLCs from nodes[0] to nodes[1], one which nodes[1]
742         // knows the preimage for, one which it does not.
743         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
744         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
745
746         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000_000);
747         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
748         nodes[0].node.send_payment_with_route(&route, payment_hash,
749                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
750         check_added_monitors!(nodes[0], 1);
751
752         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
753         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
754         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
755
756         expect_pending_htlcs_forwardable!(nodes[1]);
757         expect_payment_claimable!(nodes[1], payment_hash, payment_secret, 10_000_000);
758
759         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 20_000_000);
760         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
761                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
762         check_added_monitors!(nodes[0], 1);
763
764         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
765         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
766         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
767
768         expect_pending_htlcs_forwardable!(nodes[1]);
769         expect_payment_claimable!(nodes[1], payment_hash_2, payment_secret_2, 20_000_000);
770         nodes[1].node.claim_funds(payment_preimage_2);
771         get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
772         check_added_monitors!(nodes[1], 1);
773         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000_000);
774
775         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
776         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_id);
777
778         // First confirm the commitment transaction on nodes[0], which should leave us with three
779         // claimable balances.
780         let node_a_commitment_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
781         nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
782         check_added_monitors!(nodes[0], 1);
783         check_closed_broadcast!(nodes[0], true);
784         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 1000000);
785         let commitment_tx = {
786                 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
787                 assert_eq!(txn.len(), 1);
788                 let commitment_tx = txn.pop().unwrap();
789                 check_spends!(commitment_tx, funding_tx);
790                 commitment_tx
791         };
792         let commitment_tx_conf_height_a = block_from_scid(mine_transaction(&nodes[0], &commitment_tx));
793         if nodes[0].connect_style.borrow().updates_best_block_first() {
794                 let mut txn = nodes[0].tx_broadcaster.txn_broadcast();
795                 assert_eq!(txn.len(), 1);
796                 assert_eq!(txn[0].txid(), commitment_tx.txid());
797         }
798
799         let htlc_balance_known_preimage = Balance::MaybeTimeoutClaimableHTLC {
800                 amount_satoshis: 10_000,
801                 claimable_height: htlc_cltv_timeout,
802                 payment_hash,
803         };
804         let htlc_balance_unknown_preimage = Balance::MaybeTimeoutClaimableHTLC {
805                 amount_satoshis: 20_000,
806                 claimable_height: htlc_cltv_timeout,
807                 payment_hash: payment_hash_2,
808         };
809
810         let commitment_tx_fee = chan_feerate *
811                 (channel::commitment_tx_base_weight(&channel_type_features) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
812         let anchor_outputs_value = if anchors { 2 * channel::ANCHOR_OUTPUT_VALUE_SATOSHI } else { 0 };
813         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
814                         amount_satoshis: 1_000_000 - 10_000 - 20_000 - commitment_tx_fee - anchor_outputs_value,
815                         confirmation_height: node_a_commitment_claimable,
816                 }, htlc_balance_known_preimage.clone(), htlc_balance_unknown_preimage.clone()]),
817                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
818
819         // Get nodes[1]'s HTLC claim tx for the second HTLC
820         mine_transaction(&nodes[1], &commitment_tx);
821         check_added_monitors!(nodes[1], 1);
822         check_closed_broadcast!(nodes[1], true);
823         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
824         let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
825         assert_eq!(bs_htlc_claim_txn.len(), 1);
826         check_spends!(bs_htlc_claim_txn[0], commitment_tx);
827
828         // Connect blocks until the HTLCs expire, allowing us to (validly) broadcast the HTLC-Timeout
829         // transaction.
830         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
831         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
832                         amount_satoshis: 1_000_000 - 10_000 - 20_000 - commitment_tx_fee - anchor_outputs_value,
833                         confirmation_height: node_a_commitment_claimable,
834                 }, htlc_balance_known_preimage.clone(), htlc_balance_unknown_preimage.clone()]),
835                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
836         if anchors {
837                 handle_bump_htlc_event(&nodes[0], 2);
838         }
839         let timeout_htlc_txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
840         assert_eq!(timeout_htlc_txn.len(), 2);
841         check_spends!(timeout_htlc_txn[0], commitment_tx, coinbase_tx);
842         check_spends!(timeout_htlc_txn[1], commitment_tx, coinbase_tx);
843
844         // Now confirm nodes[0]'s HTLC-Timeout transaction, which changes the claimable balance to an
845         // "awaiting confirmations" one.
846         let node_a_htlc_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
847         mine_transaction(&nodes[0], &timeout_htlc_txn[0]);
848         // Note that prior to the fix in the commit which introduced this test, this (and the next
849         // balance) check failed. With this check removed, the code panicked in the `connect_blocks`
850         // call, as described, two hunks down.
851         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
852                         amount_satoshis: 1_000_000 - 10_000 - 20_000 - commitment_tx_fee - anchor_outputs_value,
853                         confirmation_height: node_a_commitment_claimable,
854                 }, Balance::ClaimableAwaitingConfirmations {
855                         amount_satoshis: 10_000,
856                         confirmation_height: node_a_htlc_claimable,
857                 }, htlc_balance_unknown_preimage.clone()]),
858                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
859
860         // Now confirm nodes[1]'s HTLC claim, giving nodes[0] the preimage. Note that the "maybe
861         // claimable" balance remains until we see ANTI_REORG_DELAY blocks.
862         mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
863         expect_payment_sent(&nodes[0], payment_preimage_2, None, true, false);
864         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
865                         amount_satoshis: 1_000_000 - 10_000 - 20_000 - commitment_tx_fee - anchor_outputs_value,
866                         confirmation_height: node_a_commitment_claimable,
867                 }, Balance::ClaimableAwaitingConfirmations {
868                         amount_satoshis: 10_000,
869                         confirmation_height: node_a_htlc_claimable,
870                 }, htlc_balance_unknown_preimage.clone()]),
871                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
872
873         // Finally make the HTLC transactions have ANTI_REORG_DELAY blocks. This call previously
874         // panicked as described in the test introduction. This will remove the "maybe claimable"
875         // spendable output as nodes[1] has fully claimed the second HTLC.
876         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
877         expect_payment_failed!(nodes[0], payment_hash, false);
878
879         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
880                         amount_satoshis: 1_000_000 - 10_000 - 20_000 - commitment_tx_fee - anchor_outputs_value,
881                         confirmation_height: node_a_commitment_claimable,
882                 }, Balance::ClaimableAwaitingConfirmations {
883                         amount_satoshis: 10_000,
884                         confirmation_height: node_a_htlc_claimable,
885                 }]),
886                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
887
888         // Connect blocks until the commitment transaction's CSV expires, providing us the relevant
889         // `SpendableOutputs` event and removing the claimable balance entry.
890         connect_blocks(&nodes[0], node_a_commitment_claimable - nodes[0].best_block_info().1 - 1);
891         assert!(get_monitor!(nodes[0], chan_id)
892                 .get_spendable_outputs(&commitment_tx, commitment_tx_conf_height_a).is_empty());
893         connect_blocks(&nodes[0], 1);
894         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
895                         amount_satoshis: 10_000,
896                         confirmation_height: node_a_htlc_claimable,
897                 }],
898                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
899         let to_self_spendable_output = test_spendable_output(&nodes[0], &commitment_tx, false);
900         assert_eq!(
901                 get_monitor!(nodes[0], chan_id).get_spendable_outputs(&commitment_tx, commitment_tx_conf_height_a),
902                 to_self_spendable_output
903         );
904
905         // Connect blocks until the HTLC-Timeout's CSV expires, providing us the relevant
906         // `SpendableOutputs` event and removing the claimable balance entry.
907         connect_blocks(&nodes[0], node_a_htlc_claimable - nodes[0].best_block_info().1);
908         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
909         test_spendable_output(&nodes[0], &timeout_htlc_txn[0], false);
910
911         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
912         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
913         // monitor events or claimable balances.
914         connect_blocks(&nodes[0], 6);
915         connect_blocks(&nodes[0], 6);
916         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
917         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
918 }
919
920 #[test]
921 fn test_balances_on_local_commitment_htlcs() {
922         do_test_balances_on_local_commitment_htlcs(false);
923         do_test_balances_on_local_commitment_htlcs(true);
924 }
925
926 #[test]
927 fn test_no_preimage_inbound_htlc_balances() {
928         // Tests that MaybePreimageClaimableHTLC are generated for inbound HTLCs for which we do not
929         // have a preimage.
930         let chanmon_cfgs = create_chanmon_cfgs(2);
931         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
932         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
933         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
934
935         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
936         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
937
938         // Send two HTLCs, one from A to B, and one from B to A.
939         let to_b_failed_payment_hash = route_payment(&nodes[0], &[&nodes[1]], 10_000_000).1;
940         let to_a_failed_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 20_000_000).1;
941         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
942
943         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
944         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_id);
945
946         let a_sent_htlc_balance = Balance::MaybeTimeoutClaimableHTLC {
947                 amount_satoshis: 10_000,
948                 claimable_height: htlc_cltv_timeout,
949                 payment_hash: to_b_failed_payment_hash,
950         };
951         let a_received_htlc_balance = Balance::MaybePreimageClaimableHTLC {
952                 amount_satoshis: 20_000,
953                 expiry_height: htlc_cltv_timeout,
954                 payment_hash: to_a_failed_payment_hash,
955         };
956         let b_received_htlc_balance = Balance::MaybePreimageClaimableHTLC {
957                 amount_satoshis: 10_000,
958                 expiry_height: htlc_cltv_timeout,
959                 payment_hash: to_b_failed_payment_hash,
960         };
961         let b_sent_htlc_balance = Balance::MaybeTimeoutClaimableHTLC {
962                 amount_satoshis: 20_000,
963                 claimable_height: htlc_cltv_timeout,
964                 payment_hash: to_a_failed_payment_hash,
965         };
966
967         // Both A and B will have an HTLC that's claimable on timeout and one that's claimable if they
968         // receive the preimage. These will remain the same through the channel closure and until the
969         // HTLC output is spent.
970
971         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
972                         amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
973                                 (channel::commitment_tx_base_weight(&channel_type_features) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
974                 }, a_received_htlc_balance.clone(), a_sent_htlc_balance.clone()]),
975                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
976
977         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
978                         amount_satoshis: 500_000 - 20_000,
979                 }, b_received_htlc_balance.clone(), b_sent_htlc_balance.clone()]),
980                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
981
982         // Get nodes[0]'s commitment transaction and HTLC-Timeout transaction
983         let as_txn = get_local_commitment_txn!(nodes[0], chan_id);
984         assert_eq!(as_txn.len(), 2);
985         check_spends!(as_txn[1], as_txn[0]);
986         check_spends!(as_txn[0], funding_tx);
987
988         // Now close the channel by confirming A's commitment transaction on both nodes, checking the
989         // claimable balances remain the same except for the non-HTLC balance changing variant.
990         let node_a_commitment_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
991         let as_pre_spend_claims = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
992                         amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
993                                 (channel::commitment_tx_base_weight(&channel_type_features) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
994                         confirmation_height: node_a_commitment_claimable,
995                 }, a_received_htlc_balance.clone(), a_sent_htlc_balance.clone()]);
996
997         mine_transaction(&nodes[0], &as_txn[0]);
998         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
999         check_added_monitors!(nodes[0], 1);
1000         check_closed_broadcast!(nodes[0], true);
1001         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
1002
1003         assert_eq!(as_pre_spend_claims,
1004                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1005
1006         mine_transaction(&nodes[1], &as_txn[0]);
1007         check_added_monitors!(nodes[1], 1);
1008         check_closed_broadcast!(nodes[1], true);
1009         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
1010
1011         let node_b_commitment_claimable = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1012         let mut bs_pre_spend_claims = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1013                         amount_satoshis: 500_000 - 20_000,
1014                         confirmation_height: node_b_commitment_claimable,
1015                 }, b_received_htlc_balance.clone(), b_sent_htlc_balance.clone()]);
1016         assert_eq!(bs_pre_spend_claims,
1017                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1018
1019         // We'll broadcast the HTLC-Timeout transaction one block prior to the htlc's expiration (as it
1020         // is confirmable in the next block), but will still include the same claimable balances as no
1021         // HTLC has been spent, even after the HTLC expires. We'll also fail the inbound HTLC, but it
1022         // won't do anything as the channel is already closed.
1023
1024         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
1025         let as_htlc_timeout_claim = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1026         assert_eq!(as_htlc_timeout_claim.len(), 1);
1027         check_spends!(as_htlc_timeout_claim[0], as_txn[0]);
1028         expect_pending_htlcs_forwardable_conditions!(nodes[0],
1029                 [HTLCDestination::FailedPayment { payment_hash: to_a_failed_payment_hash }]);
1030
1031         assert_eq!(as_pre_spend_claims,
1032                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1033
1034         connect_blocks(&nodes[0], 1);
1035         assert_eq!(as_pre_spend_claims,
1036                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1037
1038         // For node B, we'll get the non-HTLC funds claimable after ANTI_REORG_DELAY confirmations
1039         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
1040         test_spendable_output(&nodes[1], &as_txn[0], false);
1041         bs_pre_spend_claims.retain(|e| if let Balance::ClaimableAwaitingConfirmations { .. } = e { false } else { true });
1042
1043         // The next few blocks for B look the same as for A, though for the opposite HTLC
1044         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1045         connect_blocks(&nodes[1], TEST_FINAL_CLTV - (ANTI_REORG_DELAY - 1));
1046         expect_pending_htlcs_forwardable_conditions!(nodes[1],
1047                 [HTLCDestination::FailedPayment { payment_hash: to_b_failed_payment_hash }]);
1048         let bs_htlc_timeout_claim = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1049         assert_eq!(bs_htlc_timeout_claim.len(), 1);
1050         check_spends!(bs_htlc_timeout_claim[0], as_txn[0]);
1051
1052         assert_eq!(bs_pre_spend_claims,
1053                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1054
1055         connect_blocks(&nodes[1], 1);
1056         assert_eq!(bs_pre_spend_claims,
1057                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1058
1059         // Now confirm the two HTLC timeout transactions for A, checking that the inbound HTLC resolves
1060         // after ANTI_REORG_DELAY confirmations and the other takes BREAKDOWN_TIMEOUT confirmations.
1061         mine_transaction(&nodes[0], &as_htlc_timeout_claim[0]);
1062         let as_timeout_claimable_height = nodes[0].best_block_info().1 + (BREAKDOWN_TIMEOUT as u32) - 1;
1063         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1064                         amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
1065                                 (channel::commitment_tx_base_weight(&channel_type_features) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1066                         confirmation_height: node_a_commitment_claimable,
1067                 }, a_received_htlc_balance.clone(), Balance::ClaimableAwaitingConfirmations {
1068                         amount_satoshis: 10_000,
1069                         confirmation_height: as_timeout_claimable_height,
1070                 }]),
1071                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1072
1073         mine_transaction(&nodes[0], &bs_htlc_timeout_claim[0]);
1074         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1075                         amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
1076                                 (channel::commitment_tx_base_weight(&channel_type_features) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1077                         confirmation_height: node_a_commitment_claimable,
1078                 }, a_received_htlc_balance.clone(), Balance::ClaimableAwaitingConfirmations {
1079                         amount_satoshis: 10_000,
1080                         confirmation_height: as_timeout_claimable_height,
1081                 }]),
1082                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1083
1084         // Once as_htlc_timeout_claim[0] reaches ANTI_REORG_DELAY confirmations, we should get a
1085         // payment failure event.
1086         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
1087         expect_payment_failed!(nodes[0], to_b_failed_payment_hash, false);
1088
1089         connect_blocks(&nodes[0], 1);
1090         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1091                         amount_satoshis: 1_000_000 - 500_000 - 10_000 - chan_feerate *
1092                                 (channel::commitment_tx_base_weight(&channel_type_features) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
1093                         confirmation_height: node_a_commitment_claimable,
1094                 }, Balance::ClaimableAwaitingConfirmations {
1095                         amount_satoshis: 10_000,
1096                         confirmation_height: core::cmp::max(as_timeout_claimable_height, htlc_cltv_timeout),
1097                 }]),
1098                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1099
1100         connect_blocks(&nodes[0], node_a_commitment_claimable - nodes[0].best_block_info().1);
1101         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
1102                         amount_satoshis: 10_000,
1103                         confirmation_height: core::cmp::max(as_timeout_claimable_height, htlc_cltv_timeout),
1104                 }],
1105                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
1106         test_spendable_output(&nodes[0], &as_txn[0], false);
1107
1108         connect_blocks(&nodes[0], as_timeout_claimable_height - nodes[0].best_block_info().1);
1109         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1110         test_spendable_output(&nodes[0], &as_htlc_timeout_claim[0], false);
1111
1112         // The process for B should be completely identical as well, noting that the non-HTLC-balance
1113         // was already claimed.
1114         mine_transaction(&nodes[1], &bs_htlc_timeout_claim[0]);
1115         let bs_timeout_claimable_height = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1116         assert_eq!(sorted_vec(vec![b_received_htlc_balance.clone(), Balance::ClaimableAwaitingConfirmations {
1117                         amount_satoshis: 20_000,
1118                         confirmation_height: bs_timeout_claimable_height,
1119                 }]),
1120                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1121
1122         mine_transaction(&nodes[1], &as_htlc_timeout_claim[0]);
1123         assert_eq!(sorted_vec(vec![b_received_htlc_balance.clone(), Balance::ClaimableAwaitingConfirmations {
1124                         amount_satoshis: 20_000,
1125                         confirmation_height: bs_timeout_claimable_height,
1126                 }]),
1127                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1128
1129         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 2);
1130         expect_payment_failed!(nodes[1], to_a_failed_payment_hash, false);
1131
1132         assert_eq!(vec![b_received_htlc_balance.clone()],
1133                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
1134         test_spendable_output(&nodes[1], &bs_htlc_timeout_claim[0], false);
1135
1136         connect_blocks(&nodes[1], 1);
1137         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1138
1139         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
1140         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
1141         // monitor events or claimable balances.
1142         connect_blocks(&nodes[1], 6);
1143         connect_blocks(&nodes[1], 6);
1144         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1145         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1146 }
1147
1148 fn sorted_vec_with_additions<T: Ord + Clone>(v_orig: &Vec<T>, extra_ts: &[&T]) -> Vec<T> {
1149         let mut v = v_orig.clone();
1150         for t in extra_ts {
1151                 v.push((*t).clone());
1152         }
1153         v.sort_unstable();
1154         v
1155 }
1156
1157 fn do_test_revoked_counterparty_commitment_balances(anchors: bool, confirm_htlc_spend_first: bool) {
1158         // Tests `get_claimable_balances` for revoked counterparty commitment transactions.
1159         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1160         // We broadcast a second-to-latest commitment transaction, without providing the revocation
1161         // secret to the counterparty. However, because we always immediately take the revocation
1162         // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
1163         // transaction which, from the point of view of our keys_manager, is revoked.
1164         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
1165         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1166         let mut user_config = test_default_channel_config();
1167         if anchors {
1168                 user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
1169                 user_config.manually_accept_inbound_channels = true;
1170         }
1171         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config), Some(user_config)]);
1172         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1173
1174         let (_, _, chan_id, funding_tx) =
1175                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 100_000_000);
1176         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
1177         assert_eq!(ChannelId::v1_from_funding_outpoint(funding_outpoint), chan_id);
1178
1179         // We create five HTLCs for B to claim against A's revoked commitment transaction:
1180         //
1181         // (1) one for which A is the originator and B knows the preimage
1182         // (2) one for which B is the originator where the HTLC has since timed-out
1183         // (3) one for which B is the originator but where the HTLC has not yet timed-out
1184         // (4) one dust HTLC which is lost in the channel closure
1185         // (5) one that actually isn't in the revoked commitment transaction at all, but was added in
1186         //     later commitment transaction updates
1187         //
1188         // Though they could all be claimed in a single claim transaction, due to CLTV timeouts they
1189         // are all currently claimed in separate transactions, which helps us test as we can claim
1190         // HTLCs individually.
1191
1192         let (claimed_payment_preimage, claimed_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
1193         let timeout_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 4_000_000).1;
1194         let dust_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 3_000).1;
1195
1196         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1197
1198         connect_blocks(&nodes[0], 10);
1199         connect_blocks(&nodes[1], 10);
1200
1201         let live_htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1202         let live_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 5_000_000).1;
1203
1204         // Get the latest commitment transaction from A and then update the fee to revoke it
1205         let as_revoked_txn = get_local_commitment_txn!(nodes[0], chan_id);
1206         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_id);
1207
1208         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
1209
1210         let missing_htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1211         let missing_htlc_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 2_000_000).1;
1212
1213         nodes[1].node.claim_funds(claimed_payment_preimage);
1214         expect_payment_claimed!(nodes[1], claimed_payment_hash, 3_000_000);
1215         check_added_monitors!(nodes[1], 1);
1216         let _b_htlc_msgs = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
1217
1218         connect_blocks(&nodes[0], htlc_cltv_timeout + 1 - 10);
1219         check_closed_broadcast!(nodes[0], true);
1220         check_added_monitors!(nodes[0], 1);
1221
1222         let mut events = nodes[0].node.get_and_clear_pending_events();
1223         assert_eq!(events.len(), 6);
1224         let mut failed_payments: HashSet<_> =
1225                 [timeout_payment_hash, dust_payment_hash, live_payment_hash, missing_htlc_payment_hash]
1226                 .iter().map(|a| *a).collect();
1227         events.retain(|ev| {
1228                 match ev {
1229                         Event::HTLCHandlingFailed { failed_next_destination: HTLCDestination::NextHopChannel { node_id, channel_id }, .. } => {
1230                                 assert_eq!(*channel_id, chan_id);
1231                                 assert_eq!(*node_id, Some(nodes[1].node.get_our_node_id()));
1232                                 false
1233                         },
1234                         Event::HTLCHandlingFailed { failed_next_destination: HTLCDestination::FailedPayment { payment_hash }, .. } => {
1235                                 assert!(failed_payments.remove(payment_hash));
1236                                 false
1237                         },
1238                         _ => true,
1239                 }
1240         });
1241         assert!(failed_payments.is_empty());
1242         if let Event::PendingHTLCsForwardable { .. } = events[0] {} else { panic!(); }
1243         match &events[1] {
1244                 Event::ChannelClosed { reason: ClosureReason::HTLCsTimedOut, .. } => {},
1245                 _ => panic!(),
1246         }
1247
1248         connect_blocks(&nodes[1], htlc_cltv_timeout + 1 - 10);
1249         check_closed_broadcast!(nodes[1], true);
1250         check_added_monitors!(nodes[1], 1);
1251         check_closed_event!(nodes[1], 1, ClosureReason::HTLCsTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
1252
1253         // Prior to channel closure, B considers the preimage HTLC as its own, and otherwise only
1254         // lists the two on-chain timeout-able HTLCs as claimable balances.
1255         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
1256                         amount_satoshis: 100_000 - 5_000 - 4_000 - 3 - 2_000 + 3_000,
1257                 }, Balance::MaybeTimeoutClaimableHTLC {
1258                         amount_satoshis: 2_000,
1259                         claimable_height: missing_htlc_cltv_timeout,
1260                         payment_hash: missing_htlc_payment_hash,
1261                 }, Balance::MaybeTimeoutClaimableHTLC {
1262                         amount_satoshis: 4_000,
1263                         claimable_height: htlc_cltv_timeout,
1264                         payment_hash: timeout_payment_hash,
1265                 }, Balance::MaybeTimeoutClaimableHTLC {
1266                         amount_satoshis: 5_000,
1267                         claimable_height: live_htlc_cltv_timeout,
1268                         payment_hash: live_payment_hash,
1269                 }]),
1270                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1271
1272         mine_transaction(&nodes[1], &as_revoked_txn[0]);
1273         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();
1274         // Currently the revoked commitment is claimed in four transactions as the HTLCs all expire
1275         // quite soon.
1276         assert_eq!(claim_txn.len(), 4);
1277         claim_txn.sort_unstable_by_key(|tx| tx.output.iter().map(|output| output.value).sum::<u64>());
1278
1279         // The following constants were determined experimentally
1280         const BS_TO_SELF_CLAIM_EXP_WEIGHT: u64 = 483;
1281         let outbound_htlc_claim_exp_weight: u64 = if anchors { 574 } else { 571 };
1282         let inbound_htlc_claim_exp_weight: u64 = if anchors { 582 } else { 578 };
1283
1284         // Check that the weight is close to the expected weight. Note that signature sizes vary
1285         // somewhat so it may not always be exact.
1286         fuzzy_assert_eq(claim_txn[0].weight().to_wu(), outbound_htlc_claim_exp_weight);
1287         fuzzy_assert_eq(claim_txn[1].weight().to_wu(), inbound_htlc_claim_exp_weight);
1288         fuzzy_assert_eq(claim_txn[2].weight().to_wu(), inbound_htlc_claim_exp_weight);
1289         fuzzy_assert_eq(claim_txn[3].weight().to_wu(), BS_TO_SELF_CLAIM_EXP_WEIGHT);
1290
1291         let commitment_tx_fee = chan_feerate *
1292                 (channel::commitment_tx_base_weight(&channel_type_features) + 3 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
1293         let anchor_outputs_value = if anchors { channel::ANCHOR_OUTPUT_VALUE_SATOSHI * 2 } else { 0 };
1294         let inbound_htlc_claim_fee = chan_feerate * inbound_htlc_claim_exp_weight / 1000;
1295         let outbound_htlc_claim_fee = chan_feerate * outbound_htlc_claim_exp_weight / 1000;
1296         let to_self_claim_fee = chan_feerate * claim_txn[3].weight().to_wu() / 1000;
1297
1298         // The expected balance for the next three checks, with the largest-HTLC and to_self output
1299         // claim balances separated out.
1300         let expected_balance = vec![Balance::ClaimableAwaitingConfirmations {
1301                         // to_remote output in A's revoked commitment
1302                         amount_satoshis: 100_000 - 5_000 - 4_000 - 3,
1303                         confirmation_height: nodes[1].best_block_info().1 + 5,
1304                 }, Balance::CounterpartyRevokedOutputClaimable {
1305                         amount_satoshis: 3_000,
1306                 }, Balance::CounterpartyRevokedOutputClaimable {
1307                         amount_satoshis: 4_000,
1308                 }];
1309
1310         let to_self_unclaimed_balance = Balance::CounterpartyRevokedOutputClaimable {
1311                 amount_satoshis: 1_000_000 - 100_000 - 3_000 - commitment_tx_fee - anchor_outputs_value,
1312         };
1313         let to_self_claimed_avail_height;
1314         let largest_htlc_unclaimed_balance = Balance::CounterpartyRevokedOutputClaimable {
1315                 amount_satoshis: 5_000,
1316         };
1317         let largest_htlc_claimed_avail_height;
1318
1319         // Once the channel has been closed by A, B now considers all of the commitment transactions'
1320         // outputs as `CounterpartyRevokedOutputClaimable`.
1321         assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_unclaimed_balance, &largest_htlc_unclaimed_balance]),
1322                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1323
1324         if confirm_htlc_spend_first {
1325                 mine_transaction(&nodes[1], &claim_txn[2]);
1326                 largest_htlc_claimed_avail_height = nodes[1].best_block_info().1 + 5;
1327                 to_self_claimed_avail_height = nodes[1].best_block_info().1 + 6; // will be claimed in the next block
1328         } else {
1329                 // Connect the to_self output claim, taking all of A's non-HTLC funds
1330                 mine_transaction(&nodes[1], &claim_txn[3]);
1331                 to_self_claimed_avail_height = nodes[1].best_block_info().1 + 5;
1332                 largest_htlc_claimed_avail_height = nodes[1].best_block_info().1 + 6; // will be claimed in the next block
1333         }
1334
1335         let largest_htlc_claimed_balance = Balance::ClaimableAwaitingConfirmations {
1336                 amount_satoshis: 5_000 - inbound_htlc_claim_fee,
1337                 confirmation_height: largest_htlc_claimed_avail_height,
1338         };
1339         let to_self_claimed_balance = Balance::ClaimableAwaitingConfirmations {
1340                 amount_satoshis: 1_000_000 - 100_000 - 3_000 - commitment_tx_fee - anchor_outputs_value - to_self_claim_fee,
1341                 confirmation_height: to_self_claimed_avail_height,
1342         };
1343
1344         if confirm_htlc_spend_first {
1345                 assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_unclaimed_balance, &largest_htlc_claimed_balance]),
1346                         sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1347         } else {
1348                 assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_claimed_balance, &largest_htlc_unclaimed_balance]),
1349                         sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1350         }
1351
1352         if confirm_htlc_spend_first {
1353                 mine_transaction(&nodes[1], &claim_txn[3]);
1354         } else {
1355                 mine_transaction(&nodes[1], &claim_txn[2]);
1356         }
1357         assert_eq!(sorted_vec_with_additions(&expected_balance, &[&to_self_claimed_balance, &largest_htlc_claimed_balance]),
1358                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1359
1360         // Finally, connect the last two remaining HTLC spends and check that they move to
1361         // `ClaimableAwaitingConfirmations`
1362         mine_transaction(&nodes[1], &claim_txn[0]);
1363         mine_transaction(&nodes[1], &claim_txn[1]);
1364
1365         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1366                         // to_remote output in A's revoked commitment
1367                         amount_satoshis: 100_000 - 5_000 - 4_000 - 3,
1368                         confirmation_height: nodes[1].best_block_info().1 + 1,
1369                 }, Balance::ClaimableAwaitingConfirmations {
1370                         amount_satoshis: 1_000_000 - 100_000 - 3_000 - commitment_tx_fee - anchor_outputs_value - to_self_claim_fee,
1371                         confirmation_height: to_self_claimed_avail_height,
1372                 }, Balance::ClaimableAwaitingConfirmations {
1373                         amount_satoshis: 3_000 - outbound_htlc_claim_fee,
1374                         confirmation_height: nodes[1].best_block_info().1 + 4,
1375                 }, Balance::ClaimableAwaitingConfirmations {
1376                         amount_satoshis: 4_000 - inbound_htlc_claim_fee,
1377                         confirmation_height: nodes[1].best_block_info().1 + 5,
1378                 }, Balance::ClaimableAwaitingConfirmations {
1379                         amount_satoshis: 5_000 - inbound_htlc_claim_fee,
1380                         confirmation_height: largest_htlc_claimed_avail_height,
1381                 }]),
1382                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1383
1384         connect_blocks(&nodes[1], 1);
1385         test_spendable_output(&nodes[1], &as_revoked_txn[0], false);
1386
1387         let mut payment_failed_events = nodes[1].node.get_and_clear_pending_events();
1388         expect_payment_failed_conditions_event(payment_failed_events[..2].to_vec(),
1389                 missing_htlc_payment_hash, false, PaymentFailedConditions::new());
1390         expect_payment_failed_conditions_event(payment_failed_events[2..].to_vec(),
1391                 dust_payment_hash, false, PaymentFailedConditions::new());
1392
1393         connect_blocks(&nodes[1], 1);
1394         test_spendable_output(&nodes[1], &claim_txn[if confirm_htlc_spend_first { 2 } else { 3 }], false);
1395         connect_blocks(&nodes[1], 1);
1396         test_spendable_output(&nodes[1], &claim_txn[if confirm_htlc_spend_first { 3 } else { 2 }], false);
1397         expect_payment_failed!(nodes[1], live_payment_hash, false);
1398         connect_blocks(&nodes[1], 1);
1399         test_spendable_output(&nodes[1], &claim_txn[0], false);
1400         connect_blocks(&nodes[1], 1);
1401         test_spendable_output(&nodes[1], &claim_txn[1], false);
1402         expect_payment_failed!(nodes[1], timeout_payment_hash, false);
1403         assert_eq!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances(), Vec::new());
1404
1405         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
1406         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
1407         // monitor events or claimable balances.
1408         connect_blocks(&nodes[1], 6);
1409         connect_blocks(&nodes[1], 6);
1410         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1411         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1412 }
1413
1414 #[test]
1415 fn test_revoked_counterparty_commitment_balances() {
1416         do_test_revoked_counterparty_commitment_balances(false, true);
1417         do_test_revoked_counterparty_commitment_balances(false, false);
1418         do_test_revoked_counterparty_commitment_balances(true, true);
1419         do_test_revoked_counterparty_commitment_balances(true, false);
1420 }
1421
1422 fn do_test_revoked_counterparty_htlc_tx_balances(anchors: bool) {
1423         // Tests `get_claimable_balances` for revocation spends of HTLC transactions.
1424         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1425         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
1426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1427         let mut user_config = test_default_channel_config();
1428         if anchors {
1429                 user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
1430                 user_config.manually_accept_inbound_channels = true;
1431         }
1432         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config), Some(user_config)]);
1433         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1434
1435         let coinbase_tx = Transaction {
1436                 version: 2,
1437                 lock_time: LockTime::ZERO,
1438                 input: vec![TxIn { ..Default::default() }],
1439                 output: vec![
1440                         TxOut {
1441                                 value: Amount::ONE_BTC.to_sat(),
1442                                 script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
1443                         },
1444                         TxOut {
1445                                 value: Amount::ONE_BTC.to_sat(),
1446                                 script_pubkey: nodes[1].wallet_source.get_change_script().unwrap(),
1447                         },
1448                 ],
1449         };
1450         if anchors {
1451                 nodes[0].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 }, coinbase_tx.output[0].value);
1452                 nodes[1].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 1 }, coinbase_tx.output[1].value);
1453         }
1454
1455         // Create some initial channels
1456         let (_, _, chan_id, funding_tx) =
1457                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 12_000_000);
1458         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
1459         assert_eq!(ChannelId::v1_from_funding_outpoint(funding_outpoint), chan_id);
1460
1461         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
1462         let failed_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 1_000_000).1;
1463         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_id);
1464         assert_eq!(revoked_local_txn[0].input.len(), 1);
1465         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, funding_tx.txid());
1466         if anchors {
1467                 assert_eq!(revoked_local_txn[0].output[4].value, 11000); // to_self output
1468         } else {
1469                 assert_eq!(revoked_local_txn[0].output[2].value, 11000); // to_self output
1470         }
1471
1472         // The to-be-revoked commitment tx should have two HTLCs, an output for each side, and an
1473         // anchor output for each side if enabled.
1474         assert_eq!(revoked_local_txn[0].output.len(), if anchors { 6 } else { 4 });
1475
1476         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
1477
1478         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
1479         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_id);
1480
1481         // B will generate an HTLC-Success from its revoked commitment tx
1482         mine_transaction(&nodes[1], &revoked_local_txn[0]);
1483         check_closed_broadcast!(nodes[1], true);
1484         check_added_monitors!(nodes[1], 1);
1485         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
1486         if anchors {
1487                 handle_bump_htlc_event(&nodes[1], 1);
1488         }
1489         let revoked_htlc_success = {
1490                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
1491                 assert_eq!(txn.len(), 1);
1492                 assert_eq!(txn[0].input.len(), if anchors { 2 } else { 1 });
1493                 assert_eq!(txn[0].input[0].previous_output.vout, if anchors { 3 } else { 1 });
1494                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(),
1495                         if anchors { ACCEPTED_HTLC_SCRIPT_WEIGHT_ANCHORS } else { ACCEPTED_HTLC_SCRIPT_WEIGHT });
1496                 check_spends!(txn[0], revoked_local_txn[0], coinbase_tx);
1497                 txn.pop().unwrap()
1498         };
1499         let revoked_htlc_success_fee = chan_feerate * revoked_htlc_success.weight().to_wu() / 1000;
1500
1501         connect_blocks(&nodes[1], TEST_FINAL_CLTV);
1502         if anchors {
1503                 handle_bump_htlc_event(&nodes[1], 2);
1504         }
1505         let revoked_htlc_timeout = {
1506                 let mut txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
1507                 assert_eq!(txn.len(), 2);
1508                 if txn[0].input[0].previous_output == revoked_htlc_success.input[0].previous_output {
1509                         txn.remove(1)
1510                 } else {
1511                         txn.remove(0)
1512                 }
1513         };
1514         check_spends!(revoked_htlc_timeout, revoked_local_txn[0], coinbase_tx);
1515         assert_ne!(revoked_htlc_success.input[0].previous_output, revoked_htlc_timeout.input[0].previous_output);
1516         assert_eq!(revoked_htlc_success.lock_time, LockTime::ZERO);
1517         assert_ne!(revoked_htlc_timeout.lock_time, LockTime::ZERO);
1518
1519         // A will generate justice tx from B's revoked commitment/HTLC tx
1520         mine_transaction(&nodes[0], &revoked_local_txn[0]);
1521         check_closed_broadcast!(nodes[0], true);
1522         check_added_monitors!(nodes[0], 1);
1523         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
1524         let to_remote_conf_height = nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1;
1525
1526         let revoked_to_self_claim = {
1527                 let mut as_commitment_claim_txn = nodes[0].tx_broadcaster.txn_broadcast();
1528                 assert_eq!(as_commitment_claim_txn.len(), if anchors { 2 } else { 1 });
1529                 if anchors {
1530                         assert_eq!(as_commitment_claim_txn[0].input.len(), 1);
1531                         assert_eq!(as_commitment_claim_txn[0].input[0].previous_output.vout, 4); // Separate to_remote claim
1532                         check_spends!(as_commitment_claim_txn[0], revoked_local_txn[0]);
1533                         assert_eq!(as_commitment_claim_txn[1].input.len(), 2);
1534                         assert_eq!(as_commitment_claim_txn[1].input[0].previous_output.vout, 2);
1535                         assert_eq!(as_commitment_claim_txn[1].input[1].previous_output.vout, 3);
1536                         check_spends!(as_commitment_claim_txn[1], revoked_local_txn[0]);
1537                         Some(as_commitment_claim_txn.remove(0))
1538                 } else {
1539                         assert_eq!(as_commitment_claim_txn[0].input.len(), 3);
1540                         assert_eq!(as_commitment_claim_txn[0].input[0].previous_output.vout, 2);
1541                         assert_eq!(as_commitment_claim_txn[0].input[1].previous_output.vout, 0);
1542                         assert_eq!(as_commitment_claim_txn[0].input[2].previous_output.vout, 1);
1543                         check_spends!(as_commitment_claim_txn[0], revoked_local_txn[0]);
1544                         None
1545                 }
1546         };
1547
1548         // The next two checks have the same balance set for A - even though we confirm a revoked HTLC
1549         // transaction our balance tracking doesn't use the on-chain value so the
1550         // `CounterpartyRevokedOutputClaimable` entry doesn't change.
1551         let commitment_tx_fee = chan_feerate *
1552                 (channel::commitment_tx_base_weight(&channel_type_features) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
1553         let anchor_outputs_value = if anchors { channel::ANCHOR_OUTPUT_VALUE_SATOSHI * 2 } else { 0 };
1554         let as_balances = sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1555                         // to_remote output in B's revoked commitment
1556                         amount_satoshis: 1_000_000 - 12_000 - 3_000 - commitment_tx_fee - anchor_outputs_value,
1557                         confirmation_height: to_remote_conf_height,
1558                 }, Balance::CounterpartyRevokedOutputClaimable {
1559                         // to_self output in B's revoked commitment
1560                         amount_satoshis: 11_000,
1561                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1562                         amount_satoshis: 3_000,
1563                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1564                         amount_satoshis: 1_000,
1565                 }]);
1566         assert_eq!(as_balances,
1567                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1568
1569         mine_transaction(&nodes[0], &revoked_htlc_success);
1570         let as_htlc_claim_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1571         assert_eq!(as_htlc_claim_tx.len(), 2);
1572         assert_eq!(as_htlc_claim_tx[0].input.len(), 1);
1573         check_spends!(as_htlc_claim_tx[0], revoked_htlc_success);
1574         // A has to generate a new claim for the remaining revoked outputs (which no longer includes the
1575         // spent HTLC output)
1576         assert_eq!(as_htlc_claim_tx[1].input.len(), if anchors { 1 } else { 2 });
1577         assert_eq!(as_htlc_claim_tx[1].input[0].previous_output.vout, 2);
1578         if !anchors {
1579                 assert_eq!(as_htlc_claim_tx[1].input[1].previous_output.vout, 0);
1580         }
1581         check_spends!(as_htlc_claim_tx[1], revoked_local_txn[0]);
1582
1583         assert_eq!(as_balances,
1584                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1585
1586         assert_eq!(as_htlc_claim_tx[0].output.len(), 1);
1587         let as_revoked_htlc_success_claim_fee = chan_feerate * as_htlc_claim_tx[0].weight().to_wu() / 1000;
1588         if anchors {
1589                 // With anchors, B can pay for revoked_htlc_success's fee with additional inputs, rather
1590                 // than with the HTLC itself.
1591                 fuzzy_assert_eq(as_htlc_claim_tx[0].output[0].value,
1592                         3_000 - as_revoked_htlc_success_claim_fee);
1593         } else {
1594                 fuzzy_assert_eq(as_htlc_claim_tx[0].output[0].value,
1595                         3_000 - revoked_htlc_success_fee - as_revoked_htlc_success_claim_fee);
1596         }
1597
1598         mine_transaction(&nodes[0], &as_htlc_claim_tx[0]);
1599         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1600                         // to_remote output in B's revoked commitment
1601                         amount_satoshis: 1_000_000 - 12_000 - 3_000 - commitment_tx_fee - anchor_outputs_value,
1602                         confirmation_height: to_remote_conf_height,
1603                 }, Balance::CounterpartyRevokedOutputClaimable {
1604                         // to_self output in B's revoked commitment
1605                         amount_satoshis: 11_000,
1606                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1607                         amount_satoshis: 1_000,
1608                 }, Balance::ClaimableAwaitingConfirmations {
1609                         amount_satoshis: as_htlc_claim_tx[0].output[0].value,
1610                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
1611                 }]),
1612                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1613
1614         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 3);
1615         test_spendable_output(&nodes[0], &revoked_local_txn[0], false);
1616         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1617                         // to_self output to B
1618                         amount_satoshis: 11_000,
1619                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1620                         amount_satoshis: 1_000,
1621                 }, Balance::ClaimableAwaitingConfirmations {
1622                         amount_satoshis: as_htlc_claim_tx[0].output[0].value,
1623                         confirmation_height: nodes[0].best_block_info().1 + 2,
1624                 }]),
1625                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1626
1627         connect_blocks(&nodes[0], 2);
1628         test_spendable_output(&nodes[0], &as_htlc_claim_tx[0], false);
1629         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1630                         // to_self output in B's revoked commitment
1631                         amount_satoshis: 11_000,
1632                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1633                         amount_satoshis: 1_000,
1634                 }]),
1635                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1636
1637         connect_blocks(&nodes[0], revoked_htlc_timeout.lock_time.to_consensus_u32() - nodes[0].best_block_info().1);
1638         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(&nodes[0],
1639                 [HTLCDestination::FailedPayment { payment_hash: failed_payment_hash }]);
1640         // As time goes on A may split its revocation claim transaction into multiple.
1641         let as_fewer_input_rbf = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1642         for tx in as_fewer_input_rbf.iter() {
1643                 check_spends!(tx, revoked_local_txn[0]);
1644         }
1645
1646         // Connect a number of additional blocks to ensure we don't forget the HTLC output needs
1647         // claiming.
1648         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
1649         let as_fewer_input_rbf = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1650         for tx in as_fewer_input_rbf.iter() {
1651                 check_spends!(tx, revoked_local_txn[0]);
1652         }
1653
1654         mine_transaction(&nodes[0], &revoked_htlc_timeout);
1655         let (revoked_htlc_timeout_claim, revoked_to_self_claim) = {
1656                 let mut as_second_htlc_claim_tx = nodes[0].tx_broadcaster.txn_broadcast();
1657                 assert_eq!(as_second_htlc_claim_tx.len(), if anchors { 1 } else { 2 });
1658                 if anchors {
1659                         assert_eq!(as_second_htlc_claim_tx[0].input.len(), 1);
1660                         assert_eq!(as_second_htlc_claim_tx[0].input[0].previous_output.vout, 0);
1661                         check_spends!(as_second_htlc_claim_tx[0], revoked_htlc_timeout);
1662                         (as_second_htlc_claim_tx.remove(0), revoked_to_self_claim.unwrap())
1663                 } else {
1664                         assert_eq!(as_second_htlc_claim_tx[0].input.len(), 1);
1665                         assert_eq!(as_second_htlc_claim_tx[0].input[0].previous_output.vout, 0);
1666                         check_spends!(as_second_htlc_claim_tx[0], revoked_htlc_timeout);
1667                         assert_eq!(as_second_htlc_claim_tx[1].input.len(), 1);
1668                         assert_eq!(as_second_htlc_claim_tx[1].input[0].previous_output.vout, 2);
1669                         check_spends!(as_second_htlc_claim_tx[1], revoked_local_txn[0]);
1670                         (as_second_htlc_claim_tx.remove(0), as_second_htlc_claim_tx.remove(0))
1671                 }
1672         };
1673
1674         // Connect blocks to finalize the HTLC resolution with the HTLC-Timeout transaction. In a
1675         // previous iteration of the revoked balance handling this would result in us "forgetting" that
1676         // the revoked HTLC output still needed to be claimed.
1677         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
1678         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1679                         // to_self output in B's revoked commitment
1680                         amount_satoshis: 11_000,
1681                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1682                         amount_satoshis: 1_000,
1683                 }]),
1684                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1685
1686         mine_transaction(&nodes[0], &revoked_htlc_timeout_claim);
1687         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1688                         // to_self output in B's revoked commitment
1689                         amount_satoshis: 11_000,
1690                 }, Balance::ClaimableAwaitingConfirmations {
1691                         amount_satoshis: revoked_htlc_timeout_claim.output[0].value,
1692                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
1693                 }]),
1694                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1695
1696         mine_transaction(&nodes[0], &revoked_to_self_claim);
1697         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1698                         // to_self output in B's revoked commitment
1699                         amount_satoshis: revoked_to_self_claim.output[0].value,
1700                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
1701                 }, Balance::ClaimableAwaitingConfirmations {
1702                         amount_satoshis: revoked_htlc_timeout_claim.output[0].value,
1703                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 2,
1704                 }]),
1705                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1706
1707         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
1708         test_spendable_output(&nodes[0], &revoked_htlc_timeout_claim, false);
1709         connect_blocks(&nodes[0], 1);
1710         test_spendable_output(&nodes[0], &revoked_to_self_claim, false);
1711
1712         assert_eq!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances(), Vec::new());
1713
1714         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
1715         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
1716         // monitor events or claimable balances.
1717         connect_blocks(&nodes[0], 6);
1718         connect_blocks(&nodes[0], 6);
1719         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
1720         assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
1721 }
1722
1723 #[test]
1724 fn test_revoked_counterparty_htlc_tx_balances() {
1725         do_test_revoked_counterparty_htlc_tx_balances(false);
1726         do_test_revoked_counterparty_htlc_tx_balances(true);
1727 }
1728
1729 fn do_test_revoked_counterparty_aggregated_claims(anchors: bool) {
1730         // Tests `get_claimable_balances` for revoked counterparty commitment transactions when
1731         // claiming with an aggregated claim transaction.
1732         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1733         // We broadcast a second-to-latest commitment transaction, without providing the revocation
1734         // secret to the counterparty. However, because we always immediately take the revocation
1735         // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
1736         // transaction which, from the point of view of our keys_manager, is revoked.
1737         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
1738         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1739         let mut user_config = test_default_channel_config();
1740         if anchors {
1741                 user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
1742                 user_config.manually_accept_inbound_channels = true;
1743         }
1744         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config), Some(user_config)]);
1745         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1746
1747         let coinbase_tx = Transaction {
1748                 version: 2,
1749                 lock_time: LockTime::ZERO,
1750                 input: vec![TxIn { ..Default::default() }],
1751                 output: vec![TxOut {
1752                         value: Amount::ONE_BTC.to_sat(),
1753                         script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
1754                 }],
1755         };
1756         nodes[0].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 }, coinbase_tx.output[0].value);
1757
1758         let (_, _, chan_id, funding_tx) =
1759                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 100_000_000);
1760         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
1761         assert_eq!(ChannelId::v1_from_funding_outpoint(funding_outpoint), chan_id);
1762
1763         // We create two HTLCs, one which we will give A the preimage to to generate an HTLC-Success
1764         // transaction, and one which we will not, allowing B to claim the HTLC output in an aggregated
1765         // revocation-claim transaction.
1766
1767         let (claimed_payment_preimage, claimed_payment_hash, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
1768         let revoked_payment_hash = route_payment(&nodes[1], &[&nodes[0]], 4_000_000).1;
1769
1770         let htlc_cltv_timeout = nodes[1].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
1771
1772         // Cheat by giving A's ChannelMonitor the preimage to the to-be-claimed HTLC so that we have an
1773         // HTLC-claim transaction on the to-be-revoked state.
1774         get_monitor!(nodes[0], chan_id).provide_payment_preimage(&claimed_payment_hash, &claimed_payment_preimage,
1775                 &node_cfgs[0].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[0].fee_estimator), &nodes[0].logger);
1776
1777         // Now get the latest commitment transaction from A and then update the fee to revoke it
1778         let as_revoked_txn = get_local_commitment_txn!(nodes[0], chan_id);
1779
1780         assert_eq!(as_revoked_txn.len(), if anchors { 1 } else { 2 });
1781         check_spends!(as_revoked_txn[0], funding_tx);
1782         if !anchors {
1783                 check_spends!(as_revoked_txn[1], as_revoked_txn[0]); // The HTLC-Claim transaction
1784         }
1785
1786         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_id);
1787         let chan_feerate = get_feerate!(nodes[0], nodes[1], chan_id) as u64;
1788
1789         {
1790                 let mut feerate = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1791                 *feerate += 1;
1792         }
1793         nodes[0].node.timer_tick_occurred();
1794         check_added_monitors!(nodes[0], 1);
1795
1796         let fee_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1797         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &fee_update.update_fee.unwrap());
1798         commitment_signed_dance!(nodes[1], nodes[0], fee_update.commitment_signed, false);
1799
1800         nodes[0].node.claim_funds(claimed_payment_preimage);
1801         expect_payment_claimed!(nodes[0], claimed_payment_hash, 3_000_000);
1802         check_added_monitors!(nodes[0], 1);
1803         let _a_htlc_msgs = get_htlc_update_msgs!(&nodes[0], nodes[1].node.get_our_node_id());
1804
1805         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
1806                         amount_satoshis: 100_000 - 4_000 - 3_000,
1807                 }, Balance::MaybeTimeoutClaimableHTLC {
1808                         amount_satoshis: 4_000,
1809                         claimable_height: htlc_cltv_timeout,
1810                         payment_hash: revoked_payment_hash,
1811                 }, Balance::MaybeTimeoutClaimableHTLC {
1812                         amount_satoshis: 3_000,
1813                         claimable_height: htlc_cltv_timeout,
1814                         payment_hash: claimed_payment_hash,
1815                 }]),
1816                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1817
1818         mine_transaction(&nodes[1], &as_revoked_txn[0]);
1819         check_closed_broadcast!(nodes[1], true);
1820         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
1821         check_added_monitors!(nodes[1], 1);
1822
1823         let mut claim_txn = nodes[1].tx_broadcaster.txn_broadcast();
1824         assert_eq!(claim_txn.len(), if anchors { 2 } else { 1 });
1825         let revoked_to_self_claim = if anchors {
1826                 assert_eq!(claim_txn[0].input.len(), 1);
1827                 assert_eq!(claim_txn[0].input[0].previous_output.vout, 5); // Separate to_remote claim
1828                 check_spends!(claim_txn[0], as_revoked_txn[0]);
1829                 assert_eq!(claim_txn[1].input.len(), 2);
1830                 assert_eq!(claim_txn[1].input[0].previous_output.vout, 2);
1831                 assert_eq!(claim_txn[1].input[1].previous_output.vout, 3);
1832                 check_spends!(claim_txn[1], as_revoked_txn[0]);
1833                 Some(claim_txn.remove(0))
1834         } else {
1835                 assert_eq!(claim_txn[0].input.len(), 3);
1836                 assert_eq!(claim_txn[0].input[0].previous_output.vout, 3);
1837                 assert_eq!(claim_txn[0].input[1].previous_output.vout, 0);
1838                 assert_eq!(claim_txn[0].input[2].previous_output.vout, 1);
1839                 check_spends!(claim_txn[0], as_revoked_txn[0]);
1840                 None
1841         };
1842
1843         let to_remote_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1844
1845         let commitment_tx_fee = chan_feerate *
1846                 (channel::commitment_tx_base_weight(&channel_type_features) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
1847         let anchor_outputs_value = if anchors { channel::ANCHOR_OUTPUT_VALUE_SATOSHI * 2 } else { 0 };
1848         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1849                         // to_remote output in A's revoked commitment
1850                         amount_satoshis: 100_000 - 4_000 - 3_000,
1851                         confirmation_height: to_remote_maturity,
1852                 }, Balance::CounterpartyRevokedOutputClaimable {
1853                         // to_self output in A's revoked commitment
1854                         amount_satoshis: 1_000_000 - 100_000 - commitment_tx_fee - anchor_outputs_value,
1855                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1856                         amount_satoshis: 4_000,
1857                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1858                         amount_satoshis: 3_000,
1859                 }]),
1860                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1861
1862         // Confirm A's HTLC-Success transaction which presumably raced B's claim, causing B to create a
1863         // new claim.
1864         if anchors {
1865                 mine_transaction(&nodes[0], &as_revoked_txn[0]);
1866                 check_closed_broadcast(&nodes[0], 1, true);
1867                 check_added_monitors(&nodes[0], 1);
1868                 check_closed_event!(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false, [nodes[1].node.get_our_node_id()], 1_000_000);
1869                 handle_bump_htlc_event(&nodes[0], 1);
1870         }
1871         let htlc_success_claim = if anchors {
1872                 let mut txn = nodes[0].tx_broadcaster.txn_broadcast();
1873                 assert_eq!(txn.len(), 1);
1874                 check_spends!(txn[0], as_revoked_txn[0], coinbase_tx);
1875                 txn.pop().unwrap()
1876         } else {
1877                 as_revoked_txn[1].clone()
1878         };
1879         mine_transaction(&nodes[1], &htlc_success_claim);
1880         expect_payment_sent(&nodes[1], claimed_payment_preimage, None, true, false);
1881
1882         let mut claim_txn_2 = nodes[1].tx_broadcaster.txn_broadcast();
1883         // Once B sees the HTLC-Success transaction it splits its claim transaction into two, though in
1884         // theory it could re-aggregate the claims as well.
1885         assert_eq!(claim_txn_2.len(), 2);
1886         if anchors {
1887                 assert_eq!(claim_txn_2[0].input.len(), 1);
1888                 assert_eq!(claim_txn_2[0].input[0].previous_output.vout, 0);
1889                 check_spends!(claim_txn_2[0], &htlc_success_claim);
1890                 assert_eq!(claim_txn_2[1].input.len(), 1);
1891                 assert_eq!(claim_txn_2[1].input[0].previous_output.vout, 3);
1892                 check_spends!(claim_txn_2[1], as_revoked_txn[0]);
1893         } else {
1894                 assert_eq!(claim_txn_2[0].input.len(), 1);
1895                 assert_eq!(claim_txn_2[0].input[0].previous_output.vout, 0);
1896                 check_spends!(claim_txn_2[0], as_revoked_txn[1]);
1897                 assert_eq!(claim_txn_2[1].input.len(), 2);
1898                 assert_eq!(claim_txn_2[1].input[0].previous_output.vout, 3);
1899                 assert_eq!(claim_txn_2[1].input[1].previous_output.vout, 1);
1900                 check_spends!(claim_txn_2[1], as_revoked_txn[0]);
1901         }
1902
1903         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
1904                         // to_remote output in A's revoked commitment
1905                         amount_satoshis: 100_000 - 4_000 - 3_000,
1906                         confirmation_height: to_remote_maturity,
1907                 }, Balance::CounterpartyRevokedOutputClaimable {
1908                         // to_self output in A's revoked commitment
1909                         amount_satoshis: 1_000_000 - 100_000 - commitment_tx_fee - anchor_outputs_value,
1910                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1911                         amount_satoshis: 4_000,
1912                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1913                         // The amount here is a bit of a misnomer, really its been reduced by the HTLC
1914                         // transaction fee, but the claimable amount is always a bit of an overshoot for HTLCs
1915                         // anyway, so its not a big change.
1916                         amount_satoshis: 3_000,
1917                 }]),
1918                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1919
1920         connect_blocks(&nodes[1], 5);
1921         test_spendable_output(&nodes[1], &as_revoked_txn[0], false);
1922
1923         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1924                         // to_self output in A's revoked commitment
1925                         amount_satoshis: 1_000_000 - 100_000 - commitment_tx_fee - anchor_outputs_value,
1926                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1927                         amount_satoshis: 4_000,
1928                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 2
1929                         // The amount here is a bit of a misnomer, really its been reduced by the HTLC
1930                         // transaction fee, but the claimable amount is always a bit of an overshoot for HTLCs
1931                         // anyway, so its not a big change.
1932                         amount_satoshis: 3_000,
1933                 }]),
1934                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1935
1936         mine_transaction(&nodes[1], &claim_txn_2[0]);
1937         let htlc_2_claim_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1938
1939         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1940                         // to_self output in A's revoked commitment
1941                         amount_satoshis: 1_000_000 - 100_000 - commitment_tx_fee - anchor_outputs_value,
1942                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1943                         amount_satoshis: 4_000,
1944                 }, Balance::ClaimableAwaitingConfirmations { // HTLC 2
1945                         amount_satoshis: claim_txn_2[0].output[0].value,
1946                         confirmation_height: htlc_2_claim_maturity,
1947                 }]),
1948                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1949
1950         connect_blocks(&nodes[1], 5);
1951         test_spendable_output(&nodes[1], &claim_txn_2[0], false);
1952
1953         assert_eq!(sorted_vec(vec![Balance::CounterpartyRevokedOutputClaimable {
1954                         // to_self output in A's revoked commitment
1955                         amount_satoshis: 1_000_000 - 100_000 - commitment_tx_fee - anchor_outputs_value,
1956                 }, Balance::CounterpartyRevokedOutputClaimable { // HTLC 1
1957                         amount_satoshis: 4_000,
1958                 }]),
1959                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
1960
1961         if anchors {
1962                 mine_transactions(&nodes[1], &[&claim_txn_2[1], revoked_to_self_claim.as_ref().unwrap()]);
1963         } else {
1964                 mine_transaction(&nodes[1], &claim_txn_2[1]);
1965         }
1966         let rest_claim_maturity = nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1;
1967
1968         if anchors {
1969                 assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
1970                                 amount_satoshis: claim_txn_2[1].output[0].value,
1971                                 confirmation_height: rest_claim_maturity,
1972                         }, Balance::ClaimableAwaitingConfirmations {
1973                                 amount_satoshis: revoked_to_self_claim.as_ref().unwrap().output[0].value,
1974                                 confirmation_height: rest_claim_maturity,
1975                         }],
1976                         nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
1977         } else {
1978                 assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
1979                                 amount_satoshis: claim_txn_2[1].output[0].value,
1980                                 confirmation_height: rest_claim_maturity,
1981                         }],
1982                         nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
1983         }
1984
1985         assert!(nodes[1].node.get_and_clear_pending_events().is_empty()); // We shouldn't fail the payment until we spend the output
1986
1987         connect_blocks(&nodes[1], 5);
1988         expect_payment_failed!(nodes[1], revoked_payment_hash, false);
1989         if anchors {
1990                 let events = nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events();
1991                 assert_eq!(events.len(), 2);
1992                 for (i, event) in events.into_iter().enumerate() {
1993                         if let Event::SpendableOutputs { outputs, .. } = event {
1994                                 assert_eq!(outputs.len(), 1);
1995                                 let spend_tx = nodes[1].keys_manager.backing.spend_spendable_outputs(
1996                                         &[&outputs[0]], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
1997                                         253, None, &Secp256k1::new()
1998                                 ).unwrap();
1999                                 check_spends!(spend_tx, if i == 0 { &claim_txn_2[1] } else { revoked_to_self_claim.as_ref().unwrap() });
2000                         } else { panic!(); }
2001                 }
2002         } else {
2003                 test_spendable_output(&nodes[1], &claim_txn_2[1], false);
2004         }
2005         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
2006
2007         // Ensure that even if we connect more blocks, potentially replaying the entire chain if we're
2008         // using `ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks`, we don't get new
2009         // monitor events or claimable balances.
2010         connect_blocks(&nodes[1], 6);
2011         connect_blocks(&nodes[1], 6);
2012         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2013         assert!(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
2014 }
2015
2016 #[test]
2017 fn test_revoked_counterparty_aggregated_claims() {
2018         do_test_revoked_counterparty_aggregated_claims(false);
2019         do_test_revoked_counterparty_aggregated_claims(true);
2020 }
2021
2022 fn do_test_restored_packages_retry(check_old_monitor_retries_after_upgrade: bool) {
2023         // Tests that we'll retry packages that were previously timelocked after we've restored them.
2024         let chanmon_cfgs = create_chanmon_cfgs(2);
2025         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2026         let persister;
2027         let new_chain_monitor;
2028
2029         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2030         let node_deserialized;
2031
2032         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2033
2034         // Open a channel, lock in an HTLC, and immediately broadcast the commitment transaction. This
2035         // ensures that the HTLC timeout package is held until we reach its expiration height.
2036         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 50_000_000);
2037         route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
2038
2039         nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
2040         check_added_monitors(&nodes[0], 1);
2041         check_closed_broadcast(&nodes[0], 1, true);
2042         check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
2043                  [nodes[1].node.get_our_node_id()], 100000);
2044
2045         let commitment_tx = {
2046                 let mut txn = nodes[0].tx_broadcaster.txn_broadcast();
2047                 assert_eq!(txn.len(), 1);
2048                 assert_eq!(txn[0].output.len(), 3);
2049                 check_spends!(txn[0], funding_tx);
2050                 txn.pop().unwrap()
2051         };
2052
2053         mine_transaction(&nodes[0], &commitment_tx);
2054         if nodes[0].connect_style.borrow().updates_best_block_first() {
2055                 let txn = nodes[0].tx_broadcaster.txn_broadcast();
2056                 assert_eq!(txn.len(), 1);
2057                 assert_eq!(txn[0].txid(), commitment_tx.txid());
2058         }
2059
2060         // Connect blocks until the HTLC's expiration is met, expecting a transaction broadcast.
2061         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
2062         let htlc_timeout_tx = {
2063                 let mut txn = nodes[0].tx_broadcaster.txn_broadcast();
2064                 assert_eq!(txn.len(), 1);
2065                 check_spends!(txn[0], commitment_tx);
2066                 txn.pop().unwrap()
2067         };
2068
2069         // Check that we can still rebroadcast these packages/transactions if we're upgrading from an
2070         // old `ChannelMonitor` that did not exercise said rebroadcasting logic.
2071         if check_old_monitor_retries_after_upgrade {
2072                 let serialized_monitor = <Vec<u8>>::from_hex(
2073                         "0101fffffffffffffffff9550f22c95100160014d5a9aa98b89acc215fc3d23d6fec0ad59ca3665f00002200204c5f18e5e95b184f34d02ba6de8a2a4e36ae3d4ec87299ad81f3284dc7195c6302d7dde8e10a5a22c9bd0d7ef5494d85683ac050253b917615d4f97af633f0a8e2035f5e9d58b4328566223c107d86cf853e6b9fae1d26ff6d969be0178d1423c4ea0016001467822698d782e8421ebdf96d010de99382b7ec2300160014caf6d80fe2bab80473b021f57588a9c384bf23170000000000000000000000004d49e5da0000000000000000000000000000002a0270b20ad0f2c2bb30a55590fc77778495bc1b38c96476901145dda57491237f0f74c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e00000022002034c0cc0ad0dd5fe61dcf7ef58f995e3d34f8dbd24aa2a6fae68fefe102bf025c21391732ce658e1fe167300bb689a81e7db5399b9ee4095e217b0e997e8dd3d17a0000000000000000004a002103adde8029d3ee281a32e9db929b39f503ff9d7e93cd308eb157955344dc6def84022103205087e2dc1f6b9937e887dfa712c5bdfa950b01dbda3ebac4c85efdde48ee6a04020090004752210307a78def56cba9fc4db22a25928181de538ee59ba1a475ae113af7790acd0db32103c21e841cbc0b48197d060c71e116c185fa0ac281b7d0aa5924f535154437ca3b52ae00000000000186a0ffffffffffff0291e7c0a3232fb8650a6b4089568a81062b48a768780e5a74bb4a4a74e33aec2c029d5760248ec86c4a76d9df8308555785a06a65472fb995f5b392d520bbd000650090c1c94b11625690c9d84c5daa67b6ad19fcc7f9f23e194384140b08fcab9e8e810000ffffffffffff000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000002167c86cc0e598a6b541f7c9bf9ef17222e4a76f636e2d22185aeadd2b02d029c0000000000000000391732ce658e1fe167300bb689a81e7db5399b9ee4095e217b0e997e8dd3d17a00000000000000010000000000009896800000005166687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f29250500000000a0009d00202d704fbfe342a9ff6eaca14d80a24aaed0e680bbbdd36157b6f2798c61d906910120f9fe5e552aa0fc45020f0505efde432a4e373e5d393863973a6899f8c26d33d102080000000000989680044d4c00210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c2302090007000000000241000408000001000000000006020000080800000000009896800a04000000460000000000000000000000000000000166687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925fffffffffffe01e3002004f8eda5676356f539169a8e9a1e86c7f125283328d6f4bded1b939b52a6a7e30108000000000000c299022103a1f98e85886df54add6908b4fc1ff515e44aedefe9eb9c02879c89994298fa79042103a650bf03971df0176c7b412247390ef717853e8bd487b204dccc2fe2078bb75206210390bbbcebe9f70ba5dfd98866a79f72f75e0a6ea550ef73b202dd87cd6477350a08210284152d57908488e666e872716a286eb670b3d06cbeebf3f2e4ad350e01ec5e5b0a2102295e2de39eb3dcc2882f8cc266df7882a8b6d2c32aa08799f49b693aad3be28e0c04000000fd0e00fd0202002045cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d01080000000000009b5e0221035f5e9d58b4328566223c107d86cf853e6b9fae1d26ff6d969be0178d1423c4ea04210230fde9c031f487db95ff55b7c0acbe0c7c26a8d82615e9184416bd350101616706210225afb4e88eac8b47b67adeaf085f5eb5d37d936f56138f0848de3d104edf113208210208e4687a95c172b86b920c3bc5dbd5f023094ec2cb0abdb74f9b624f45740df90a2102d7dde8e10a5a22c9bd0d7ef5494d85683ac050253b917615d4f97af633f0a8e20c04000000fd0efd011d3b00010102080000000000989680040400000051062066687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925080400000000417e2650c201383711eed2a7cb8652c3e77ee6a395e81849c5c222217ed68b333c0ca9f1e900662ae68a7359efa7ef9d90613f2a62f7c3ff90f8c25e2cc974c9d3a0009d00202d704fbfe342a9ff6eaca14d80a24aaed0e680bbbdd36157b6f2798c61d906910120f9fe5e552aa0fc45020f0505efde432a4e373e5d393863973a6899f8c26d33d102080000000000989680044d4c00210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c2302090007000000000241000408000001000000000006020000080800000000009896800a0400000046fffffffffffefffffffffffe000000000000000000000000000000000000000000000000f1600ef6ea657b8d411d553516ae35cedfe86b0cd48d1f91b32772facbae757d0000000b0000000000000002fd01da002045cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d01fd01840200000000010174c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e00000000000f55f9800310270000000000002200208309b406e3b96e76cde414fbb8f5159f5b25b24075656c6382cec797854d53495e9b0000000000002200204c5f18e5e95b184f34d02ba6de8a2a4e36ae3d4ec87299ad81f3284dc7195c6350c300000000000016001425df8ec4a074f80579fed67d4707d5ec8ed7e8d304004730440220671c9badf26bd3a1ebd2d17020c6be20587d7822530daacc52c28839875eaec602204b575a21729ed27311f6d79fdf6fe8702b0a798f7d842e39ede1b56f249a613401473044022016a0da36f70cbf5d889586af88f238982889dc161462c56557125c7acfcb69e9022036ae10c6cc8cbc3b27d9e9ef6babb556086585bc819f252208bd175286699fdd014752210307a78def56cba9fc4db22a25928181de538ee59ba1a475ae113af7790acd0db32103c21e841cbc0b48197d060c71e116c185fa0ac281b7d0aa5924f535154437ca3b52ae50c9222002040000000b0320f1600ef6ea657b8d411d553516ae35cedfe86b0cd48d1f91b32772facbae757d0406030400020090fd02a1002045cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d01fd01840200000000010174c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e00000000000f55f9800310270000000000002200208309b406e3b96e76cde414fbb8f5159f5b25b24075656c6382cec797854d53495e9b0000000000002200204c5f18e5e95b184f34d02ba6de8a2a4e36ae3d4ec87299ad81f3284dc7195c6350c300000000000016001425df8ec4a074f80579fed67d4707d5ec8ed7e8d304004730440220671c9badf26bd3a1ebd2d17020c6be20587d7822530daacc52c28839875eaec602204b575a21729ed27311f6d79fdf6fe8702b0a798f7d842e39ede1b56f249a613401473044022016a0da36f70cbf5d889586af88f238982889dc161462c56557125c7acfcb69e9022036ae10c6cc8cbc3b27d9e9ef6babb556086585bc819f252208bd175286699fdd014752210307a78def56cba9fc4db22a25928181de538ee59ba1a475ae113af7790acd0db32103c21e841cbc0b48197d060c71e116c185fa0ac281b7d0aa5924f535154437ca3b52ae50c9222002040000000b0320f1600ef6ea657b8d411d553516ae35cedfe86b0cd48d1f91b32772facbae757d04cd01cb00c901c7002245cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d0001022102d7dde8e10a5a22c9bd0d7ef5494d85683ac050253b917615d4f97af633f0a8e204020090062b5e9b0000000000002200204c5f18e5e95b184f34d02ba6de8a2a4e36ae3d4ec87299ad81f3284dc7195c630821035f5e9d58b4328566223c107d86cf853e6b9fae1d26ff6d969be0178d1423c4ea0a200000000000000000000000004d49e5da0000000000000000000000000000002a0c0800000000000186a0000000000000000274c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e0000000000000001000000000022002034c0cc0ad0dd5fe61dcf7ef58f995e3d34f8dbd24aa2a6fae68fefe102bf025c45cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d000000000000000100000000002200208309b406e3b96e76cde414fbb8f5159f5b25b24075656c6382cec797854d5349010100160014d5a9aa98b89acc215fc3d23d6fec0ad59ca3665ffd027100fd01e6fd01e300080000fffffffffffe02080000000000009b5e0408000000000000c3500604000000fd08b0af002102d7dde8e10a5a22c9bd0d7ef5494d85683ac050253b917615d4f97af633f0a8e20221035f5e9d58b4328566223c107d86cf853e6b9fae1d26ff6d969be0178d1423c4ea04210230fde9c031f487db95ff55b7c0acbe0c7c26a8d82615e9184416bd350101616706210225afb4e88eac8b47b67adeaf085f5eb5d37d936f56138f0848de3d104edf113208210208e4687a95c172b86b920c3bc5dbd5f023094ec2cb0abdb74f9b624f45740df90acdcc00a8020000000174c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e00000000000f55f9800310270000000000002200208309b406e3b96e76cde414fbb8f5159f5b25b24075656c6382cec797854d53495e9b0000000000002200204c5f18e5e95b184f34d02ba6de8a2a4e36ae3d4ec87299ad81f3284dc7195c6350c300000000000016001425df8ec4a074f80579fed67d4707d5ec8ed7e8d350c92220022045cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d0c3c3b00010102080000000000989680040400000051062066687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f29250804000000000240671c9badf26bd3a1ebd2d17020c6be20587d7822530daacc52c28839875eaec64b575a21729ed27311f6d79fdf6fe8702b0a798f7d842e39ede1b56f249a613404010006407e2650c201383711eed2a7cb8652c3e77ee6a395e81849c5c222217ed68b333c0ca9f1e900662ae68a7359efa7ef9d90613f2a62f7c3ff90f8c25e2cc974c9d3010000000000000001010000000000000000090b2a953d93a124c600ecb1a0ccfed420169cdd37f538ad94a3e4e6318c93c14adf59cdfbb40bdd40950c9f8dd547d29d75a173e1376a7850743394c46dea2dfd01cefd01ca00fd017ffd017c00080000ffffffffffff0208000000000000c2990408000000000000c3500604000000fd08b0af002102295e2de39eb3dcc2882f8cc266df7882a8b6d2c32aa08799f49b693aad3be28e022103a1f98e85886df54add6908b4fc1ff515e44aedefe9eb9c02879c89994298fa79042103a650bf03971df0176c7b412247390ef717853e8bd487b204dccc2fe2078bb75206210390bbbcebe9f70ba5dfd98866a79f72f75e0a6ea550ef73b202dd87cd6477350a08210284152d57908488e666e872716a286eb670b3d06cbeebf3f2e4ad350e01ec5e5b0aa2a1007d020000000174c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e00000000000f55f9800299c2000000000000220020740e108cfbc93967b6ab242a351ebee7de51814cf78d366adefd78b10281f17e50c300000000000016001425df8ec4a074f80579fed67d4707d5ec8ed7e8d351c92220022004f8eda5676356f539169a8e9a1e86c7f125283328d6f4bded1b939b52a6a7e30c00024045cb2485594bb1ec08e7bb6af4f89c912bd53f006d7876ea956773e04a4aad4a40e2b8d4fc612102f0b54061b3c1239fb78783053e8e6f9d92b1b99f81ae9ec2040100060000fd019600b0af002103c21e841cbc0b48197d060c71e116c185fa0ac281b7d0aa5924f535154437ca3b02210270b20ad0f2c2bb30a55590fc77778495bc1b38c96476901145dda57491237f0f042103b4e59df102747edc3a3e2283b42b88a8c8218ffd0dcfb52f2524b371d64cadaa062103d902b7b8b3434076d2b210e912c76645048b71e28995aad227a465a65ccd817608210301e9a52f923c157941de4a7692e601f758660969dcf5abdb67817efe84cce2ef0202009004010106b7b600b0af00210307a78def56cba9fc4db22a25928181de538ee59ba1a475ae113af7790acd0db30221034d0f817cb19b4a3bd144b615459bd06cbab3b4bdc96d73e18549a992cee80e8104210380542b59a9679890cba529fe155a9508ef57dac7416d035b23666e3fb98c3814062103adde8029d3ee281a32e9db929b39f503ff9d7e93cd308eb157955344dc6def84082103205087e2dc1f6b9937e887dfa712c5bdfa950b01dbda3ebac4c85efdde48ee6a02020090082274c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e000000000287010108d30df34e3a1e00ecdd03a2c843db062479a81752c4dfd0cc4baef0f81e7bc7ef8820990daf8d8e8d30a3b4b08af12c9f5cd71e45c7238103e0c80ca13850862e4fd2c56b69b7195312518de1bfe9aed63c80bb7760d70b2a870d542d815895fd12423d11e2adb0cdf55d776dac8f487c9b3b7ea12f1b150eb15889cf41333ade465692bf1cdc360b9c2a19bf8c1ca4fed7639d8bc953d36c10d8c6c9a8c0a57608788979bcf145e61b308006896e21d03e92084f93bd78740c20639134a7a8fd019afd019600b0af002103c21e841cbc0b48197d060c71e116c185fa0ac281b7d0aa5924f535154437ca3b02210270b20ad0f2c2bb30a55590fc77778495bc1b38c96476901145dda57491237f0f042103b4e59df102747edc3a3e2283b42b88a8c8218ffd0dcfb52f2524b371d64cadaa062103d902b7b8b3434076d2b210e912c76645048b71e28995aad227a465a65ccd817608210301e9a52f923c157941de4a7692e601f758660969dcf5abdb67817efe84cce2ef0202009004010106b7b600b0af00210307a78def56cba9fc4db22a25928181de538ee59ba1a475ae113af7790acd0db30221034d0f817cb19b4a3bd144b615459bd06cbab3b4bdc96d73e18549a992cee80e8104210380542b59a9679890cba529fe155a9508ef57dac7416d035b23666e3fb98c3814062103adde8029d3ee281a32e9db929b39f503ff9d7e93cd308eb157955344dc6def84082103205087e2dc1f6b9937e887dfa712c5bdfa950b01dbda3ebac4c85efdde48ee6a02020090082274c52ab4f11296d62b66a6dba9513b04a3e7fb5a09a30cee22fce7294ab55b7e000000000000000186a00000000000000000000000004d49e5da0000000000000000000000000000002a00000000000000000000000000000000000000000000000001000000510000000000000001000000000000000145cfd42d0989e55b953f516ac7fd152bd90ec4438a2fc636f97ddd32a0c8fe0d00000000041000080000000000989680020400000051160004000000510208000000000000000004040000000b0000000000000000000101300300050007010109210355f8d2238a322d16b602bd0ceaad5b01019fb055971eaadcc9b29226a4da6c230d000f020000",
2074                 ).unwrap();
2075                 reload_node!(nodes[0], &nodes[0].node.encode(), &[&serialized_monitor], persister, new_chain_monitor, node_deserialized);
2076         }
2077
2078         // Connecting more blocks should result in the HTLC transactions being rebroadcast.
2079         connect_blocks(&nodes[0], 6);
2080         if check_old_monitor_retries_after_upgrade {
2081                 check_added_monitors(&nodes[0], 1);
2082         }
2083         {
2084                 let txn = nodes[0].tx_broadcaster.txn_broadcast();
2085                 if !nodes[0].connect_style.borrow().skips_blocks() {
2086                         assert_eq!(txn.len(), 6);
2087                 } else {
2088                         assert!(txn.len() < 6);
2089                 }
2090                 for tx in txn {
2091                         assert_eq!(tx.input.len(), htlc_timeout_tx.input.len());
2092                         assert_eq!(tx.output.len(), htlc_timeout_tx.output.len());
2093                         assert_eq!(tx.input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
2094                         assert_eq!(tx.output[0], htlc_timeout_tx.output[0]);
2095                 }
2096         }
2097 }
2098
2099 #[test]
2100 fn test_restored_packages_retry() {
2101         do_test_restored_packages_retry(false);
2102         do_test_restored_packages_retry(true);
2103 }
2104
2105 fn do_test_monitor_rebroadcast_pending_claims(anchors: bool) {
2106         // Test that we will retry broadcasting pending claims for a force-closed channel on every
2107         // `ChainMonitor::rebroadcast_pending_claims` call.
2108         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2109         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2110         let mut config = test_default_channel_config();
2111         if anchors {
2112                 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
2113                 config.manually_accept_inbound_channels = true;
2114         }
2115         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), Some(config)]);
2116         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2117
2118         let (_, _, _, chan_id, funding_tx) = create_chan_between_nodes_with_value(
2119                 &nodes[0], &nodes[1], 1_000_000, 500_000_000
2120         );
2121         const HTLC_AMT_MSAT: u64 = 1_000_000;
2122         const HTLC_AMT_SAT: u64 = HTLC_AMT_MSAT / 1000;
2123         route_payment(&nodes[0], &[&nodes[1]], HTLC_AMT_MSAT);
2124
2125         let htlc_expiry = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1;
2126
2127         let commitment_txn = get_local_commitment_txn!(&nodes[0], &chan_id);
2128         assert_eq!(commitment_txn.len(), if anchors { 1 /* commitment tx only */} else { 2 /* commitment and htlc timeout tx */ });
2129         check_spends!(&commitment_txn[0], &funding_tx);
2130         mine_transaction(&nodes[0], &commitment_txn[0]);
2131         check_closed_broadcast!(&nodes[0], true);
2132         check_closed_event!(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed,
2133                  false, [nodes[1].node.get_our_node_id()], 1000000);
2134         check_added_monitors(&nodes[0], 1);
2135
2136         let coinbase_tx = Transaction {
2137                 version: 2,
2138                 lock_time: LockTime::ZERO,
2139                 input: vec![TxIn { ..Default::default() }],
2140                 output: vec![TxOut { // UTXO to attach fees to `htlc_tx` on anchors
2141                         value: Amount::ONE_BTC.to_sat(),
2142                         script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
2143                 }],
2144         };
2145         nodes[0].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 }, coinbase_tx.output[0].value);
2146
2147         // Set up a helper closure we'll use throughout our test. We should only expect retries without
2148         // bumps if fees have not increased after a block has been connected (assuming the height timer
2149         // re-evaluates at every block) or after `ChainMonitor::rebroadcast_pending_claims` is called.
2150         let mut prev_htlc_tx_feerate = None;
2151         let mut check_htlc_retry = |should_retry: bool, should_bump: bool| -> Option<Transaction> {
2152                 let (htlc_tx, htlc_tx_feerate) = if anchors {
2153                         assert!(nodes[0].tx_broadcaster.txn_broadcast().is_empty());
2154                         let events = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
2155                         assert_eq!(events.len(), if should_retry { 1 } else { 0 });
2156                         if !should_retry {
2157                                 return None;
2158                         }
2159                         match &events[0] {
2160                                 Event::BumpTransaction(event) => {
2161                                         nodes[0].bump_tx_handler.handle_event(&event);
2162                                         let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
2163                                         assert_eq!(txn.len(), 1);
2164                                         let htlc_tx = txn.pop().unwrap();
2165                                         check_spends!(&htlc_tx, &commitment_txn[0], &coinbase_tx);
2166                                         let htlc_tx_fee = HTLC_AMT_SAT + coinbase_tx.output[0].value -
2167                                                 htlc_tx.output.iter().map(|output| output.value).sum::<u64>();
2168                                         let htlc_tx_weight = htlc_tx.weight().to_wu();
2169                                         (htlc_tx, compute_feerate_sat_per_1000_weight(htlc_tx_fee, htlc_tx_weight))
2170                                 }
2171                                 _ => panic!("Unexpected event"),
2172                         }
2173                 } else {
2174                         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2175                         let mut txn = nodes[0].tx_broadcaster.txn_broadcast();
2176                         assert_eq!(txn.len(), if should_retry { 1 } else { 0 });
2177                         if !should_retry {
2178                                 return None;
2179                         }
2180                         let htlc_tx = txn.pop().unwrap();
2181                         check_spends!(htlc_tx, commitment_txn[0]);
2182                         let htlc_tx_fee = HTLC_AMT_SAT - htlc_tx.output[0].value;
2183                         let htlc_tx_weight = htlc_tx.weight().to_wu();
2184                         (htlc_tx, compute_feerate_sat_per_1000_weight(htlc_tx_fee, htlc_tx_weight))
2185                 };
2186                 if should_bump {
2187                         assert!(htlc_tx_feerate > prev_htlc_tx_feerate.take().unwrap());
2188                 } else if let Some(prev_feerate) = prev_htlc_tx_feerate.take() {
2189                         assert_eq!(htlc_tx_feerate, prev_feerate);
2190                 }
2191                 prev_htlc_tx_feerate = Some(htlc_tx_feerate);
2192                 Some(htlc_tx)
2193         };
2194
2195         // Connect blocks up to one before the HTLC expires. This should not result in a claim/retry.
2196         connect_blocks(&nodes[0], htlc_expiry - nodes[0].best_block_info().1 - 1);
2197         check_htlc_retry(false, false);
2198
2199         // Connect one more block, producing our first claim.
2200         connect_blocks(&nodes[0], 1);
2201         check_htlc_retry(true, false);
2202
2203         // Connect one more block, expecting a retry with a fee bump. Unfortunately, we cannot bump HTLC
2204         // transactions pre-anchors.
2205         connect_blocks(&nodes[0], 1);
2206         check_htlc_retry(true, anchors);
2207
2208         // Trigger a call and we should have another retry, but without a bump.
2209         nodes[0].chain_monitor.chain_monitor.rebroadcast_pending_claims();
2210         check_htlc_retry(true, false);
2211
2212         // Double the feerate and trigger a call, expecting a fee-bumped retry.
2213         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
2214         nodes[0].chain_monitor.chain_monitor.rebroadcast_pending_claims();
2215         check_htlc_retry(true, anchors);
2216
2217         // Connect one more block, expecting a retry with a fee bump. Unfortunately, we cannot bump HTLC
2218         // transactions pre-anchors.
2219         connect_blocks(&nodes[0], 1);
2220         let htlc_tx = check_htlc_retry(true, anchors).unwrap();
2221
2222         // Mine the HTLC transaction to ensure we don't retry claims while they're confirmed.
2223         mine_transaction(&nodes[0], &htlc_tx);
2224         // If we have a `ConnectStyle` that advertises the new block first without the transactions,
2225         // we'll receive an extra bumped claim.
2226         if nodes[0].connect_style.borrow().updates_best_block_first() {
2227                 nodes[0].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 }, coinbase_tx.output[0].value);
2228                 nodes[0].wallet_source.remove_utxo(bitcoin::OutPoint { txid: htlc_tx.txid(), vout: 1 });
2229                 check_htlc_retry(true, anchors);
2230         }
2231         nodes[0].chain_monitor.chain_monitor.rebroadcast_pending_claims();
2232         check_htlc_retry(false, false);
2233 }
2234
2235 #[test]
2236 fn test_monitor_timer_based_claim() {
2237         do_test_monitor_rebroadcast_pending_claims(false);
2238         do_test_monitor_rebroadcast_pending_claims(true);
2239 }
2240
2241 #[test]
2242 fn test_yield_anchors_events() {
2243         // Tests that two parties supporting anchor outputs can open a channel, route payments over
2244         // it, and finalize its resolution uncooperatively. Once the HTLCs are locked in, one side will
2245         // force close once the HTLCs expire. The force close should stem from an event emitted by LDK,
2246         // allowing the consumer to provide additional fees to the commitment transaction to be
2247         // broadcast. Once the commitment transaction confirms, events for the HTLC resolution should be
2248         // emitted by LDK, such that the consumer can attach fees to the zero fee HTLC transactions.
2249         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2250         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2251         let mut anchors_config = test_default_channel_config();
2252         anchors_config.channel_handshake_config.announced_channel = true;
2253         anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
2254         anchors_config.manually_accept_inbound_channels = true;
2255         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config), Some(anchors_config)]);
2256         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2257
2258         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(
2259                 &nodes, 0, 1, 1_000_000, 500_000_000
2260         );
2261         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2262         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 2_000_000);
2263
2264         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2265         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2266
2267         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
2268
2269         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2270         assert!(nodes[0].tx_broadcaster.txn_broadcast().is_empty());
2271
2272         connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2273         {
2274                 let txn = nodes[1].tx_broadcaster.txn_broadcast();
2275                 assert_eq!(txn.len(), 1);
2276                 check_spends!(txn[0], funding_tx);
2277         }
2278
2279         get_monitor!(nodes[0], chan_id).provide_payment_preimage(
2280                 &payment_hash_2, &payment_preimage_2, &node_cfgs[0].tx_broadcaster,
2281                 &LowerBoundedFeeEstimator::new(node_cfgs[0].fee_estimator), &nodes[0].logger
2282         );
2283         get_monitor!(nodes[1], chan_id).provide_payment_preimage(
2284                 &payment_hash_1, &payment_preimage_1, &node_cfgs[1].tx_broadcaster,
2285                 &LowerBoundedFeeEstimator::new(node_cfgs[1].fee_estimator), &nodes[1].logger
2286         );
2287
2288         let mut holder_events = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
2289         assert_eq!(holder_events.len(), 1);
2290         let (commitment_tx, anchor_tx) = match holder_events.pop().unwrap() {
2291                 Event::BumpTransaction(event) => {
2292                         let coinbase_tx = Transaction {
2293                                 version: 2,
2294                                 lock_time: LockTime::ZERO,
2295                                 input: vec![TxIn { ..Default::default() }],
2296                                 output: vec![TxOut { // UTXO to attach fees to `anchor_tx`
2297                                         value: Amount::ONE_BTC.to_sat(),
2298                                         script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
2299                                 }],
2300                         };
2301                         nodes[0].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 }, coinbase_tx.output[0].value);
2302                         nodes[0].bump_tx_handler.handle_event(&event);
2303                         let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
2304                         assert_eq!(txn.len(), 2);
2305                         let anchor_tx = txn.pop().unwrap();
2306                         let commitment_tx = txn.pop().unwrap();
2307                         check_spends!(commitment_tx, funding_tx);
2308                         check_spends!(anchor_tx, coinbase_tx, commitment_tx);
2309                         (commitment_tx, anchor_tx)
2310                 },
2311                 _ => panic!("Unexpected event"),
2312         };
2313
2314         assert_eq!(commitment_tx.output[2].value, 1_000); // HTLC A -> B
2315         assert_eq!(commitment_tx.output[3].value, 2_000); // HTLC B -> A
2316
2317         mine_transactions(&nodes[0], &[&commitment_tx, &anchor_tx]);
2318         check_added_monitors!(nodes[0], 1);
2319         mine_transactions(&nodes[1], &[&commitment_tx, &anchor_tx]);
2320         check_added_monitors!(nodes[1], 1);
2321
2322         {
2323                 let mut txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
2324                 assert_eq!(txn.len(), if nodes[1].connect_style.borrow().updates_best_block_first() { 3 } else { 2 });
2325
2326                 let htlc_preimage_tx = txn.pop().unwrap();
2327                 assert_eq!(htlc_preimage_tx.input.len(), 1);
2328                 assert_eq!(htlc_preimage_tx.input[0].previous_output.vout, 3);
2329                 check_spends!(htlc_preimage_tx, commitment_tx);
2330
2331                 let htlc_timeout_tx = txn.pop().unwrap();
2332                 assert_eq!(htlc_timeout_tx.input.len(), 1);
2333                 assert_eq!(htlc_timeout_tx.input[0].previous_output.vout, 2);
2334                 check_spends!(htlc_timeout_tx, commitment_tx);
2335
2336                 if let Some(commitment_tx) = txn.pop() {
2337                         check_spends!(commitment_tx, funding_tx);
2338                 }
2339         }
2340
2341         let mut holder_events = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
2342         // Certain block `ConnectStyle`s cause an extra `ChannelClose` event to be emitted since the
2343         // best block is updated before the confirmed transactions are notified.
2344         if nodes[0].connect_style.borrow().updates_best_block_first() {
2345                 assert_eq!(holder_events.len(), 3);
2346                 if let Event::BumpTransaction(BumpTransactionEvent::ChannelClose { .. }) = holder_events.remove(0) {}
2347                 else { panic!("unexpected event"); }
2348         } else {
2349                 assert_eq!(holder_events.len(), 2);
2350         }
2351         let mut htlc_txs = Vec::with_capacity(2);
2352         for event in holder_events {
2353                 match event {
2354                         Event::BumpTransaction(event) => {
2355                                 nodes[0].bump_tx_handler.handle_event(&event);
2356                                 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
2357                                 assert_eq!(txn.len(), 1);
2358                                 let htlc_tx = txn.pop().unwrap();
2359                                 check_spends!(htlc_tx, commitment_tx, anchor_tx);
2360                                 htlc_txs.push(htlc_tx);
2361                         },
2362                         _ => panic!("Unexpected event"),
2363                 }
2364         }
2365
2366         mine_transactions(&nodes[0], &[&htlc_txs[0], &htlc_txs[1]]);
2367         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
2368
2369         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2370
2371         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32);
2372
2373         let holder_events = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
2374         assert_eq!(holder_events.len(), 3);
2375         for event in holder_events {
2376                 match event {
2377                         Event::SpendableOutputs { .. } => {},
2378                         _ => panic!("Unexpected event"),
2379                 }
2380         }
2381
2382         // Clear the remaining events as they're not relevant to what we're testing.
2383         nodes[0].node.get_and_clear_pending_events();
2384         nodes[1].node.get_and_clear_pending_events();
2385         nodes[0].node.get_and_clear_pending_msg_events();
2386         nodes[1].node.get_and_clear_pending_msg_events();
2387 }
2388
2389 #[test]
2390 fn test_anchors_aggregated_revoked_htlc_tx() {
2391         // Test that `ChannelMonitor`s can properly detect and claim funds from a counterparty claiming
2392         // multiple HTLCs from multiple channels in a single transaction via the success path from a
2393         // revoked commitment.
2394         let secp = Secp256k1::new();
2395         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2396         // Required to sign a revoked commitment transaction
2397         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2398         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2399         let bob_persister;
2400         let bob_chain_monitor;
2401
2402         let mut anchors_config = test_default_channel_config();
2403         anchors_config.channel_handshake_config.announced_channel = true;
2404         anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
2405         anchors_config.manually_accept_inbound_channels = true;
2406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config), Some(anchors_config)]);
2407         let bob_deserialized;
2408
2409         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2410
2411         let chan_a = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 20_000_000);
2412         let chan_b = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 20_000_000);
2413
2414         // Serialize Bob with the initial state of both channels, which we'll use later.
2415         let bob_serialized = nodes[1].node.encode();
2416
2417         // Route two payments for each channel from Alice to Bob to lock in the HTLCs.
2418         let payment_a = route_payment(&nodes[0], &[&nodes[1]], 50_000_000);
2419         let payment_b = route_payment(&nodes[0], &[&nodes[1]], 50_000_000);
2420         let payment_c = route_payment(&nodes[0], &[&nodes[1]], 50_000_000);
2421         let payment_d = route_payment(&nodes[0], &[&nodes[1]], 50_000_000);
2422
2423         // Serialize Bob's monitors with the HTLCs locked in. We'll restart Bob later on with the state
2424         // at this point such that he broadcasts a revoked commitment transaction with the HTLCs
2425         // present.
2426         let bob_serialized_monitor_a = get_monitor!(nodes[1], chan_a.2).encode();
2427         let bob_serialized_monitor_b = get_monitor!(nodes[1], chan_b.2).encode();
2428
2429         // Bob claims all the HTLCs...
2430         claim_payment(&nodes[0], &[&nodes[1]], payment_a.0);
2431         claim_payment(&nodes[0], &[&nodes[1]], payment_b.0);
2432         claim_payment(&nodes[0], &[&nodes[1]], payment_c.0);
2433         claim_payment(&nodes[0], &[&nodes[1]], payment_d.0);
2434
2435         // ...and sends one back through each channel such that he has a motive to broadcast his
2436         // revoked state.
2437         send_payment(&nodes[1], &[&nodes[0]], 30_000_000);
2438         send_payment(&nodes[1], &[&nodes[0]], 30_000_000);
2439
2440         // Restart Bob with the revoked state and provide the HTLC preimages he claimed.
2441         reload_node!(
2442                 nodes[1], anchors_config, bob_serialized, &[&bob_serialized_monitor_a, &bob_serialized_monitor_b],
2443                 bob_persister, bob_chain_monitor, bob_deserialized
2444         );
2445         for chan_id in [chan_a.2, chan_b.2].iter() {
2446                 let monitor = get_monitor!(nodes[1], chan_id);
2447                 for payment in [payment_a, payment_b, payment_c, payment_d].iter() {
2448                         monitor.provide_payment_preimage(
2449                                 &payment.1, &payment.0, &node_cfgs[1].tx_broadcaster,
2450                                 &LowerBoundedFeeEstimator::new(node_cfgs[1].fee_estimator), &nodes[1].logger
2451                         );
2452                 }
2453         }
2454
2455         // Bob force closes by restarting with the outdated state, prompting the ChannelMonitors to
2456         // broadcast the latest commitment transaction known to them, which in our case is the one with
2457         // the HTLCs still pending.
2458         *nodes[1].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
2459         nodes[1].node.timer_tick_occurred();
2460         check_added_monitors(&nodes[1], 2);
2461         check_closed_event!(&nodes[1], 2, ClosureReason::OutdatedChannelManager, [nodes[0].node.get_our_node_id(); 2], 1000000);
2462
2463         // Bob should now receive two events to bump his revoked commitment transaction fees.
2464         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2465         let events = nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events();
2466         assert_eq!(events.len(), 2);
2467         let mut revoked_commitment_txs = Vec::with_capacity(events.len());
2468         let mut anchor_txs = Vec::with_capacity(events.len());
2469         for (idx, event) in events.into_iter().enumerate() {
2470                 let utxo_value = Amount::ONE_BTC.to_sat() * (idx + 1) as u64;
2471                 let coinbase_tx = Transaction {
2472                         version: 2,
2473                         lock_time: LockTime::ZERO,
2474                         input: vec![TxIn { ..Default::default() }],
2475                         output: vec![TxOut { // UTXO to attach fees to `anchor_tx`
2476                                 value: utxo_value,
2477                                 script_pubkey: nodes[1].wallet_source.get_change_script().unwrap(),
2478                         }],
2479                 };
2480                 nodes[1].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 }, utxo_value);
2481                 match event {
2482                         Event::BumpTransaction(event) => nodes[1].bump_tx_handler.handle_event(&event),
2483                         _ => panic!("Unexpected event"),
2484                 };
2485                 let txn = nodes[1].tx_broadcaster.txn_broadcast();
2486                 assert_eq!(txn.len(), 2);
2487                 assert_eq!(txn[0].output.len(), 6); // 2 HTLC outputs + 1 to_self output + 1 to_remote output + 2 anchor outputs
2488                 if txn[0].input[0].previous_output.txid == chan_a.3.txid() {
2489                         check_spends!(&txn[0], &chan_a.3);
2490                 } else {
2491                         check_spends!(&txn[0], &chan_b.3);
2492                 }
2493                 let (commitment_tx, anchor_tx) = (&txn[0], &txn[1]);
2494                 check_spends!(anchor_tx, coinbase_tx, commitment_tx);
2495
2496                 revoked_commitment_txs.push(commitment_tx.clone());
2497                 anchor_txs.push(anchor_tx.clone());
2498         };
2499
2500         for node in &nodes {
2501                 mine_transactions(node, &[&revoked_commitment_txs[0], &anchor_txs[0], &revoked_commitment_txs[1], &anchor_txs[1]]);
2502         }
2503         check_added_monitors!(&nodes[0], 2);
2504         check_closed_broadcast(&nodes[0], 2, true);
2505         check_closed_event!(&nodes[0], 2, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id(); 2], 1000000);
2506
2507         // Alice should detect the confirmed revoked commitments, and attempt to claim all of the
2508         // revoked outputs.
2509         {
2510                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2511                 assert_eq!(txn.len(), 4);
2512
2513                 let (revoked_htlc_claim_a, revoked_htlc_claim_b) = if txn[0].input[0].previous_output.txid == revoked_commitment_txs[0].txid() {
2514                         (if txn[0].input.len() == 2 { &txn[0] } else { &txn[1] }, if txn[2].input.len() == 2 { &txn[2] } else { &txn[3] })
2515                 } else {
2516                         (if txn[2].input.len() == 2 { &txn[2] } else { &txn[3] }, if txn[0].input.len() == 2 { &txn[0] } else { &txn[1] })
2517                 };
2518
2519                 assert_eq!(revoked_htlc_claim_a.input.len(), 2); // Spends both HTLC outputs
2520                 assert_eq!(revoked_htlc_claim_a.output.len(), 1);
2521                 check_spends!(revoked_htlc_claim_a, revoked_commitment_txs[0]);
2522                 assert_eq!(revoked_htlc_claim_b.input.len(), 2); // Spends both HTLC outputs
2523                 assert_eq!(revoked_htlc_claim_b.output.len(), 1);
2524                 check_spends!(revoked_htlc_claim_b, revoked_commitment_txs[1]);
2525         }
2526
2527         // Since Bob was able to confirm his revoked commitment, he'll now try to claim the HTLCs
2528         // through the success path.
2529         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2530         let mut events = nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events();
2531         // Certain block `ConnectStyle`s cause an extra `ChannelClose` event to be emitted since the
2532         // best block is updated before the confirmed transactions are notified.
2533         match *nodes[1].connect_style.borrow() {
2534                 ConnectStyle::BestBlockFirst|ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::BestBlockFirstSkippingBlocks => {
2535                         assert_eq!(events.len(), 4);
2536                         if let Event::BumpTransaction(BumpTransactionEvent::ChannelClose { .. }) = events.remove(0) {}
2537                         else { panic!("unexpected event"); }
2538                         if let Event::BumpTransaction(BumpTransactionEvent::ChannelClose { .. }) = events.remove(1) {}
2539                         else { panic!("unexpected event"); }
2540
2541                 },
2542                 _ => assert_eq!(events.len(), 2),
2543         };
2544         let htlc_tx = {
2545                 let secret_key = SecretKey::from_slice(&[1; 32]).unwrap();
2546                 let public_key = PublicKey::new(secret_key.public_key(&secp));
2547                 let fee_utxo_script = ScriptBuf::new_v0_p2wpkh(&public_key.wpubkey_hash().unwrap());
2548                 let coinbase_tx = Transaction {
2549                         version: 2,
2550                         lock_time: LockTime::ZERO,
2551                         input: vec![TxIn { ..Default::default() }],
2552                         output: vec![TxOut { // UTXO to attach fees to `htlc_tx`
2553                                 value: Amount::ONE_BTC.to_sat(),
2554                                 script_pubkey: fee_utxo_script.clone(),
2555                         }],
2556                 };
2557                 let mut htlc_tx = Transaction {
2558                         version: 2,
2559                         lock_time: LockTime::ZERO,
2560                         input: vec![TxIn { // Fee input
2561                                 previous_output: bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 },
2562                                 ..Default::default()
2563                         }],
2564                         output: vec![TxOut { // Fee input change
2565                                 value: coinbase_tx.output[0].value / 2 ,
2566                                 script_pubkey: ScriptBuf::new_op_return(&[]),
2567                         }],
2568                 };
2569                 let mut descriptors = Vec::with_capacity(4);
2570                 for event in events {
2571                         // We don't use the `BumpTransactionEventHandler` here because it does not support
2572                         // creating one transaction from multiple `HTLCResolution` events.
2573                         if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, tx_lock_time, .. }) = event {
2574                                 assert_eq!(htlc_descriptors.len(), 2);
2575                                 for htlc_descriptor in &htlc_descriptors {
2576                                         assert!(!htlc_descriptor.htlc.offered);
2577                                         htlc_tx.input.push(htlc_descriptor.unsigned_tx_input());
2578                                         htlc_tx.output.push(htlc_descriptor.tx_output(&secp));
2579                                 }
2580                                 descriptors.append(&mut htlc_descriptors);
2581                                 htlc_tx.lock_time = tx_lock_time;
2582                         } else {
2583                                 panic!("Unexpected event");
2584                         }
2585                 }
2586                 for (idx, htlc_descriptor) in descriptors.into_iter().enumerate() {
2587                         let htlc_input_idx = idx + 1;
2588                         let signer = htlc_descriptor.derive_channel_signer(&nodes[1].keys_manager);
2589                         let our_sig = signer.sign_holder_htlc_transaction(&htlc_tx, htlc_input_idx, &htlc_descriptor, &secp).unwrap();
2590                         let witness_script = htlc_descriptor.witness_script(&secp);
2591                         htlc_tx.input[htlc_input_idx].witness = htlc_descriptor.tx_input_witness(&our_sig, &witness_script);
2592                 }
2593                 let fee_utxo_sig = {
2594                         let witness_script = ScriptBuf::new_p2pkh(&public_key.pubkey_hash());
2595                         let sighash = hash_to_message!(&SighashCache::new(&htlc_tx).segwit_signature_hash(
2596                                 0, &witness_script, coinbase_tx.output[0].value, EcdsaSighashType::All
2597                         ).unwrap()[..]);
2598                         let sig = sign(&secp, &sighash, &secret_key);
2599                         let mut sig = sig.serialize_der().to_vec();
2600                         sig.push(EcdsaSighashType::All as u8);
2601                         sig
2602                 };
2603                 htlc_tx.input[0].witness = Witness::from_slice(&[fee_utxo_sig, public_key.to_bytes()]);
2604                 check_spends!(htlc_tx, coinbase_tx, revoked_commitment_txs[0], revoked_commitment_txs[1]);
2605                 htlc_tx
2606         };
2607
2608         for node in &nodes {
2609                 mine_transaction(node, &htlc_tx);
2610         }
2611
2612         // Alice should see that Bob is trying to claim to HTLCs, so she should now try to claim them at
2613         // the second level instead.
2614         let revoked_claim_transactions = {
2615                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2616                 assert_eq!(txn.len(), 2);
2617
2618                 let revoked_htlc_claims = txn.iter().filter(|tx|
2619                         tx.input.len() == 2 &&
2620                         tx.output.len() == 1 &&
2621                         tx.input[0].previous_output.txid == htlc_tx.txid()
2622                 ).collect::<Vec<_>>();
2623                 assert_eq!(revoked_htlc_claims.len(), 2);
2624                 for revoked_htlc_claim in revoked_htlc_claims {
2625                         check_spends!(revoked_htlc_claim, htlc_tx);
2626                 }
2627
2628                 let mut revoked_claim_transaction_map = new_hash_map();
2629                 for current_tx in txn.into_iter() {
2630                         revoked_claim_transaction_map.insert(current_tx.txid(), current_tx);
2631                 }
2632                 revoked_claim_transaction_map
2633         };
2634         for node in &nodes {
2635                 mine_transactions(node, &revoked_claim_transactions.values().collect::<Vec<_>>());
2636         }
2637
2638
2639         // Connect one block to make sure the HTLC events are not yielded while ANTI_REORG_DELAY has not
2640         // been reached.
2641         connect_blocks(&nodes[0], 1);
2642         connect_blocks(&nodes[1], 1);
2643
2644         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2645         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2646
2647         // Connect the remaining blocks to reach ANTI_REORG_DELAY.
2648         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
2649         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 2);
2650
2651         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
2652         let spendable_output_events = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
2653         assert_eq!(spendable_output_events.len(), 4);
2654         for event in spendable_output_events {
2655                 if let Event::SpendableOutputs { outputs, channel_id } = event {
2656                         assert_eq!(outputs.len(), 1);
2657                         assert!(vec![chan_b.2, chan_a.2].contains(&channel_id.unwrap()));
2658                         let spend_tx = nodes[0].keys_manager.backing.spend_spendable_outputs(
2659                                 &[&outputs[0]], Vec::new(), ScriptBuf::new_op_return(&[]), 253, None, &Secp256k1::new(),
2660                         ).unwrap();
2661
2662                         if let SpendableOutputDescriptor::StaticPaymentOutput(_) = &outputs[0] {
2663                                 check_spends!(spend_tx, &revoked_commitment_txs[0], &revoked_commitment_txs[1]);
2664                         } else {
2665                                 check_spends!(spend_tx, revoked_claim_transactions.get(&spend_tx.input[0].previous_output.txid).unwrap());
2666                         }
2667                 } else {
2668                         panic!("unexpected event");
2669                 }
2670         }
2671
2672         assert!(nodes[0].node.list_channels().is_empty());
2673         assert!(nodes[1].node.list_channels().is_empty());
2674         // On the Alice side, the individual to_self_claim are still pending confirmation.
2675         assert_eq!(nodes[0].chain_monitor.chain_monitor.get_claimable_balances(&[]).len(), 2);
2676         // TODO: From Bob's PoV, he still thinks he can claim the outputs from his revoked commitment.
2677         // This needs to be fixed before we enable pruning `ChannelMonitor`s once they don't have any
2678         // balances to claim.
2679         //
2680         // The 6 claimable balances correspond to his `to_self` outputs and the 2 HTLC outputs in each
2681         // revoked commitment which Bob has the preimage for.
2682         assert_eq!(nodes[1].chain_monitor.chain_monitor.get_claimable_balances(&[]).len(), 6);
2683 }
2684
2685 fn do_test_anchors_monitor_fixes_counterparty_payment_script_on_reload(confirm_commitment_before_reload: bool) {
2686         // Tests that we'll fix a ChannelMonitor's `counterparty_payment_script` for an anchor outputs
2687         // channel upon deserialization.
2688         let chanmon_cfgs = create_chanmon_cfgs(2);
2689         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2690         let persister;
2691         let chain_monitor;
2692         let mut user_config = test_default_channel_config();
2693         user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
2694         user_config.manually_accept_inbound_channels = true;
2695         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config), Some(user_config)]);
2696         let node_deserialized;
2697         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2698
2699         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 50_000_000);
2700
2701         // Set the monitor's `counterparty_payment_script` to a dummy P2WPKH script.
2702         let secp = Secp256k1::new();
2703         let privkey = bitcoin::PrivateKey::from_slice(&[1; 32], bitcoin::Network::Testnet).unwrap();
2704         let pubkey = bitcoin::PublicKey::from_private_key(&secp, &privkey);
2705         let p2wpkh_script = ScriptBuf::new_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap());
2706         get_monitor!(nodes[1], chan_id).set_counterparty_payment_script(p2wpkh_script.clone());
2707         assert_eq!(get_monitor!(nodes[1], chan_id).get_counterparty_payment_script(), p2wpkh_script);
2708
2709         // Confirm the counterparty's commitment and reload the monitor (either before or after) such
2710         // that we arrive at the correct `counterparty_payment_script` after the reload.
2711         nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
2712         check_added_monitors(&nodes[0], 1);
2713         check_closed_broadcast(&nodes[0], 1, true);
2714         check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
2715                  [nodes[1].node.get_our_node_id()], 100000);
2716
2717         let commitment_tx = {
2718                 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
2719                 assert_eq!(txn.len(), 1);
2720                 assert_eq!(txn[0].output.len(), 4);
2721                 check_spends!(txn[0], funding_tx);
2722                 txn.pop().unwrap()
2723         };
2724
2725         mine_transaction(&nodes[0], &commitment_tx);
2726         let commitment_tx_conf_height = if confirm_commitment_before_reload {
2727                 // We should expect our round trip serialization check to fail as we're writing the monitor
2728                 // with the incorrect P2WPKH script but reading it with the correct P2WSH script.
2729                 *nodes[1].chain_monitor.expect_monitor_round_trip_fail.lock().unwrap() = Some(chan_id);
2730                 let commitment_tx_conf_height = block_from_scid(mine_transaction(&nodes[1], &commitment_tx));
2731                 let serialized_monitor = get_monitor!(nodes[1], chan_id).encode();
2732                 reload_node!(nodes[1], user_config, &nodes[1].node.encode(), &[&serialized_monitor], persister, chain_monitor, node_deserialized);
2733                 commitment_tx_conf_height
2734         } else {
2735                 let serialized_monitor = get_monitor!(nodes[1], chan_id).encode();
2736                 reload_node!(nodes[1], user_config, &nodes[1].node.encode(), &[&serialized_monitor], persister, chain_monitor, node_deserialized);
2737                 let commitment_tx_conf_height = block_from_scid(mine_transaction(&nodes[1], &commitment_tx));
2738                 check_added_monitors(&nodes[1], 1);
2739                 check_closed_broadcast(&nodes[1], 1, true);
2740                 commitment_tx_conf_height
2741         };
2742         check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2743                  [nodes[0].node.get_our_node_id()], 100000);
2744         assert!(get_monitor!(nodes[1], chan_id).get_counterparty_payment_script().is_v0_p2wsh());
2745
2746         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
2747         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2748
2749         if confirm_commitment_before_reload {
2750                 // If we saw the commitment before our `counterparty_payment_script` was fixed, we'll never
2751                 // get the spendable output event for the `to_remote` output, so we'll need to get it
2752                 // manually via `get_spendable_outputs`.
2753                 check_added_monitors(&nodes[1], 1);
2754                 let outputs = get_monitor!(nodes[1], chan_id).get_spendable_outputs(&commitment_tx, commitment_tx_conf_height);
2755                 assert_eq!(outputs.len(), 1);
2756                 let spend_tx = nodes[1].keys_manager.backing.spend_spendable_outputs(
2757                         &[&outputs[0]], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
2758                         253, None, &secp
2759                 ).unwrap();
2760                 check_spends!(spend_tx, &commitment_tx);
2761         } else {
2762                 test_spendable_output(&nodes[1], &commitment_tx, false);
2763         }
2764 }
2765
2766 #[test]
2767 fn test_anchors_monitor_fixes_counterparty_payment_script_on_reload() {
2768         do_test_anchors_monitor_fixes_counterparty_payment_script_on_reload(false);
2769         do_test_anchors_monitor_fixes_counterparty_payment_script_on_reload(true);
2770 }
2771
2772 #[cfg(not(feature = "_test_vectors"))]
2773 fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterparty_commitment: bool) {
2774         // Tests that our monitor claims will always use fresh random signatures (ensuring a unique
2775         // wtxid) to prevent certain classes of transaction replacement at the bitcoin P2P layer.
2776         let chanmon_cfgs = create_chanmon_cfgs(2);
2777         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2778         let mut user_config = test_default_channel_config();
2779         if anchors {
2780                 user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
2781                 user_config.manually_accept_inbound_channels = true;
2782         }
2783         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(user_config), Some(user_config)]);
2784         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2785
2786         let coinbase_tx = Transaction {
2787                 version: 2,
2788                 lock_time: LockTime::ZERO,
2789                 input: vec![TxIn { ..Default::default() }],
2790                 output: vec![
2791                         TxOut {
2792                                 value: Amount::ONE_BTC.to_sat(),
2793                                 script_pubkey: nodes[0].wallet_source.get_change_script().unwrap(),
2794                         },
2795                 ],
2796         };
2797         if anchors {
2798                 nodes[0].wallet_source.add_utxo(bitcoin::OutPoint { txid: coinbase_tx.txid(), vout: 0 }, coinbase_tx.output[0].value);
2799         }
2800
2801         // Open a channel and route a payment. We'll let it timeout to claim it.
2802         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2803         route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2804
2805         let (closing_node, other_node) = if confirm_counterparty_commitment {
2806                 (&nodes[1], &nodes[0])
2807         } else {
2808                 (&nodes[0], &nodes[1])
2809         };
2810
2811         get_monitor!(closing_node, chan_id).broadcast_latest_holder_commitment_txn(
2812                 &closing_node.tx_broadcaster, &closing_node.fee_estimator, &closing_node.logger
2813         );
2814
2815         // The commitment transaction comes first.
2816         let commitment_tx = {
2817                 let mut txn = closing_node.tx_broadcaster.unique_txn_broadcast();
2818                 assert_eq!(txn.len(), 1);
2819                 check_spends!(txn[0], funding_tx);
2820                 txn.pop().unwrap()
2821         };
2822
2823         mine_transaction(closing_node, &commitment_tx);
2824         check_added_monitors!(closing_node, 1);
2825         check_closed_broadcast!(closing_node, true);
2826         check_closed_event!(closing_node, 1, ClosureReason::CommitmentTxConfirmed, [other_node.node.get_our_node_id()], 1_000_000);
2827
2828         mine_transaction(other_node, &commitment_tx);
2829         check_added_monitors!(other_node, 1);
2830         check_closed_broadcast!(other_node, true);
2831         check_closed_event!(other_node, 1, ClosureReason::CommitmentTxConfirmed, [closing_node.node.get_our_node_id()], 1_000_000);
2832
2833         // If we update the best block to the new height before providing the confirmed transactions,
2834         // we'll see another broadcast of the commitment transaction.
2835         if !confirm_counterparty_commitment && nodes[0].connect_style.borrow().updates_best_block_first() {
2836                 let _ = nodes[0].tx_broadcaster.txn_broadcast();
2837         }
2838
2839         // Then comes the HTLC timeout transaction.
2840         if confirm_counterparty_commitment {
2841                 connect_blocks(&nodes[0], 5);
2842                 test_spendable_output(&nodes[0], &commitment_tx, false);
2843                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 5);
2844         } else {
2845                 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
2846         }
2847         if anchors && !confirm_counterparty_commitment {
2848                 handle_bump_htlc_event(&nodes[0], 1);
2849         }
2850         let htlc_timeout_tx = {
2851                 let mut txn = nodes[0].tx_broadcaster.txn_broadcast();
2852                 assert_eq!(txn.len(), 1);
2853                 let tx = txn.pop().unwrap();
2854                 check_spends!(tx, commitment_tx, coinbase_tx);
2855                 tx
2856         };
2857
2858         // Check we rebroadcast it with a different wtxid.
2859         nodes[0].chain_monitor.chain_monitor.rebroadcast_pending_claims();
2860         if anchors && !confirm_counterparty_commitment {
2861                 handle_bump_htlc_event(&nodes[0], 1);
2862         }
2863         {
2864                 let mut txn = nodes[0].tx_broadcaster.txn_broadcast();
2865                 assert_eq!(txn.len(), 1);
2866                 assert_eq!(txn[0].txid(), htlc_timeout_tx.txid());
2867                 assert_ne!(txn[0].wtxid(), htlc_timeout_tx.wtxid());
2868         }
2869 }
2870
2871 #[cfg(not(feature = "_test_vectors"))]
2872 #[test]
2873 fn test_monitor_claims_with_random_signatures() {
2874         do_test_monitor_claims_with_random_signatures(false, false);
2875         do_test_monitor_claims_with_random_signatures(false, true);
2876         do_test_monitor_claims_with_random_signatures(true, false);
2877         do_test_monitor_claims_with_random_signatures(true, true);
2878 }
2879
2880 #[test]
2881 fn test_event_replay_causing_monitor_replay() {
2882         // In LDK 0.0.121 there was a bug where if a `PaymentSent` event caused an RAA
2883         // `ChannelMonitorUpdate` hold and then the node was restarted after the `PaymentSent` event
2884         // and `ChannelMonitorUpdate` both completed but without persisting the `ChannelManager` we'd
2885         // replay the `ChannelMonitorUpdate` on restart (which is fine, but triggered a safety panic).
2886         let chanmon_cfgs = create_chanmon_cfgs(2);
2887         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2888         let persister;
2889         let new_chain_monitor;
2890         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2891         let node_deserialized;
2892         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2893
2894         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
2895
2896         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_000_000).0;
2897
2898         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
2899
2900         // At this point the `PaymentSent` event has not been processed but the full commitment signed
2901         // dance has completed.
2902         let serialized_channel_manager = nodes[0].node.encode();
2903
2904         // Now process the `PaymentSent` to get the final RAA `ChannelMonitorUpdate`, checking that it
2905         // resulted in a `ChannelManager` persistence request.
2906         nodes[0].node.get_and_clear_needs_persistence();
2907         expect_payment_sent(&nodes[0], payment_preimage, None, true, true /* expected post-event monitor update*/);
2908         assert!(nodes[0].node.get_and_clear_needs_persistence());
2909
2910         let serialized_monitor = get_monitor!(nodes[0], chan.2).encode();
2911         reload_node!(nodes[0], &serialized_channel_manager, &[&serialized_monitor], persister, new_chain_monitor, node_deserialized);
2912
2913         // Expect the `PaymentSent` to get replayed, this time without the duplicate monitor update
2914         expect_payment_sent(&nodes[0], payment_preimage, None, false, false /* expected post-event monitor update*/);
2915 }