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.
12 use chain::channelmonitor::{ANTI_REORG_DELAY, Balance};
13 use chain::transaction::OutPoint;
15 use ln::channelmanager::BREAKDOWN_TIMEOUT;
16 use ln::features::InitFeatures;
17 use ln::msgs::ChannelMessageHandler;
18 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
20 use bitcoin::blockdata::script::Builder;
21 use bitcoin::blockdata::opcodes;
22 use bitcoin::secp256k1::Secp256k1;
23 use bitcoin::Transaction;
27 use ln::functional_test_utils::*;
30 fn chanmon_fail_from_stale_commitment() {
31 // If we forward an HTLC to our counterparty, but we force-closed the channel before our
32 // counterparty provides us an updated commitment transaction, we'll end up with a commitment
33 // transaction that does not contain the HTLC which we attempted to forward. In this case, we
34 // need to wait `ANTI_REORG_DELAY` blocks and then fail back the HTLC as there is no way for us
35 // to learn the preimage and the confirmed commitment transaction paid us the value of the
38 // However, previously, we did not do this, ignoring the HTLC entirely.
40 // This could lead to channel closure if the sender we received the HTLC from decides to go on
41 // chain to get their HTLC back before it times out.
43 // Here, we check exactly this case, forwarding a payment from A, through B, to C, before B
44 // broadcasts its latest commitment transaction, which should result in it eventually failing
45 // the HTLC back off-chain to A.
46 let chanmon_cfgs = create_chanmon_cfgs(3);
47 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
48 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
49 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
51 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
52 let (update_a, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
54 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
55 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
56 check_added_monitors!(nodes[0], 1);
58 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id_2);
60 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
61 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
62 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
64 expect_pending_htlcs_forwardable!(nodes[1]);
65 get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
66 check_added_monitors!(nodes[1], 1);
68 // Don't bother delivering the new HTLC add/commits, instead confirming the pre-HTLC commitment
69 // transaction for nodes[1].
70 mine_transaction(&nodes[1], &bs_txn[0]);
71 check_added_monitors!(nodes[1], 1);
72 check_closed_broadcast!(nodes[1], true);
73 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
74 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
76 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
77 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 }]);
78 check_added_monitors!(nodes[1], 1);
79 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
81 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
82 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, true, true);
83 expect_payment_failed_with_update!(nodes[0], payment_hash, false, update_a.contents.short_channel_id, true);
86 fn test_spendable_output<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, spendable_tx: &Transaction) {
87 let mut spendable = node.chain_monitor.chain_monitor.get_and_clear_pending_events();
88 assert_eq!(spendable.len(), 1);
89 if let Event::SpendableOutputs { outputs } = spendable.pop().unwrap() {
90 assert_eq!(outputs.len(), 1);
91 let spend_tx = node.keys_manager.backing.spend_spendable_outputs(&[&outputs[0]], Vec::new(),
92 Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &Secp256k1::new()).unwrap();
93 check_spends!(spend_tx, spendable_tx);
98 fn revoked_output_htlc_resolution_timing() {
99 // Tests that HTLCs which were present in a broadcasted remote revoked commitment transaction
100 // are resolved only after a spend of the HTLC output reaches six confirmations. Preivously
101 // they would resolve after the revoked commitment transaction itself reaches six
103 let chanmon_cfgs = create_chanmon_cfgs(2);
104 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
105 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
106 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
108 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
110 let payment_hash_1 = route_payment(&nodes[1], &[&nodes[0]], 1_000_000).1;
112 // Get a commitment transaction which contains the HTLC we care about, but which we'll revoke
113 // before forwarding.
114 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
115 assert_eq!(revoked_local_txn.len(), 1);
117 // Route a dust payment to revoke the above commitment transaction
118 route_payment(&nodes[0], &[&nodes[1]], 1_000);
120 // Confirm the revoked commitment transaction, closing the channel.
121 mine_transaction(&nodes[1], &revoked_local_txn[0]);
122 check_added_monitors!(nodes[1], 1);
123 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
124 check_closed_broadcast!(nodes[1], true);
126 let bs_spend_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
127 assert_eq!(bs_spend_txn.len(), 2);
128 check_spends!(bs_spend_txn[0], revoked_local_txn[0]);
129 check_spends!(bs_spend_txn[1], chan.3);
131 // After the commitment transaction confirms, we should still wait on the HTLC spend
132 // transaction to confirm before resolving the HTLC.
133 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
134 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
135 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
137 // Spend the HTLC output, generating a HTLC failure event after ANTI_REORG_DELAY confirmations.
138 mine_transaction(&nodes[1], &bs_spend_txn[0]);
139 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
140 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
142 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
143 expect_payment_failed!(nodes[1], payment_hash_1, true);
147 fn chanmon_claim_value_coop_close() {
148 // Tests `get_claimable_balances` returns the correct values across a simple cooperative claim.
149 // Specifically, this tests that the channel non-HTLC balances show up in
150 // `get_claimable_balances` until the cooperative claims have confirmed and generated a
151 // `SpendableOutputs` event, and no longer.
152 let chanmon_cfgs = create_chanmon_cfgs(2);
153 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
154 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
155 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
157 let (_, _, chan_id, funding_tx) =
158 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000, InitFeatures::known(), InitFeatures::known());
159 let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
160 assert_eq!(funding_outpoint.to_channel_id(), chan_id);
162 let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
163 let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
165 assert_eq!(vec![Balance::ClaimableOnChannelClose {
166 claimable_amount_satoshis: 1_000_000 - 1_000 - chan_feerate * channel::commitment_tx_base_weight(opt_anchors) / 1000
168 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
169 assert_eq!(vec![Balance::ClaimableOnChannelClose { claimable_amount_satoshis: 1_000, }],
170 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
172 nodes[0].node.close_channel(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
173 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
174 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
175 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
176 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
178 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
179 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
180 let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
181 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
182 let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
183 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
184 let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
185 assert!(node_1_none.is_none());
187 let shutdown_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
188 assert_eq!(shutdown_tx, nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0));
189 assert_eq!(shutdown_tx.len(), 1);
191 mine_transaction(&nodes[0], &shutdown_tx[0]);
192 mine_transaction(&nodes[1], &shutdown_tx[0]);
194 assert!(nodes[0].node.list_channels().is_empty());
195 assert!(nodes[1].node.list_channels().is_empty());
197 assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
198 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
200 assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
201 claimable_amount_satoshis: 1_000_000 - 1_000 - chan_feerate * channel::commitment_tx_base_weight(opt_anchors) / 1000,
202 confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
204 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
205 assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
206 claimable_amount_satoshis: 1000,
207 confirmation_height: nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1,
209 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
211 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
212 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
214 assert_eq!(Vec::<Balance>::new(),
215 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
216 assert_eq!(Vec::<Balance>::new(),
217 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
219 test_spendable_output(&nodes[0], &shutdown_tx[0]);
220 test_spendable_output(&nodes[1], &shutdown_tx[0]);
222 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
223 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
226 fn sorted_vec<T: Ord>(mut v: Vec<T>) -> Vec<T> {
231 fn do_test_claim_value_force_close(prev_commitment_tx: bool) {
232 // Tests `get_claimable_balances` with an HTLC across a force-close.
233 // We build a channel with an HTLC pending, then force close the channel and check that the
234 // `get_claimable_balances` return value is correct as transactions confirm on-chain.
235 let mut chanmon_cfgs = create_chanmon_cfgs(2);
236 if prev_commitment_tx {
237 // We broadcast a second-to-latest commitment transaction, without providing the revocation
238 // secret to the counterparty. However, because we always immediately take the revocation
239 // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
240 // transaction which, from the point of view of our keys_manager, is revoked.
241 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
243 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
244 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
245 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
247 let (_, _, chan_id, funding_tx) =
248 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000, InitFeatures::known(), InitFeatures::known());
249 let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
250 assert_eq!(funding_outpoint.to_channel_id(), chan_id);
252 // This HTLC is immediately claimed, giving node B the preimage
253 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
254 // This HTLC is allowed to time out, letting A claim it. However, in order to test claimable
255 // balances more fully we also give B the preimage for this HTLC.
256 let (timeout_payment_preimage, timeout_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 4_000_000);
257 // This HTLC will be dust, and not be claimable at all:
258 let (dust_payment_preimage, dust_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000);
260 let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
262 let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
263 let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
265 let remote_txn = get_local_commitment_txn!(nodes[1], chan_id);
266 // Before B receives the payment preimage, it only suggests the push_msat value of 1_000 sats
267 // as claimable. A lists both its to-self balance and the (possibly-claimable) HTLCs.
268 assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
269 claimable_amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - chan_feerate *
270 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
271 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
272 claimable_amount_satoshis: 3_000,
273 claimable_height: htlc_cltv_timeout,
274 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
275 claimable_amount_satoshis: 4_000,
276 claimable_height: htlc_cltv_timeout,
278 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
279 assert_eq!(vec![Balance::ClaimableOnChannelClose {
280 claimable_amount_satoshis: 1_000,
282 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
284 nodes[1].node.claim_funds(payment_preimage);
285 check_added_monitors!(nodes[1], 1);
286 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
288 let b_htlc_msgs = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
289 // We claim the dust payment here as well, but it won't impact our claimable balances as its
290 // dust and thus doesn't appear on chain at all.
291 nodes[1].node.claim_funds(dust_payment_preimage);
292 check_added_monitors!(nodes[1], 1);
293 expect_payment_claimed!(nodes[1], dust_payment_hash, 3_000);
295 nodes[1].node.claim_funds(timeout_payment_preimage);
296 check_added_monitors!(nodes[1], 1);
297 expect_payment_claimed!(nodes[1], timeout_payment_hash, 4_000_000);
299 if prev_commitment_tx {
300 // To build a previous commitment transaction, deliver one round of commitment messages.
301 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.update_fulfill_htlcs[0]);
302 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
303 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.commitment_signed);
304 check_added_monitors!(nodes[0], 1);
305 let (as_raa, as_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
306 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
307 let _htlc_updates = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
308 check_added_monitors!(nodes[1], 1);
309 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs);
310 let _bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
311 check_added_monitors!(nodes[1], 1);
314 // Once B has received the payment preimage, it includes the value of the HTLC in its
315 // "claimable if you were to close the channel" balance.
316 let mut a_expected_balances = vec![Balance::ClaimableOnChannelClose {
317 claimable_amount_satoshis: 1_000_000 - // Channel funding value in satoshis
318 4_000 - // The to-be-failed HTLC value in satoshis
319 3_000 - // The claimed HTLC value in satoshis
320 1_000 - // The push_msat value in satoshis
321 3 - // The dust HTLC value in satoshis
322 // The commitment transaction fee with two HTLC outputs:
323 chan_feerate * (channel::commitment_tx_base_weight(opt_anchors) +
324 if prev_commitment_tx { 1 } else { 2 } *
325 channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
326 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
327 claimable_amount_satoshis: 4_000,
328 claimable_height: htlc_cltv_timeout,
330 if !prev_commitment_tx {
331 a_expected_balances.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
332 claimable_amount_satoshis: 3_000,
333 claimable_height: htlc_cltv_timeout,
336 assert_eq!(sorted_vec(a_expected_balances),
337 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
338 assert_eq!(vec![Balance::ClaimableOnChannelClose {
339 claimable_amount_satoshis: 1_000 + 3_000 + 4_000,
341 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
343 // Broadcast the closing transaction (which has both pending HTLCs in it) and get B's
344 // broadcasted HTLC claim transaction with preimage.
345 let node_b_commitment_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
346 mine_transaction(&nodes[0], &remote_txn[0]);
347 mine_transaction(&nodes[1], &remote_txn[0]);
349 let b_broadcast_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
350 assert_eq!(b_broadcast_txn.len(), if prev_commitment_tx { 4 } else { 5 });
351 if prev_commitment_tx {
352 check_spends!(b_broadcast_txn[3], b_broadcast_txn[2]);
354 assert_eq!(b_broadcast_txn[0], b_broadcast_txn[3]);
355 assert_eq!(b_broadcast_txn[1], b_broadcast_txn[4]);
357 // b_broadcast_txn[0] should spend the HTLC output of the commitment tx for 3_000 sats
358 check_spends!(b_broadcast_txn[0], remote_txn[0]);
359 check_spends!(b_broadcast_txn[1], remote_txn[0]);
360 assert_eq!(b_broadcast_txn[0].input.len(), 1);
361 assert_eq!(b_broadcast_txn[1].input.len(), 1);
362 assert_eq!(remote_txn[0].output[b_broadcast_txn[0].input[0].previous_output.vout as usize].value, 3_000);
363 assert_eq!(remote_txn[0].output[b_broadcast_txn[1].input[0].previous_output.vout as usize].value, 4_000);
364 check_spends!(b_broadcast_txn[2], funding_tx);
366 assert!(nodes[0].node.list_channels().is_empty());
367 check_closed_broadcast!(nodes[0], true);
368 check_added_monitors!(nodes[0], 1);
369 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
370 assert!(nodes[1].node.list_channels().is_empty());
371 check_closed_broadcast!(nodes[1], true);
372 check_added_monitors!(nodes[1], 1);
373 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
374 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
375 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
377 // Once the commitment transaction confirms, we will wait until ANTI_REORG_DELAY until we
378 // generate any `SpendableOutputs` events. Thus, the same balances will still be listed
379 // available in `get_claimable_balances`. However, both will swap from `ClaimableOnClose` to
380 // other Balance variants, as close has already happened.
381 assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
382 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
384 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
385 claimable_amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - chan_feerate *
386 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
387 confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
388 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
389 claimable_amount_satoshis: 3_000,
390 claimable_height: htlc_cltv_timeout,
391 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
392 claimable_amount_satoshis: 4_000,
393 claimable_height: htlc_cltv_timeout,
395 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
396 // The main non-HTLC balance is just awaiting confirmations, but the claimable height is the
397 // CSV delay, not ANTI_REORG_DELAY.
398 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
399 claimable_amount_satoshis: 1_000,
400 confirmation_height: node_b_commitment_claimable,
402 // Both HTLC balances are "contentious" as our counterparty could claim them if we wait too
404 Balance::ContentiousClaimable {
405 claimable_amount_satoshis: 3_000,
406 timeout_height: htlc_cltv_timeout,
407 }, Balance::ContentiousClaimable {
408 claimable_amount_satoshis: 4_000,
409 timeout_height: htlc_cltv_timeout,
411 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
413 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
414 expect_payment_failed!(nodes[0], dust_payment_hash, true);
415 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
417 // After ANTI_REORG_DELAY, A will consider its balance fully spendable and generate a
418 // `SpendableOutputs` event. However, B still has to wait for the CSV delay.
419 assert_eq!(sorted_vec(vec![Balance::MaybeClaimableHTLCAwaitingTimeout {
420 claimable_amount_satoshis: 3_000,
421 claimable_height: htlc_cltv_timeout,
422 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
423 claimable_amount_satoshis: 4_000,
424 claimable_height: htlc_cltv_timeout,
426 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
427 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
428 claimable_amount_satoshis: 1_000,
429 confirmation_height: node_b_commitment_claimable,
430 }, Balance::ContentiousClaimable {
431 claimable_amount_satoshis: 3_000,
432 timeout_height: htlc_cltv_timeout,
433 }, Balance::ContentiousClaimable {
434 claimable_amount_satoshis: 4_000,
435 timeout_height: htlc_cltv_timeout,
437 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
439 test_spendable_output(&nodes[0], &remote_txn[0]);
440 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
442 // After broadcasting the HTLC claim transaction, node A will still consider the HTLC
443 // possibly-claimable up to ANTI_REORG_DELAY, at which point it will drop it.
444 mine_transaction(&nodes[0], &b_broadcast_txn[0]);
445 if prev_commitment_tx {
446 expect_payment_path_successful!(nodes[0]);
448 expect_payment_sent!(nodes[0], payment_preimage);
450 assert_eq!(sorted_vec(vec![Balance::MaybeClaimableHTLCAwaitingTimeout {
451 claimable_amount_satoshis: 3_000,
452 claimable_height: htlc_cltv_timeout,
453 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
454 claimable_amount_satoshis: 4_000,
455 claimable_height: htlc_cltv_timeout,
457 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
458 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
459 assert_eq!(vec![Balance::MaybeClaimableHTLCAwaitingTimeout {
460 claimable_amount_satoshis: 4_000,
461 claimable_height: htlc_cltv_timeout,
463 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
465 // When the HTLC timeout output is spendable in the next block, A should broadcast it
466 connect_blocks(&nodes[0], htlc_cltv_timeout - nodes[0].best_block_info().1 - 1);
467 let a_broadcast_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
468 assert_eq!(a_broadcast_txn.len(), 3);
469 check_spends!(a_broadcast_txn[0], funding_tx);
470 assert_eq!(a_broadcast_txn[1].input.len(), 1);
471 check_spends!(a_broadcast_txn[1], remote_txn[0]);
472 assert_eq!(a_broadcast_txn[2].input.len(), 1);
473 check_spends!(a_broadcast_txn[2], remote_txn[0]);
474 assert_ne!(a_broadcast_txn[1].input[0].previous_output.vout,
475 a_broadcast_txn[2].input[0].previous_output.vout);
476 // a_broadcast_txn [1] and [2] should spend the HTLC outputs of the commitment tx
477 assert_eq!(remote_txn[0].output[a_broadcast_txn[1].input[0].previous_output.vout as usize].value, 3_000);
478 assert_eq!(remote_txn[0].output[a_broadcast_txn[2].input[0].previous_output.vout as usize].value, 4_000);
480 // Once the HTLC-Timeout transaction confirms, A will no longer consider the HTLC
481 // "MaybeClaimable", but instead move it to "AwaitingConfirmations".
482 mine_transaction(&nodes[0], &a_broadcast_txn[2]);
483 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
484 assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
485 claimable_amount_satoshis: 4_000,
486 confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
488 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
489 // After ANTI_REORG_DELAY, A will generate a SpendableOutputs event and drop the claimable
491 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
492 assert_eq!(Vec::<Balance>::new(),
493 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
494 expect_payment_failed!(nodes[0], timeout_payment_hash, true);
496 test_spendable_output(&nodes[0], &a_broadcast_txn[2]);
498 // Node B will no longer consider the HTLC "contentious" after the HTLC claim transaction
499 // confirms, and consider it simply "awaiting confirmations". Note that it has to wait for the
500 // standard revocable transaction CSV delay before receiving a `SpendableOutputs`.
501 let node_b_htlc_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
502 mine_transaction(&nodes[1], &b_broadcast_txn[0]);
504 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
505 claimable_amount_satoshis: 1_000,
506 confirmation_height: node_b_commitment_claimable,
507 }, Balance::ClaimableAwaitingConfirmations {
508 claimable_amount_satoshis: 3_000,
509 confirmation_height: node_b_htlc_claimable,
510 }, Balance::ContentiousClaimable {
511 claimable_amount_satoshis: 4_000,
512 timeout_height: htlc_cltv_timeout,
514 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
516 // After reaching the commitment output CSV, we'll get a SpendableOutputs event for it and have
517 // only the HTLCs claimable on node B.
518 connect_blocks(&nodes[1], node_b_commitment_claimable - nodes[1].best_block_info().1);
519 test_spendable_output(&nodes[1], &remote_txn[0]);
521 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
522 claimable_amount_satoshis: 3_000,
523 confirmation_height: node_b_htlc_claimable,
524 }, Balance::ContentiousClaimable {
525 claimable_amount_satoshis: 4_000,
526 timeout_height: htlc_cltv_timeout,
528 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
530 // After reaching the claimed HTLC output CSV, we'll get a SpendableOutptus event for it and
531 // have only one HTLC output left spendable.
532 connect_blocks(&nodes[1], node_b_htlc_claimable - nodes[1].best_block_info().1);
533 test_spendable_output(&nodes[1], &b_broadcast_txn[0]);
535 assert_eq!(vec![Balance::ContentiousClaimable {
536 claimable_amount_satoshis: 4_000,
537 timeout_height: htlc_cltv_timeout,
539 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
541 // Finally, mine the HTLC timeout transaction that A broadcasted (even though B should be able
542 // to claim this HTLC with the preimage it knows!). It will remain listed as a claimable HTLC
543 // until ANTI_REORG_DELAY confirmations on the spend.
544 mine_transaction(&nodes[1], &a_broadcast_txn[2]);
545 assert_eq!(vec![Balance::ContentiousClaimable {
546 claimable_amount_satoshis: 4_000,
547 timeout_height: htlc_cltv_timeout,
549 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
550 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
551 assert_eq!(Vec::<Balance>::new(),
552 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
556 fn test_claim_value_force_close() {
557 do_test_claim_value_force_close(true);
558 do_test_claim_value_force_close(false);
562 fn test_balances_on_local_commitment_htlcs() {
563 // Previously, when handling the broadcast of a local commitment transactions (with associated
564 // CSV delays prior to spendability), we incorrectly handled the CSV delays on HTLC
565 // transactions. This caused us to miss spendable outputs for HTLCs which were awaiting a CSV
566 // delay prior to spendability.
568 // Further, because of this, we could hit an assertion as `get_claimable_balances` asserted
569 // that HTLCs were resolved after the funding spend was resolved, which was not true if the
570 // HTLC did not have a CSV delay attached (due to the above bug or due to it being an HTLC
571 // claim by our counterparty).
572 let chanmon_cfgs = create_chanmon_cfgs(2);
573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
575 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
577 // Create a single channel with two pending HTLCs from nodes[0] to nodes[1], one which nodes[1]
578 // knows the preimage for, one which it does not.
579 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
580 let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
582 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000_000);
583 let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
584 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
585 check_added_monitors!(nodes[0], 1);
587 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
588 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
589 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
591 expect_pending_htlcs_forwardable!(nodes[1]);
592 expect_payment_received!(nodes[1], payment_hash, payment_secret, 10_000_000);
594 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 20_000_000);
595 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
596 check_added_monitors!(nodes[0], 1);
598 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
599 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
600 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
602 expect_pending_htlcs_forwardable!(nodes[1]);
603 expect_payment_received!(nodes[1], payment_hash_2, payment_secret_2, 20_000_000);
604 nodes[1].node.claim_funds(payment_preimage_2);
605 get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
606 check_added_monitors!(nodes[1], 1);
607 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000_000);
609 let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
610 let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
612 // Get nodes[0]'s commitment transaction and HTLC-Timeout transactions
613 let as_txn = get_local_commitment_txn!(nodes[0], chan_id);
614 assert_eq!(as_txn.len(), 3);
615 check_spends!(as_txn[1], as_txn[0]);
616 check_spends!(as_txn[2], as_txn[0]);
617 check_spends!(as_txn[0], funding_tx);
619 // First confirm the commitment transaction on nodes[0], which should leave us with three
620 // claimable balances.
621 let node_a_commitment_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
622 mine_transaction(&nodes[0], &as_txn[0]);
623 check_added_monitors!(nodes[0], 1);
624 check_closed_broadcast!(nodes[0], true);
625 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
627 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
628 claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
629 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
630 confirmation_height: node_a_commitment_claimable,
631 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
632 claimable_amount_satoshis: 10_000,
633 claimable_height: htlc_cltv_timeout,
634 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
635 claimable_amount_satoshis: 20_000,
636 claimable_height: htlc_cltv_timeout,
638 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
640 // Get nodes[1]'s HTLC claim tx for the second HTLC
641 mine_transaction(&nodes[1], &as_txn[0]);
642 check_added_monitors!(nodes[1], 1);
643 check_closed_broadcast!(nodes[1], true);
644 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
645 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
646 assert_eq!(bs_htlc_claim_txn.len(), 3);
647 check_spends!(bs_htlc_claim_txn[0], as_txn[0]);
648 check_spends!(bs_htlc_claim_txn[1], funding_tx);
649 check_spends!(bs_htlc_claim_txn[2], bs_htlc_claim_txn[1]);
651 // Connect blocks until the HTLCs expire, allowing us to (validly) broadcast the HTLC-Timeout
653 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
654 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
655 claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
656 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
657 confirmation_height: node_a_commitment_claimable,
658 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
659 claimable_amount_satoshis: 10_000,
660 claimable_height: htlc_cltv_timeout,
661 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
662 claimable_amount_satoshis: 20_000,
663 claimable_height: htlc_cltv_timeout,
665 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
666 assert_eq!(as_txn[1].lock_time, nodes[0].best_block_info().1 + 1); // as_txn[1] can be included in the next block
668 // Now confirm nodes[0]'s HTLC-Timeout transaction, which changes the claimable balance to an
669 // "awaiting confirmations" one.
670 let node_a_htlc_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
671 mine_transaction(&nodes[0], &as_txn[1]);
672 // Note that prior to the fix in the commit which introduced this test, this (and the next
673 // balance) check failed. With this check removed, the code panicked in the `connect_blocks`
674 // call, as described, two hunks down.
675 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
676 claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
677 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
678 confirmation_height: node_a_commitment_claimable,
679 }, Balance::ClaimableAwaitingConfirmations {
680 claimable_amount_satoshis: 10_000,
681 confirmation_height: node_a_htlc_claimable,
682 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
683 claimable_amount_satoshis: 20_000,
684 claimable_height: htlc_cltv_timeout,
686 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
688 // Now confirm nodes[1]'s HTLC claim, giving nodes[0] the preimage. Note that the "maybe
689 // claimable" balance remains until we see ANTI_REORG_DELAY blocks.
690 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
691 expect_payment_sent!(nodes[0], payment_preimage_2);
692 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
693 claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
694 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
695 confirmation_height: node_a_commitment_claimable,
696 }, Balance::ClaimableAwaitingConfirmations {
697 claimable_amount_satoshis: 10_000,
698 confirmation_height: node_a_htlc_claimable,
699 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
700 claimable_amount_satoshis: 20_000,
701 claimable_height: htlc_cltv_timeout,
703 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
705 // Finally make the HTLC transactions have ANTI_REORG_DELAY blocks. This call previously
706 // panicked as described in the test introduction. This will remove the "maybe claimable"
707 // spendable output as nodes[1] has fully claimed the second HTLC.
708 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
709 expect_payment_failed!(nodes[0], payment_hash, true);
711 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
712 claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
713 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
714 confirmation_height: node_a_commitment_claimable,
715 }, Balance::ClaimableAwaitingConfirmations {
716 claimable_amount_satoshis: 10_000,
717 confirmation_height: node_a_htlc_claimable,
719 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
721 // Connect blocks until the commitment transaction's CSV expires, providing us the relevant
722 // `SpendableOutputs` event and removing the claimable balance entry.
723 connect_blocks(&nodes[0], node_a_commitment_claimable - nodes[0].best_block_info().1);
724 assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
725 claimable_amount_satoshis: 10_000,
726 confirmation_height: node_a_htlc_claimable,
728 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
729 test_spendable_output(&nodes[0], &as_txn[0]);
731 // Connect blocks until the HTLC-Timeout's CSV expires, providing us the relevant
732 // `SpendableOutputs` event and removing the claimable balance entry.
733 connect_blocks(&nodes[0], node_a_htlc_claimable - nodes[0].best_block_info().1);
734 assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
735 test_spendable_output(&nodes[0], &as_txn[1]);