Add mpp_timeout and invalid_onion_payload descriptions & handling
[rust-lightning] / lightning / src / ln / monitor_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Further functional tests which test blockchain reorganizations.
11
12 use chain::channelmonitor::{ANTI_REORG_DELAY, Balance};
13 use chain::transaction::OutPoint;
14 use ln::channel;
15 use ln::channelmanager::BREAKDOWN_TIMEOUT;
16 use ln::features::InitFeatures;
17 use ln::msgs::ChannelMessageHandler;
18 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
19 use routing::network_graph::NetworkUpdate;
20
21 use bitcoin::blockdata::script::Builder;
22 use bitcoin::blockdata::opcodes;
23 use bitcoin::secp256k1::Secp256k1;
24
25 use prelude::*;
26
27 use ln::functional_test_utils::*;
28
29 #[test]
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
36         // HTLC.
37         //
38         // However, previously, we did not do this, ignoring the HTLC entirely.
39         //
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.
42         //
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);
50
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());
53
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);
57
58         let bs_txn = get_local_commitment_txn!(nodes[1], chan_id_2);
59
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);
63
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);
67
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());
75
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());
80
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);
84 }
85
86 #[test]
87 fn chanmon_claim_value_coop_close() {
88         // Tests `get_claimable_balances` returns the correct values across a simple cooperative claim.
89         // Specifically, this tests that the channel non-HTLC balances show up in
90         // `get_claimable_balances` until the cooperative claims have confirmed and generated a
91         // `SpendableOutputs` event, and no longer.
92         let chanmon_cfgs = create_chanmon_cfgs(2);
93         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
94         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
95         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
96
97         let (_, _, chan_id, funding_tx) =
98                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000, InitFeatures::known(), InitFeatures::known());
99         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
100         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
101
102         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
103
104         assert_eq!(vec![Balance::ClaimableOnChannelClose {
105                         claimable_amount_satoshis: 1_000_000 - 1_000 - chan_feerate * channel::COMMITMENT_TX_BASE_WEIGHT / 1000
106                 }],
107                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
108         assert_eq!(vec![Balance::ClaimableOnChannelClose { claimable_amount_satoshis: 1_000, }],
109                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
110
111         nodes[0].node.close_channel(&chan_id).unwrap();
112         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
113         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
114         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
115         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
116
117         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
118         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
119         let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
120         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
121         let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
122         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
123         let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
124         assert!(node_1_none.is_none());
125
126         let shutdown_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
127         assert_eq!(shutdown_tx, nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0));
128         assert_eq!(shutdown_tx.len(), 1);
129
130         mine_transaction(&nodes[0], &shutdown_tx[0]);
131         mine_transaction(&nodes[1], &shutdown_tx[0]);
132
133         assert!(nodes[0].node.list_channels().is_empty());
134         assert!(nodes[1].node.list_channels().is_empty());
135
136         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
137         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
138
139         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
140                         claimable_amount_satoshis: 1_000_000 - 1_000 - chan_feerate * channel::COMMITMENT_TX_BASE_WEIGHT / 1000,
141                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
142                 }],
143                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
144         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
145                         claimable_amount_satoshis: 1000,
146                         confirmation_height: nodes[1].best_block_info().1 + ANTI_REORG_DELAY - 1,
147                 }],
148                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
149
150         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
151         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
152
153         assert_eq!(Vec::<Balance>::new(),
154                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
155         assert_eq!(Vec::<Balance>::new(),
156                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
157
158         let mut node_a_spendable = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
159         assert_eq!(node_a_spendable.len(), 1);
160         if let Event::SpendableOutputs { outputs } = node_a_spendable.pop().unwrap() {
161                 assert_eq!(outputs.len(), 1);
162                 let spend_tx = nodes[0].keys_manager.backing.spend_spendable_outputs(&[&outputs[0]], Vec::new(),
163                         Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &Secp256k1::new()).unwrap();
164                 check_spends!(spend_tx, shutdown_tx[0]);
165         }
166
167         let mut node_b_spendable = nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events();
168         assert_eq!(node_b_spendable.len(), 1);
169         if let Event::SpendableOutputs { outputs } = node_b_spendable.pop().unwrap() {
170                 assert_eq!(outputs.len(), 1);
171                 let spend_tx = nodes[1].keys_manager.backing.spend_spendable_outputs(&[&outputs[0]], Vec::new(),
172                         Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &Secp256k1::new()).unwrap();
173                 check_spends!(spend_tx, shutdown_tx[0]);
174         }
175         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
176         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
177 }
178
179 fn sorted_vec<T: Ord>(mut v: Vec<T>) -> Vec<T> {
180         v.sort_unstable();
181         v
182 }
183
184 fn do_test_claim_value_force_close(prev_commitment_tx: bool) {
185         // Tests `get_claimable_balances` with an HTLC across a force-close.
186         // We build a channel with an HTLC pending, then force close the channel and check that the
187         // `get_claimable_balances` return value is correct as transactions confirm on-chain.
188         let mut chanmon_cfgs = create_chanmon_cfgs(2);
189         if prev_commitment_tx {
190                 // We broadcast a second-to-latest commitment transaction, without providing the revocation
191                 // secret to the counterparty. However, because we always immediately take the revocation
192                 // secret from the keys_manager, we would panic at broadcast as we're trying to sign a
193                 // transaction which, from the point of view of our keys_manager, is revoked.
194                 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
195         }
196         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
197         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
198         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
199
200         let (_, _, chan_id, funding_tx) =
201                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 1_000_000, InitFeatures::known(), InitFeatures::known());
202         let funding_outpoint = OutPoint { txid: funding_tx.txid(), index: 0 };
203         assert_eq!(funding_outpoint.to_channel_id(), chan_id);
204
205         // This HTLC is immediately claimed, giving node B the preimage
206         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
207         // This HTLC is allowed to time out, letting A claim it. However, in order to test claimable
208         // balances more fully we also give B the preimage for this HTLC.
209         let (timeout_payment_preimage, timeout_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 4_000_000);
210         // This HTLC will be dust, and not be claimable at all:
211         let (dust_payment_preimage, dust_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000);
212
213         let htlc_cltv_timeout = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 1; // Note ChannelManager adds one to CLTV timeouts for safety
214
215         let chan_feerate = get_feerate!(nodes[0], chan_id) as u64;
216
217         let remote_txn = get_local_commitment_txn!(nodes[1], chan_id);
218         // Before B receives the payment preimage, it only suggests the push_msat value of 1_000 sats
219         // as claimable. A lists both its to-self balance and the (possibly-claimable) HTLCs.
220         assert_eq!(sorted_vec(vec![Balance::ClaimableOnChannelClose {
221                         claimable_amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - chan_feerate *
222                                 (channel::COMMITMENT_TX_BASE_WEIGHT + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
223                 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
224                         claimable_amount_satoshis: 3_000,
225                         claimable_height: htlc_cltv_timeout,
226                 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
227                         claimable_amount_satoshis: 4_000,
228                         claimable_height: htlc_cltv_timeout,
229                 }]),
230                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
231         assert_eq!(vec![Balance::ClaimableOnChannelClose {
232                         claimable_amount_satoshis: 1_000,
233                 }],
234                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
235
236         nodes[1].node.claim_funds(payment_preimage);
237         check_added_monitors!(nodes[1], 1);
238         let b_htlc_msgs = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
239         // We claim the dust payment here as well, but it won't impact our claimable balances as its
240         // dust and thus doesn't appear on chain at all.
241         nodes[1].node.claim_funds(dust_payment_preimage);
242         check_added_monitors!(nodes[1], 1);
243         nodes[1].node.claim_funds(timeout_payment_preimage);
244         check_added_monitors!(nodes[1], 1);
245
246         if prev_commitment_tx {
247                 // To build a previous commitment transaction, deliver one round of commitment messages.
248                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.update_fulfill_htlcs[0]);
249                 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
250                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &b_htlc_msgs.commitment_signed);
251                 check_added_monitors!(nodes[0], 1);
252                 let (as_raa, as_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
253                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
254                 let _htlc_updates = get_htlc_update_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
255                 check_added_monitors!(nodes[1], 1);
256                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs);
257                 let _bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
258                 check_added_monitors!(nodes[1], 1);
259         }
260
261         // Once B has received the payment preimage, it includes the value of the HTLC in its
262         // "claimable if you were to close the channel" balance.
263         let mut a_expected_balances = vec![Balance::ClaimableOnChannelClose {
264                         claimable_amount_satoshis: 1_000_000 - // Channel funding value in satoshis
265                                 4_000 - // The to-be-failed HTLC value in satoshis
266                                 3_000 - // The claimed HTLC value in satoshis
267                                 1_000 - // The push_msat value in satoshis
268                                 3 - // The dust HTLC value in satoshis
269                                 // The commitment transaction fee with two HTLC outputs:
270                                 chan_feerate * (channel::COMMITMENT_TX_BASE_WEIGHT +
271                                                                 if prev_commitment_tx { 1 } else { 2 } *
272                                                                 channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
273                 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
274                         claimable_amount_satoshis: 4_000,
275                         claimable_height: htlc_cltv_timeout,
276                 }];
277         if !prev_commitment_tx {
278                 a_expected_balances.push(Balance::MaybeClaimableHTLCAwaitingTimeout {
279                         claimable_amount_satoshis: 3_000,
280                         claimable_height: htlc_cltv_timeout,
281                 });
282         }
283         assert_eq!(sorted_vec(a_expected_balances),
284                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
285         assert_eq!(vec![Balance::ClaimableOnChannelClose {
286                         claimable_amount_satoshis: 1_000 + 3_000 + 4_000,
287                 }],
288                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
289
290         // Broadcast the closing transaction (which has both pending HTLCs in it) and get B's
291         // broadcasted HTLC claim transaction with preimage.
292         let node_b_commitment_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
293         mine_transaction(&nodes[0], &remote_txn[0]);
294         mine_transaction(&nodes[1], &remote_txn[0]);
295
296         let b_broadcast_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
297         assert_eq!(b_broadcast_txn.len(), if prev_commitment_tx { 4 } else { 5 });
298         if prev_commitment_tx {
299                 check_spends!(b_broadcast_txn[3], b_broadcast_txn[2]);
300         } else {
301                 assert_eq!(b_broadcast_txn[0], b_broadcast_txn[3]);
302                 assert_eq!(b_broadcast_txn[1], b_broadcast_txn[4]);
303         }
304         // b_broadcast_txn[0] should spend the HTLC output of the commitment tx for 3_000 sats
305         check_spends!(b_broadcast_txn[0], remote_txn[0]);
306         check_spends!(b_broadcast_txn[1], remote_txn[0]);
307         assert_eq!(b_broadcast_txn[0].input.len(), 1);
308         assert_eq!(b_broadcast_txn[1].input.len(), 1);
309         assert_eq!(remote_txn[0].output[b_broadcast_txn[0].input[0].previous_output.vout as usize].value, 3_000);
310         assert_eq!(remote_txn[0].output[b_broadcast_txn[1].input[0].previous_output.vout as usize].value, 4_000);
311         check_spends!(b_broadcast_txn[2], funding_tx);
312
313         assert!(nodes[0].node.list_channels().is_empty());
314         check_closed_broadcast!(nodes[0], true);
315         check_added_monitors!(nodes[0], 1);
316         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
317         assert!(nodes[1].node.list_channels().is_empty());
318         check_closed_broadcast!(nodes[1], true);
319         check_added_monitors!(nodes[1], 1);
320         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
321         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
322         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
323
324         // Once the commitment transaction confirms, we will wait until ANTI_REORG_DELAY until we
325         // generate any `SpendableOutputs` events. Thus, the same balances will still be listed
326         // available in `get_claimable_balances`. However, both will swap from `ClaimableOnClose` to
327         // other Balance variants, as close has already happened.
328         assert!(nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
329         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
330
331         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
332                         claimable_amount_satoshis: 1_000_000 - 3_000 - 4_000 - 1_000 - 3 - chan_feerate *
333                                 (channel::COMMITMENT_TX_BASE_WEIGHT + 2 * channel::COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000,
334                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
335                 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
336                         claimable_amount_satoshis: 3_000,
337                         claimable_height: htlc_cltv_timeout,
338                 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
339                         claimable_amount_satoshis: 4_000,
340                         claimable_height: htlc_cltv_timeout,
341                 }]),
342                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
343         // The main non-HTLC balance is just awaiting confirmations, but the claimable height is the
344         // CSV delay, not ANTI_REORG_DELAY.
345         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
346                         claimable_amount_satoshis: 1_000,
347                         confirmation_height: node_b_commitment_claimable,
348                 },
349                 // Both HTLC balances are "contentious" as our counterparty could claim them if we wait too
350                 // long.
351                 Balance::ContentiousClaimable {
352                         claimable_amount_satoshis: 3_000,
353                         timeout_height: htlc_cltv_timeout,
354                 }, Balance::ContentiousClaimable {
355                         claimable_amount_satoshis: 4_000,
356                         timeout_height: htlc_cltv_timeout,
357                 }]),
358                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
359
360         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
361         expect_payment_failed!(nodes[0], dust_payment_hash, true);
362         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
363
364         // After ANTI_REORG_DELAY, A will consider its balance fully spendable and generate a
365         // `SpendableOutputs` event. However, B still has to wait for the CSV delay.
366         assert_eq!(sorted_vec(vec![Balance::MaybeClaimableHTLCAwaitingTimeout {
367                         claimable_amount_satoshis: 3_000,
368                         claimable_height: htlc_cltv_timeout,
369                 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
370                         claimable_amount_satoshis: 4_000,
371                         claimable_height: htlc_cltv_timeout,
372                 }]),
373                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
374         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
375                         claimable_amount_satoshis: 1_000,
376                         confirmation_height: node_b_commitment_claimable,
377                 }, Balance::ContentiousClaimable {
378                         claimable_amount_satoshis: 3_000,
379                         timeout_height: htlc_cltv_timeout,
380                 }, Balance::ContentiousClaimable {
381                         claimable_amount_satoshis: 4_000,
382                         timeout_height: htlc_cltv_timeout,
383                 }]),
384                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
385
386         let mut node_a_spendable = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
387         assert_eq!(node_a_spendable.len(), 1);
388         if let Event::SpendableOutputs { outputs } = node_a_spendable.pop().unwrap() {
389                 assert_eq!(outputs.len(), 1);
390                 let spend_tx = nodes[0].keys_manager.backing.spend_spendable_outputs(&[&outputs[0]], Vec::new(),
391                         Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &Secp256k1::new()).unwrap();
392                 check_spends!(spend_tx, remote_txn[0]);
393         }
394
395         assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
396
397         // After broadcasting the HTLC claim transaction, node A will still consider the HTLC
398         // possibly-claimable up to ANTI_REORG_DELAY, at which point it will drop it.
399         mine_transaction(&nodes[0], &b_broadcast_txn[0]);
400         if prev_commitment_tx {
401                 expect_payment_path_successful!(nodes[0]);
402         } else {
403                 expect_payment_sent!(nodes[0], payment_preimage);
404         }
405         assert_eq!(sorted_vec(vec![Balance::MaybeClaimableHTLCAwaitingTimeout {
406                         claimable_amount_satoshis: 3_000,
407                         claimable_height: htlc_cltv_timeout,
408                 }, Balance::MaybeClaimableHTLCAwaitingTimeout {
409                         claimable_amount_satoshis: 4_000,
410                         claimable_height: htlc_cltv_timeout,
411                 }]),
412                 sorted_vec(nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
413         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
414         assert_eq!(vec![Balance::MaybeClaimableHTLCAwaitingTimeout {
415                         claimable_amount_satoshis: 4_000,
416                         claimable_height: htlc_cltv_timeout,
417                 }],
418                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
419
420         // When the HTLC timeout output is spendable in the next block, A should broadcast it
421         connect_blocks(&nodes[0], htlc_cltv_timeout - nodes[0].best_block_info().1 - 1);
422         let a_broadcast_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
423         assert_eq!(a_broadcast_txn.len(), 3);
424         check_spends!(a_broadcast_txn[0], funding_tx);
425         assert_eq!(a_broadcast_txn[1].input.len(), 1);
426         check_spends!(a_broadcast_txn[1], remote_txn[0]);
427         assert_eq!(a_broadcast_txn[2].input.len(), 1);
428         check_spends!(a_broadcast_txn[2], remote_txn[0]);
429         assert_ne!(a_broadcast_txn[1].input[0].previous_output.vout,
430                    a_broadcast_txn[2].input[0].previous_output.vout);
431         // a_broadcast_txn [1] and [2] should spend the HTLC outputs of the commitment tx
432         assert_eq!(remote_txn[0].output[a_broadcast_txn[1].input[0].previous_output.vout as usize].value, 3_000);
433         assert_eq!(remote_txn[0].output[a_broadcast_txn[2].input[0].previous_output.vout as usize].value, 4_000);
434
435         // Once the HTLC-Timeout transaction confirms, A will no longer consider the HTLC
436         // "MaybeClaimable", but instead move it to "AwaitingConfirmations".
437         mine_transaction(&nodes[0], &a_broadcast_txn[2]);
438         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
439         assert_eq!(vec![Balance::ClaimableAwaitingConfirmations {
440                         claimable_amount_satoshis: 4_000,
441                         confirmation_height: nodes[0].best_block_info().1 + ANTI_REORG_DELAY - 1,
442                 }],
443                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
444         // After ANTI_REORG_DELAY, A will generate a SpendableOutputs event and drop the claimable
445         // balance entry.
446         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
447         assert_eq!(Vec::<Balance>::new(),
448                 nodes[0].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
449         expect_payment_failed!(nodes[0], timeout_payment_hash, true);
450
451         let mut node_a_spendable = nodes[0].chain_monitor.chain_monitor.get_and_clear_pending_events();
452         assert_eq!(node_a_spendable.len(), 1);
453         if let Event::SpendableOutputs { outputs } = node_a_spendable.pop().unwrap() {
454                 assert_eq!(outputs.len(), 1);
455                 let spend_tx = nodes[0].keys_manager.backing.spend_spendable_outputs(&[&outputs[0]], Vec::new(),
456                         Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &Secp256k1::new()).unwrap();
457                 check_spends!(spend_tx, a_broadcast_txn[2]);
458         } else { panic!(); }
459
460         // Node B will no longer consider the HTLC "contentious" after the HTLC claim transaction
461         // confirms, and consider it simply "awaiting confirmations". Note that it has to wait for the
462         // standard revocable transaction CSV delay before receiving a `SpendableOutputs`.
463         let node_b_htlc_claimable = nodes[1].best_block_info().1 + BREAKDOWN_TIMEOUT as u32;
464         mine_transaction(&nodes[1], &b_broadcast_txn[0]);
465
466         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
467                         claimable_amount_satoshis: 1_000,
468                         confirmation_height: node_b_commitment_claimable,
469                 }, Balance::ClaimableAwaitingConfirmations {
470                         claimable_amount_satoshis: 3_000,
471                         confirmation_height: node_b_htlc_claimable,
472                 }, Balance::ContentiousClaimable {
473                         claimable_amount_satoshis: 4_000,
474                         timeout_height: htlc_cltv_timeout,
475                 }]),
476                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
477
478         // After reaching the commitment output CSV, we'll get a SpendableOutputs event for it and have
479         // only the HTLCs claimable on node B.
480         connect_blocks(&nodes[1], node_b_commitment_claimable - nodes[1].best_block_info().1);
481
482         let mut node_b_spendable = nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events();
483         assert_eq!(node_b_spendable.len(), 1);
484         if let Event::SpendableOutputs { outputs } = node_b_spendable.pop().unwrap() {
485                 assert_eq!(outputs.len(), 1);
486                 let spend_tx = nodes[1].keys_manager.backing.spend_spendable_outputs(&[&outputs[0]], Vec::new(),
487                         Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &Secp256k1::new()).unwrap();
488                 check_spends!(spend_tx, remote_txn[0]);
489         }
490
491         assert_eq!(sorted_vec(vec![Balance::ClaimableAwaitingConfirmations {
492                         claimable_amount_satoshis: 3_000,
493                         confirmation_height: node_b_htlc_claimable,
494                 }, Balance::ContentiousClaimable {
495                         claimable_amount_satoshis: 4_000,
496                         timeout_height: htlc_cltv_timeout,
497                 }]),
498                 sorted_vec(nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances()));
499
500         // After reaching the claimed HTLC output CSV, we'll get a SpendableOutptus event for it and
501         // have only one HTLC output left spendable.
502         connect_blocks(&nodes[1], node_b_htlc_claimable - nodes[1].best_block_info().1);
503
504         let mut node_b_spendable = nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events();
505         assert_eq!(node_b_spendable.len(), 1);
506         if let Event::SpendableOutputs { outputs } = node_b_spendable.pop().unwrap() {
507                 assert_eq!(outputs.len(), 1);
508                 let spend_tx = nodes[1].keys_manager.backing.spend_spendable_outputs(&[&outputs[0]], Vec::new(),
509                         Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &Secp256k1::new()).unwrap();
510                 check_spends!(spend_tx, b_broadcast_txn[0]);
511         } else { panic!(); }
512
513         assert_eq!(vec![Balance::ContentiousClaimable {
514                         claimable_amount_satoshis: 4_000,
515                         timeout_height: htlc_cltv_timeout,
516                 }],
517                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
518
519         // Finally, mine the HTLC timeout transaction that A broadcasted (even though B should be able
520         // to claim this HTLC with the preimage it knows!). It will remain listed as a claimable HTLC
521         // until ANTI_REORG_DELAY confirmations on the spend.
522         mine_transaction(&nodes[1], &a_broadcast_txn[2]);
523         assert_eq!(vec![Balance::ContentiousClaimable {
524                         claimable_amount_satoshis: 4_000,
525                         timeout_height: htlc_cltv_timeout,
526                 }],
527                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
528         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
529         assert_eq!(Vec::<Balance>::new(),
530                 nodes[1].chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances());
531 }
532
533 #[test]
534 fn test_claim_value_force_close() {
535         do_test_claim_value_force_close(true);
536         do_test_claim_value_force_close(false);
537 }