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};
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!(nodes[1]);
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 chanmon_claim_value_coop_close() {
99 // Tests `get_claimable_balances` returns the correct values across a simple cooperative claim.
100 // Specifically, this tests that the channel non-HTLC balances show up in
101 // `get_claimable_balances` until the cooperative claims have confirmed and generated a
102 // `SpendableOutputs` event, and no longer.
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_id, funding_tx) =
109 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000, InitFeatures::known(), InitFeatures::known());
110 let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
111 assert_eq!(funding_outpoint.to_channel_id(), chan_id);
113 let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
114 let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
116 assert_eq!(vec![Balance::ClaimableOnChannelClose {
117 claimable_amount_satoshis: 1_000_000 - 1_000 - chan_feerate * channel::commitment_tx_base_weight(opt_anchors) / 1000
119 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
120 assert_eq!(vec![Balance::ClaimableOnChannelClose { claimable_amount_satoshis: 1_000, }],
121 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
123 nodes[0].node.close_channel(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
124 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
125 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
126 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
127 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
129 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
130 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
131 let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
132 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
133 let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
134 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
135 let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
136 assert!(node_1_none.is_none());
138 let shutdown_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
139 assert_eq!(shutdown_tx, nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0));
140 assert_eq!(shutdown_tx.len(), 1);
142 mine_transaction(&nodes[0], &shutdown_tx[0]);
143 mine_transaction(&nodes[1], &shutdown_tx[0]);
145 assert!(nodes[0].node.list_channels().is_empty());
146 assert!(nodes[1].node.list_channels().is_empty());
148 assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
149 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
151 assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
152 claimable_amount_satoshis: 1_000_000 - 1_000 - chan_feerate * channel::commitment_tx_base_weight(opt_anchors) / 1000,
153 confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
155 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
156 assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
157 claimable_amount_satoshis: 1000,
158 confirmation_height: nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1,
160 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
162 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
163 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
165 assert_eq!(Vec::<Balance>::new(),
166 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
167 assert_eq!(Vec::<Balance>::new(),
168 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
170 test_spendable_output(&nodes[0], &shutdown_tx[0]);
171 test_spendable_output(&nodes[1], &shutdown_tx[0]);
173 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
174 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
177 fn sorted_vec<T: Ord>(mut v: Vec<T>) -> Vec<T> {
182 fn do_test_claim_value_force_close(prev_commitment_tx: bool) {
183 // Tests `get_claimable_balances` with an HTLC across a force-close.
184 // We build a channel with an HTLC pending, then force close the channel and check that the
185 // `get_claimable_balances` return value is correct as transactions confirm on-chain.
186 let mut chanmon_cfgs = create_chanmon_cfgs(2);
187 if prev_commitment_tx {
188 // We broadcast a second-to-latest commitment transaction, without providing the revocation
189 // secret to the counterparty. However, because we always immediately take the revocation
190 // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
191 // transaction which, from the point of view of our keys_manager, is revoked.
192 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
194 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
195 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
196 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
198 let (_, _, chan_id, funding_tx) =
199 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000, InitFeatures::known(), InitFeatures::known());
200 let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
201 assert_eq!(funding_outpoint.to_channel_id(), chan_id);
203 // This HTLC is immediately claimed, giving node B the preimage
204 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
205 // This HTLC is allowed to time out, letting A claim it. However, in order to test claimable
206 // balances more fully we also give B the preimage for this HTLC.
207 let (timeout_payment_preimage, timeout_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 4_000_000);
208 // This HTLC will be dust, and not be claimable at all:
209 let (dust_payment_preimage, dust_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000);
211 let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
213 let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
214 let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
216 let remote_txn = get_local_commitment_txn!(nodes[1], chan_id);
217 // Before B receives the payment preimage, it only suggests the push_msat value of 1_000 sats
218 // as claimable. A lists both its to-self balance and the (possibly-claimable) HTLCs.
219 assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
220 claimable_amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - chan_feerate *
221 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
222 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
223 claimable_amount_satoshis: 3_000,
224 claimable_height: htlc_cltv_timeout,
225 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
226 claimable_amount_satoshis: 4_000,
227 claimable_height: htlc_cltv_timeout,
229 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
230 assert_eq!(vec![Balance::ClaimableOnChannelClose {
231 claimable_amount_satoshis: 1_000,
233 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
235 nodes[1].node.claim_funds(payment_preimage);
236 check_added_monitors!(nodes[1], 1);
237 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
239 let b_htlc_msgs = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
240 // We claim the dust payment here as well, but it won't impact our claimable balances as its
241 // dust and thus doesn't appear on chain at all.
242 nodes[1].node.claim_funds(dust_payment_preimage);
243 check_added_monitors!(nodes[1], 1);
244 expect_payment_claimed!(nodes[1], dust_payment_hash, 3_000);
246 nodes[1].node.claim_funds(timeout_payment_preimage);
247 check_added_monitors!(nodes[1], 1);
248 expect_payment_claimed!(nodes[1], timeout_payment_hash, 4_000_000);
250 if prev_commitment_tx {
251 // To build a previous commitment transaction, deliver one round of commitment messages.
252 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.update_fulfill_htlcs[0]);
253 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
254 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.commitment_signed);
255 check_added_monitors!(nodes[0], 1);
256 let (as_raa, as_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
257 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
258 let _htlc_updates = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
259 check_added_monitors!(nodes[1], 1);
260 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs);
261 let _bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
262 check_added_monitors!(nodes[1], 1);
265 // Once B has received the payment preimage, it includes the value of the HTLC in its
266 // "claimable if you were to close the channel" balance.
267 let mut a_expected_balances = vec![Balance::ClaimableOnChannelClose {
268 claimable_amount_satoshis: 1_000_000 - // Channel funding value in satoshis
269 4_000 - // The to-be-failed HTLC value in satoshis
270 3_000 - // The claimed HTLC value in satoshis
271 1_000 - // The push_msat value in satoshis
272 3 - // The dust HTLC value in satoshis
273 // The commitment transaction fee with two HTLC outputs:
274 chan_feerate * (channel::commitment_tx_base_weight(opt_anchors) +
275 if prev_commitment_tx { 1 } else { 2 } *
276 channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
277 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
278 claimable_amount_satoshis: 4_000,
279 claimable_height: htlc_cltv_timeout,
281 if !prev_commitment_tx {
282 a_expected_balances.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
283 claimable_amount_satoshis: 3_000,
284 claimable_height: htlc_cltv_timeout,
287 assert_eq!(sorted_vec(a_expected_balances),
288 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
289 assert_eq!(vec![Balance::ClaimableOnChannelClose {
290 claimable_amount_satoshis: 1_000 + 3_000 + 4_000,
292 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
294 // Broadcast the closing transaction (which has both pending HTLCs in it) and get B's
295 // broadcasted HTLC claim transaction with preimage.
296 let node_b_commitment_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
297 mine_transaction(&nodes[0], &remote_txn[0]);
298 mine_transaction(&nodes[1], &remote_txn[0]);
300 let b_broadcast_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
301 assert_eq!(b_broadcast_txn.len(), if prev_commitment_tx { 4 } else { 5 });
302 if prev_commitment_tx {
303 check_spends!(b_broadcast_txn[3], b_broadcast_txn[2]);
305 assert_eq!(b_broadcast_txn[0], b_broadcast_txn[3]);
306 assert_eq!(b_broadcast_txn[1], b_broadcast_txn[4]);
308 // b_broadcast_txn[0] should spend the HTLC output of the commitment tx for 3_000 sats
309 check_spends!(b_broadcast_txn[0], remote_txn[0]);
310 check_spends!(b_broadcast_txn[1], remote_txn[0]);
311 assert_eq!(b_broadcast_txn[0].input.len(), 1);
312 assert_eq!(b_broadcast_txn[1].input.len(), 1);
313 assert_eq!(remote_txn[0].output[b_broadcast_txn[0].input[0].previous_output.vout as usize].value, 3_000);
314 assert_eq!(remote_txn[0].output[b_broadcast_txn[1].input[0].previous_output.vout as usize].value, 4_000);
315 check_spends!(b_broadcast_txn[2], funding_tx);
317 assert!(nodes[0].node.list_channels().is_empty());
318 check_closed_broadcast!(nodes[0], true);
319 check_added_monitors!(nodes[0], 1);
320 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
321 assert!(nodes[1].node.list_channels().is_empty());
322 check_closed_broadcast!(nodes[1], true);
323 check_added_monitors!(nodes[1], 1);
324 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
325 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
326 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
328 // Once the commitment transaction confirms, we will wait until ANTI_REORG_DELAY until we
329 // generate any `SpendableOutputs` events. Thus, the same balances will still be listed
330 // available in `get_claimable_balances`. However, both will swap from `ClaimableOnClose` to
331 // other Balance variants, as close has already happened.
332 assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
333 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
335 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
336 claimable_amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - chan_feerate *
337 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
338 confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
339 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
340 claimable_amount_satoshis: 3_000,
341 claimable_height: htlc_cltv_timeout,
342 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
343 claimable_amount_satoshis: 4_000,
344 claimable_height: htlc_cltv_timeout,
346 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
347 // The main non-HTLC balance is just awaiting confirmations, but the claimable height is the
348 // CSV delay, not ANTI_REORG_DELAY.
349 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
350 claimable_amount_satoshis: 1_000,
351 confirmation_height: node_b_commitment_claimable,
353 // Both HTLC balances are "contentious" as our counterparty could claim them if we wait too
355 Balance::ContentiousClaimable {
356 claimable_amount_satoshis: 3_000,
357 timeout_height: htlc_cltv_timeout,
358 }, Balance::ContentiousClaimable {
359 claimable_amount_satoshis: 4_000,
360 timeout_height: htlc_cltv_timeout,
362 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
364 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
365 expect_payment_failed!(nodes[0], dust_payment_hash, true);
366 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
368 // After ANTI_REORG_DELAY, A will consider its balance fully spendable and generate a
369 // `SpendableOutputs` event. However, B still has to wait for the CSV delay.
370 assert_eq!(sorted_vec(vec![Balance::MaybeClaimableHTLCAwaitingTimeout {
371 claimable_amount_satoshis: 3_000,
372 claimable_height: htlc_cltv_timeout,
373 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
374 claimable_amount_satoshis: 4_000,
375 claimable_height: htlc_cltv_timeout,
377 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
378 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
379 claimable_amount_satoshis: 1_000,
380 confirmation_height: node_b_commitment_claimable,
381 }, Balance::ContentiousClaimable {
382 claimable_amount_satoshis: 3_000,
383 timeout_height: htlc_cltv_timeout,
384 }, Balance::ContentiousClaimable {
385 claimable_amount_satoshis: 4_000,
386 timeout_height: htlc_cltv_timeout,
388 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
390 test_spendable_output(&nodes[0], &remote_txn[0]);
391 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
393 // After broadcasting the HTLC claim transaction, node A will still consider the HTLC
394 // possibly-claimable up to ANTI_REORG_DELAY, at which point it will drop it.
395 mine_transaction(&nodes[0], &b_broadcast_txn[0]);
396 if prev_commitment_tx {
397 expect_payment_path_successful!(nodes[0]);
399 expect_payment_sent!(nodes[0], payment_preimage);
401 assert_eq!(sorted_vec(vec![Balance::MaybeClaimableHTLCAwaitingTimeout {
402 claimable_amount_satoshis: 3_000,
403 claimable_height: htlc_cltv_timeout,
404 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
405 claimable_amount_satoshis: 4_000,
406 claimable_height: htlc_cltv_timeout,
408 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
409 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
410 assert_eq!(vec![Balance::MaybeClaimableHTLCAwaitingTimeout {
411 claimable_amount_satoshis: 4_000,
412 claimable_height: htlc_cltv_timeout,
414 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
416 // When the HTLC timeout output is spendable in the next block, A should broadcast it
417 connect_blocks(&nodes[0], htlc_cltv_timeout - nodes[0].best_block_info().1 - 1);
418 let a_broadcast_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
419 assert_eq!(a_broadcast_txn.len(), 3);
420 check_spends!(a_broadcast_txn[0], funding_tx);
421 assert_eq!(a_broadcast_txn[1].input.len(), 1);
422 check_spends!(a_broadcast_txn[1], remote_txn[0]);
423 assert_eq!(a_broadcast_txn[2].input.len(), 1);
424 check_spends!(a_broadcast_txn[2], remote_txn[0]);
425 assert_ne!(a_broadcast_txn[1].input[0].previous_output.vout,
426 a_broadcast_txn[2].input[0].previous_output.vout);
427 // a_broadcast_txn [1] and [2] should spend the HTLC outputs of the commitment tx
428 assert_eq!(remote_txn[0].output[a_broadcast_txn[1].input[0].previous_output.vout as usize].value, 3_000);
429 assert_eq!(remote_txn[0].output[a_broadcast_txn[2].input[0].previous_output.vout as usize].value, 4_000);
431 // Once the HTLC-Timeout transaction confirms, A will no longer consider the HTLC
432 // "MaybeClaimable", but instead move it to "AwaitingConfirmations".
433 mine_transaction(&nodes[0], &a_broadcast_txn[2]);
434 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
435 assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
436 claimable_amount_satoshis: 4_000,
437 confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
439 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
440 // After ANTI_REORG_DELAY, A will generate a SpendableOutputs event and drop the claimable
442 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
443 assert_eq!(Vec::<Balance>::new(),
444 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
445 expect_payment_failed!(nodes[0], timeout_payment_hash, true);
447 test_spendable_output(&nodes[0], &a_broadcast_txn[2]);
449 // Node B will no longer consider the HTLC "contentious" after the HTLC claim transaction
450 // confirms, and consider it simply "awaiting confirmations". Note that it has to wait for the
451 // standard revocable transaction CSV delay before receiving a `SpendableOutputs`.
452 let node_b_htlc_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
453 mine_transaction(&nodes[1], &b_broadcast_txn[0]);
455 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
456 claimable_amount_satoshis: 1_000,
457 confirmation_height: node_b_commitment_claimable,
458 }, Balance::ClaimableAwaitingConfirmations {
459 claimable_amount_satoshis: 3_000,
460 confirmation_height: node_b_htlc_claimable,
461 }, Balance::ContentiousClaimable {
462 claimable_amount_satoshis: 4_000,
463 timeout_height: htlc_cltv_timeout,
465 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
467 // After reaching the commitment output CSV, we'll get a SpendableOutputs event for it and have
468 // only the HTLCs claimable on node B.
469 connect_blocks(&nodes[1], node_b_commitment_claimable - nodes[1].best_block_info().1);
470 test_spendable_output(&nodes[1], &remote_txn[0]);
472 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
473 claimable_amount_satoshis: 3_000,
474 confirmation_height: node_b_htlc_claimable,
475 }, Balance::ContentiousClaimable {
476 claimable_amount_satoshis: 4_000,
477 timeout_height: htlc_cltv_timeout,
479 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
481 // After reaching the claimed HTLC output CSV, we'll get a SpendableOutptus event for it and
482 // have only one HTLC output left spendable.
483 connect_blocks(&nodes[1], node_b_htlc_claimable - nodes[1].best_block_info().1);
484 test_spendable_output(&nodes[1], &b_broadcast_txn[0]);
486 assert_eq!(vec![Balance::ContentiousClaimable {
487 claimable_amount_satoshis: 4_000,
488 timeout_height: htlc_cltv_timeout,
490 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
492 // Finally, mine the HTLC timeout transaction that A broadcasted (even though B should be able
493 // to claim this HTLC with the preimage it knows!). It will remain listed as a claimable HTLC
494 // until ANTI_REORG_DELAY confirmations on the spend.
495 mine_transaction(&nodes[1], &a_broadcast_txn[2]);
496 assert_eq!(vec![Balance::ContentiousClaimable {
497 claimable_amount_satoshis: 4_000,
498 timeout_height: htlc_cltv_timeout,
500 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
501 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
502 assert_eq!(Vec::<Balance>::new(),
503 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
507 fn test_claim_value_force_close() {
508 do_test_claim_value_force_close(true);
509 do_test_claim_value_force_close(false);
513 fn test_balances_on_local_commitment_htlcs() {
514 // Previously, when handling the broadcast of a local commitment transactions (with associated
515 // CSV delays prior to spendability), we incorrectly handled the CSV delays on HTLC
516 // transactions. This caused us to miss spendable outputs for HTLCs which were awaiting a CSV
517 // delay prior to spendability.
519 // Further, because of this, we could hit an assertion as `get_claimable_balances` asserted
520 // that HTLCs were resolved after the funding spend was resolved, which was not true if the
521 // HTLC did not have a CSV delay attached (due to the above bug or due to it being an HTLC
522 // claim by our counterparty).
523 let chanmon_cfgs = create_chanmon_cfgs(2);
524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
526 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
528 // Create a single channel with two pending HTLCs from nodes[0] to nodes[1], one which nodes[1]
529 // knows the preimage for, one which it does not.
530 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
531 let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
533 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000_000);
534 let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
535 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
536 check_added_monitors!(nodes[0], 1);
538 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
539 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
540 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
542 expect_pending_htlcs_forwardable!(nodes[1]);
543 expect_payment_received!(nodes[1], payment_hash, payment_secret, 10_000_000);
545 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 20_000_000);
546 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
547 check_added_monitors!(nodes[0], 1);
549 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
550 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
551 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false);
553 expect_pending_htlcs_forwardable!(nodes[1]);
554 expect_payment_received!(nodes[1], payment_hash_2, payment_secret_2, 20_000_000);
555 nodes[1].node.claim_funds(payment_preimage_2);
556 get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
557 check_added_monitors!(nodes[1], 1);
558 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000_000);
560 let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
561 let opt_anchors = get_opt_anchors!(nodes[0], chan_id);
563 // Get nodes[0]'s commitment transaction and HTLC-Timeout transactions
564 let as_txn = get_local_commitment_txn!(nodes[0], chan_id);
565 assert_eq!(as_txn.len(), 3);
566 check_spends!(as_txn[1], as_txn[0]);
567 check_spends!(as_txn[2], as_txn[0]);
568 check_spends!(as_txn[0], funding_tx);
570 // First confirm the commitment transaction on nodes[0], which should leave us with three
571 // claimable balances.
572 let node_a_commitment_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
573 mine_transaction(&nodes[0], &as_txn[0]);
574 check_added_monitors!(nodes[0], 1);
575 check_closed_broadcast!(nodes[0], true);
576 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
578 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
579 claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
580 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
581 confirmation_height: node_a_commitment_claimable,
582 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
583 claimable_amount_satoshis: 10_000,
584 claimable_height: htlc_cltv_timeout,
585 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
586 claimable_amount_satoshis: 20_000,
587 claimable_height: htlc_cltv_timeout,
589 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
591 // Get nodes[1]'s HTLC claim tx for the second HTLC
592 mine_transaction(&nodes[1], &as_txn[0]);
593 check_added_monitors!(nodes[1], 1);
594 check_closed_broadcast!(nodes[1], true);
595 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
596 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
597 assert_eq!(bs_htlc_claim_txn.len(), 3);
598 check_spends!(bs_htlc_claim_txn[0], as_txn[0]);
599 check_spends!(bs_htlc_claim_txn[1], funding_tx);
600 check_spends!(bs_htlc_claim_txn[2], bs_htlc_claim_txn[1]);
602 // Connect blocks until the HTLCs expire, allowing us to (validly) broadcast the HTLC-Timeout
604 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
605 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
606 claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
607 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
608 confirmation_height: node_a_commitment_claimable,
609 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
610 claimable_amount_satoshis: 10_000,
611 claimable_height: htlc_cltv_timeout,
612 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
613 claimable_amount_satoshis: 20_000,
614 claimable_height: htlc_cltv_timeout,
616 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
617 assert_eq!(as_txn[1].lock_time, nodes[0].best_block_info().1 + 1); // as_txn[1] can be included in the next block
619 // Now confirm nodes[0]'s HTLC-Timeout transaction, which changes the claimable balance to an
620 // "awaiting confirmations" one.
621 let node_a_htlc_claimable = nodes[0].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
622 mine_transaction(&nodes[0], &as_txn[1]);
623 // Note that prior to the fix in the commit which introduced this test, this (and the next
624 // balance) check failed. With this check removed, the code panicked in the `connect_blocks`
625 // call, as described, two hunks down.
626 assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
627 claimable_amount_satoshis: 1_000_000 - 10_000 - 20_000 - chan_feerate *
628 (channel::commitment_tx_base_weight(opt_anchors) + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
629 confirmation_height: node_a_commitment_claimable,
630 }, Balance::ClaimableAwaitingConfirmations {
631 claimable_amount_satoshis: 10_000,
632 confirmation_height: node_a_htlc_claimable,
633 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
634 claimable_amount_satoshis: 20_000,
635 claimable_height: htlc_cltv_timeout,
637 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
639 // Now confirm nodes[1]'s HTLC claim, giving nodes[0] the preimage. Note that the "maybe
640 // claimable" balance remains until we see ANTI_REORG_DELAY blocks.
641 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
642 expect_payment_sent!(nodes[0], payment_preimage_2);
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 }, Balance::ClaimableAwaitingConfirmations {
648 claimable_amount_satoshis: 10_000,
649 confirmation_height: node_a_htlc_claimable,
650 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
651 claimable_amount_satoshis: 20_000,
652 claimable_height: htlc_cltv_timeout,
654 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
656 // Finally make the HTLC transactions have ANTI_REORG_DELAY blocks. This call previously
657 // panicked as described in the test introduction. This will remove the "maybe claimable"
658 // spendable output as nodes[1] has fully claimed the second HTLC.
659 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
660 expect_payment_failed!(nodes[0], payment_hash, true);
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 }, Balance::ClaimableAwaitingConfirmations {
667 claimable_amount_satoshis: 10_000,
668 confirmation_height: node_a_htlc_claimable,
670 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
672 // Connect blocks until the commitment transaction's CSV expires, providing us the relevant
673 // `SpendableOutputs` event and removing the claimable balance entry.
674 connect_blocks(&nodes[0], node_a_commitment_claimable - nodes[0].best_block_info().1);
675 assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
676 claimable_amount_satoshis: 10_000,
677 confirmation_height: node_a_htlc_claimable,
679 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
680 test_spendable_output(&nodes[0], &as_txn[0]);
682 // Connect blocks until the HTLC-Timeout's CSV expires, providing us the relevant
683 // `SpendableOutputs` event and removing the claimable balance entry.
684 connect_blocks(&nodes[0], node_a_htlc_claimable - nodes[0].best_block_info().1);
685 assert!(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances().is_empty());
686 test_spendable_output(&nodes[0], &as_txn[1]);