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