]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/shutdown_tests.rs
Support failing blinded non-intro HTLCs after RAA processing.
[rust-lightning] / lightning / src / ln / shutdown_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 //! Tests of our shutdown and closing_signed negotiation logic.
11
12 use crate::sign::{EntropySource, SignerProvider};
13 use crate::chain::ChannelMonitorUpdateStatus;
14 use crate::chain::transaction::OutPoint;
15 use crate::events::{MessageSendEvent, HTLCDestination, MessageSendEventsProvider, ClosureReason};
16 use crate::ln::channelmanager::{self, PaymentSendFailure, PaymentId, RecipientOnionFields, Retry, ChannelShutdownState, ChannelDetails};
17 use crate::routing::router::{PaymentParameters, get_route, RouteParameters};
18 use crate::ln::msgs;
19 use crate::ln::msgs::{ChannelMessageHandler, ErrorAction};
20 use crate::ln::onion_utils::INVALID_ONION_BLINDING;
21 use crate::ln::script::ShutdownScript;
22 use crate::util::test_utils;
23 use crate::util::test_utils::OnGetShutdownScriptpubkey;
24 use crate::util::errors::APIError;
25 use crate::util::config::UserConfig;
26 use crate::util::string::UntrustedString;
27
28 use bitcoin::blockdata::script::Builder;
29 use bitcoin::blockdata::opcodes;
30 use bitcoin::network::constants::Network;
31 use bitcoin::address::{WitnessProgram, WitnessVersion};
32
33 use regex;
34
35 use core::default::Default;
36 use std::convert::TryFrom;
37
38 use crate::ln::functional_test_utils::*;
39
40 #[test]
41 fn pre_funding_lock_shutdown_test() {
42         // Test sending a shutdown prior to channel_ready after funding generation
43         let chanmon_cfgs = create_chanmon_cfgs(2);
44         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
45         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
46         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
47         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
48         mine_transaction(&nodes[0], &tx);
49         mine_transaction(&nodes[1], &tx);
50
51         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id(), &nodes[1].node.get_our_node_id()).unwrap();
52         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
53         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
54         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
55         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
56
57         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
58         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
59         let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
60         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
61         let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
62         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
63         let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
64         assert!(node_1_none.is_none());
65
66         assert!(nodes[0].node.list_channels().is_empty());
67         assert!(nodes[1].node.list_channels().is_empty());
68         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 8000000);
69         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 8000000);
70 }
71
72 #[test]
73 fn expect_channel_shutdown_state() {
74         // Test sending a shutdown prior to channel_ready after funding generation
75         let chanmon_cfgs = create_chanmon_cfgs(2);
76         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
77         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
78         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
79         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
80
81         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::NotShuttingDown);
82
83         nodes[0].node.close_channel(&chan_1.2, &nodes[1].node.get_our_node_id()).unwrap();
84
85         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::ShutdownInitiated);
86         expect_channel_shutdown_state!(nodes[1], chan_1.2, ChannelShutdownState::NotShuttingDown);
87
88         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
89         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
90
91         // node1 goes into NegotiatingClosingFee since there are no HTLCs in flight, note that it
92         // doesnt mean that node1 has sent/recved its closing signed message
93         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::ShutdownInitiated);
94         expect_channel_shutdown_state!(nodes[1], chan_1.2, ChannelShutdownState::NegotiatingClosingFee);
95
96         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
97         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
98
99         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::NegotiatingClosingFee);
100         expect_channel_shutdown_state!(nodes[1], chan_1.2, ChannelShutdownState::NegotiatingClosingFee);
101
102         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
103         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
104         let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
105         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
106         let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
107         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
108         let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
109         assert!(node_1_none.is_none());
110
111         assert!(nodes[0].node.list_channels().is_empty());
112         assert!(nodes[1].node.list_channels().is_empty());
113         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
114         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
115 }
116
117 #[test]
118 fn expect_channel_shutdown_state_with_htlc() {
119         // Test sending a shutdown with outstanding updates pending.
120         let chanmon_cfgs = create_chanmon_cfgs(3);
121         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
122         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
123         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
124         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
125         let _chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
126
127         let (payment_preimage_0, payment_hash_0, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100_000);
128
129         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::NotShuttingDown);
130         expect_channel_shutdown_state!(nodes[1], chan_1.2, ChannelShutdownState::NotShuttingDown);
131
132         nodes[0].node.close_channel(&chan_1.2, &nodes[1].node.get_our_node_id()).unwrap();
133
134         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::ShutdownInitiated);
135         expect_channel_shutdown_state!(nodes[1], chan_1.2, ChannelShutdownState::NotShuttingDown);
136
137         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
138         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
139
140         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::ShutdownInitiated);
141         expect_channel_shutdown_state!(nodes[1], chan_1.2, ChannelShutdownState::ResolvingHTLCs);
142
143         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
144         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
145
146         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::ResolvingHTLCs);
147         expect_channel_shutdown_state!(nodes[1], chan_1.2, ChannelShutdownState::ResolvingHTLCs);
148
149         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
150         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
151
152         // Claim Funds on Node2
153         nodes[2].node.claim_funds(payment_preimage_0);
154         check_added_monitors!(nodes[2], 1);
155         expect_payment_claimed!(nodes[2], payment_hash_0, 100_000);
156
157         // Fulfil HTLCs on node1 and node0
158         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
159         assert!(updates.update_add_htlcs.is_empty());
160         assert!(updates.update_fail_htlcs.is_empty());
161         assert!(updates.update_fail_malformed_htlcs.is_empty());
162         assert!(updates.update_fee.is_none());
163         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
164         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
165         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(1000), false, false);
166         check_added_monitors!(nodes[1], 1);
167         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
168         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
169
170         // Still in "resolvingHTLCs" on chan1 after htlc removed on chan2
171         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::ResolvingHTLCs);
172         expect_channel_shutdown_state!(nodes[1], chan_1.2, ChannelShutdownState::ResolvingHTLCs);
173
174         assert!(updates_2.update_add_htlcs.is_empty());
175         assert!(updates_2.update_fail_htlcs.is_empty());
176         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
177         assert!(updates_2.update_fee.is_none());
178         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
179         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
180         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
181         expect_payment_sent!(nodes[0], payment_preimage_0);
182
183         // all htlcs removed, chan1 advances to NegotiatingClosingFee
184         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::NegotiatingClosingFee);
185         expect_channel_shutdown_state!(nodes[1], chan_1.2, ChannelShutdownState::NegotiatingClosingFee);
186
187         // ClosingSignNegotion process
188         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
189         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
190         let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
191         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
192         let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
193         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
194         let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
195         assert!(node_1_none.is_none());
196         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
197         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
198
199         // Shutdown basically removes the channelDetails, testing of shutdowncomplete state unnecessary
200         assert!(nodes[0].node.list_channels().is_empty());
201 }
202
203 #[test]
204 fn test_lnd_bug_6039() {
205         // LND sends a nonsense error message any time it gets a shutdown if there are still HTLCs
206         // pending. We currently swallow that error to work around LND's bug #6039. This test emulates
207         // the LND nonsense and ensures we at least kinda handle it.
208         let chanmon_cfgs = create_chanmon_cfgs(2);
209         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
210         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
211         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
212         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
213
214         let (payment_preimage, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
215
216         nodes[0].node.close_channel(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
217         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
218         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
219
220         // Generate an lnd-like error message and check that we respond by simply screaming louder to
221         // see if LND will accept our protocol compliance.
222         let err_msg = msgs::ErrorMessage { channel_id: chan.2, data: "link failed to shutdown".to_string() };
223         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &err_msg);
224         let node_a_responses = nodes[0].node.get_and_clear_pending_msg_events();
225         assert_eq!(node_a_responses[0], MessageSendEvent::SendShutdown {
226                         node_id: nodes[1].node.get_our_node_id(),
227                         msg: node_0_shutdown,
228                 });
229         if let MessageSendEvent::HandleError { action: msgs::ErrorAction::SendWarningMessage { .. }, .. }
230                 = node_a_responses[1] {} else { panic!(); }
231
232         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
233
234         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
235         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
236
237         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
238
239         // Assume that LND will eventually respond to our Shutdown if we clear all the remaining HTLCs
240         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
241
242         // ClosingSignNegotion process
243         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
244         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
245         let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
246         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
247         let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
248         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
249         let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
250         assert!(node_1_none.is_none());
251         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
252         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
253
254         // Shutdown basically removes the channelDetails, testing of shutdowncomplete state unnecessary
255         assert!(nodes[0].node.list_channels().is_empty());
256 }
257
258 #[test]
259 fn shutdown_on_unfunded_channel() {
260         // Test receiving a shutdown prior to funding generation
261         let chanmon_cfgs = create_chanmon_cfgs(2);
262         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
263         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
264         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
265
266         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 100_000, 0, None, None).unwrap();
267         let open_chan = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
268
269         // Create a dummy P2WPKH script
270         let script = Builder::new().push_int(0)
271                 .push_slice(&[0; 20])
272                 .into_script();
273
274         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &msgs::Shutdown {
275                 channel_id: open_chan.temporary_channel_id, scriptpubkey: script,
276         });
277         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyCoopClosedUnfundedChannel, [nodes[1].node.get_our_node_id()], 1_000_000);
278 }
279
280 #[test]
281 fn close_on_unfunded_channel() {
282         // Test the user asking us to close prior to funding generation
283         let chanmon_cfgs = create_chanmon_cfgs(2);
284         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
285         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
286         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
287
288         let chan_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 100_000, 0, None, None).unwrap();
289         let _open_chan = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
290
291         nodes[0].node.close_channel(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
292         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 1_000_000);
293 }
294
295 #[test]
296 fn expect_channel_shutdown_state_with_force_closure() {
297         // Test sending a shutdown prior to channel_ready after funding generation
298         let chanmon_cfgs = create_chanmon_cfgs(2);
299         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
300         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
301         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
302         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
303
304         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::NotShuttingDown);
305         expect_channel_shutdown_state!(nodes[1], chan_1.2, ChannelShutdownState::NotShuttingDown);
306
307         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
308         check_closed_broadcast!(nodes[1], true);
309         check_added_monitors!(nodes[1], 1);
310
311         expect_channel_shutdown_state!(nodes[0], chan_1.2, ChannelShutdownState::NotShuttingDown);
312         assert!(nodes[1].node.list_channels().is_empty());
313
314         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
315         assert_eq!(node_txn.len(), 1);
316         check_spends!(node_txn[0], chan_1.3);
317         mine_transaction(&nodes[0], &node_txn[0]);
318         check_added_monitors!(nodes[0], 1);
319
320         assert!(nodes[0].node.list_channels().is_empty());
321         assert!(nodes[1].node.list_channels().is_empty());
322         check_closed_broadcast!(nodes[0], true);
323         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
324         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
325 }
326
327 #[test]
328 fn updates_shutdown_wait() {
329         // Test sending a shutdown with outstanding updates pending
330         let chanmon_cfgs = create_chanmon_cfgs(3);
331         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
332         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
333         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
334         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
335         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
336         let logger = test_utils::TestLogger::new();
337         let scorer = test_utils::TestScorer::new();
338         let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
339         let random_seed_bytes = keys_manager.get_secure_random_bytes();
340
341         let (payment_preimage_0, payment_hash_0, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100_000);
342
343         nodes[0].node.close_channel(&chan_1.2, &nodes[1].node.get_our_node_id()).unwrap();
344         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
345         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
346         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
347         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
348
349         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
350         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
351
352         let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
353
354         let payment_params_1 = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
355                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
356         let route_params = RouteParameters::from_payment_params_and_value(payment_params_1, 100_000);
357         let route_1 = get_route(&nodes[0].node.get_our_node_id(), &route_params,
358                 &nodes[0].network_graph.read_only(), None, &logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
359         let payment_params_2 = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), TEST_FINAL_CLTV)
360                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
361         let route_params = RouteParameters::from_payment_params_and_value(payment_params_2, 100_000);
362         let route_2 = get_route(&nodes[1].node.get_our_node_id(), &route_params,
363                 &nodes[1].network_graph.read_only(), None, &logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
364         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route_1, payment_hash,
365                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
366                 ), true, APIError::ChannelUnavailable {..}, {});
367         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route_2, payment_hash,
368                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
369                 ), true, APIError::ChannelUnavailable {..}, {});
370
371         nodes[2].node.claim_funds(payment_preimage_0);
372         check_added_monitors!(nodes[2], 1);
373         expect_payment_claimed!(nodes[2], payment_hash_0, 100_000);
374
375         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
376         assert!(updates.update_add_htlcs.is_empty());
377         assert!(updates.update_fail_htlcs.is_empty());
378         assert!(updates.update_fail_malformed_htlcs.is_empty());
379         assert!(updates.update_fee.is_none());
380         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
381         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
382         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(1000), false, false);
383         check_added_monitors!(nodes[1], 1);
384         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
385         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
386
387         assert!(updates_2.update_add_htlcs.is_empty());
388         assert!(updates_2.update_fail_htlcs.is_empty());
389         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
390         assert!(updates_2.update_fee.is_none());
391         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
392         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
393         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
394         expect_payment_sent!(nodes[0], payment_preimage_0);
395
396         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
397         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
398         let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
399         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
400         let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
401         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
402         let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
403         assert!(node_1_none.is_none());
404         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
405         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
406
407         assert!(nodes[0].node.list_channels().is_empty());
408
409         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
410         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
411         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
412         assert!(nodes[1].node.list_channels().is_empty());
413         assert!(nodes[2].node.list_channels().is_empty());
414         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
415         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
416 }
417
418 #[test]
419 fn htlc_fail_async_shutdown() {
420         do_htlc_fail_async_shutdown(true);
421         do_htlc_fail_async_shutdown(false);
422 }
423
424 fn do_htlc_fail_async_shutdown(blinded_recipient: bool) {
425         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
426         let chanmon_cfgs = create_chanmon_cfgs(3);
427         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
428         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
429         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
430         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
431         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
432
433         let amt_msat = 100000;
434         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), None);
435         let route_params = if blinded_recipient {
436                 crate::ln::blinded_payment_tests::get_blinded_route_parameters(
437                         amt_msat, our_payment_secret,
438                         nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_2.0.contents],
439                         &chanmon_cfgs[2].keys_manager)
440         } else {
441                 RouteParameters::from_payment_params_and_value(
442                         PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV), amt_msat)
443         };
444         nodes[0].node.send_payment(our_payment_hash,
445                 RecipientOnionFields::secret_only(our_payment_secret),
446                 PaymentId(our_payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
447         check_added_monitors!(nodes[0], 1);
448         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
449         assert_eq!(updates.update_add_htlcs.len(), 1);
450         assert!(updates.update_fulfill_htlcs.is_empty());
451         assert!(updates.update_fail_htlcs.is_empty());
452         assert!(updates.update_fail_malformed_htlcs.is_empty());
453         assert!(updates.update_fee.is_none());
454
455         nodes[1].node.close_channel(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
456         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
457         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
458         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
459
460         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
461         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
462         check_added_monitors!(nodes[1], 1);
463         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
464         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false, false);
465
466         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
467         assert!(updates_2.update_add_htlcs.is_empty());
468         assert!(updates_2.update_fulfill_htlcs.is_empty());
469         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
470         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
471         assert!(updates_2.update_fee.is_none());
472
473         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
474         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
475
476         if blinded_recipient {
477                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, false,
478                         PaymentFailedConditions::new().expected_htlc_error_data(INVALID_ONION_BLINDING, &[0; 32]));
479         } else {
480                 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_2.0.contents.short_channel_id, true);
481         }
482
483         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
484         assert_eq!(msg_events.len(), 1);
485         let node_0_closing_signed = match msg_events[0] {
486                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
487                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
488                         (*msg).clone()
489                 },
490                 _ => panic!("Unexpected event"),
491         };
492
493         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
494         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
495         let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
496         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
497         let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
498         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
499         let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
500         assert!(node_1_none.is_none());
501
502         assert!(nodes[0].node.list_channels().is_empty());
503
504         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
505         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
506         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
507         assert!(nodes[1].node.list_channels().is_empty());
508         assert!(nodes[2].node.list_channels().is_empty());
509         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
510         check_closed_event!(nodes[1], 2, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id(), nodes[2].node.get_our_node_id()], 100000);
511         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
512 }
513
514 fn do_test_shutdown_rebroadcast(recv_count: u8) {
515         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
516         // messages delivered prior to disconnect
517         let chanmon_cfgs = create_chanmon_cfgs(3);
518         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
519         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
520         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
521         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
522         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
523
524         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100_000);
525
526         nodes[1].node.close_channel(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
527         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
528         if recv_count > 0 {
529                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
530                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
531                 if recv_count > 1 {
532                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
533                 }
534         }
535
536         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
537         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
538
539         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
540                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
541         }, true).unwrap();
542         let node_0_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
543         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
544                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
545         }, false).unwrap();
546         let node_1_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
547
548         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
549         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
550         assert!(node_1_shutdown == node_1_2nd_shutdown);
551
552         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
553         let node_0_2nd_shutdown = if recv_count > 0 {
554                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
555                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
556                 node_0_2nd_shutdown
557         } else {
558                 let node_0_chan_update = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
559                 assert_eq!(node_0_chan_update.contents.flags & 2, 0); // "disabled" flag must not be set as we just reconnected.
560                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
561                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
562         };
563         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
564
565         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
566         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
567
568         nodes[2].node.claim_funds(payment_preimage);
569         check_added_monitors!(nodes[2], 1);
570         expect_payment_claimed!(nodes[2], payment_hash, 100_000);
571
572         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
573         assert!(updates.update_add_htlcs.is_empty());
574         assert!(updates.update_fail_htlcs.is_empty());
575         assert!(updates.update_fail_malformed_htlcs.is_empty());
576         assert!(updates.update_fee.is_none());
577         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
578         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
579         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(1000), false, false);
580         check_added_monitors!(nodes[1], 1);
581         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
582         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
583
584         assert!(updates_2.update_add_htlcs.is_empty());
585         assert!(updates_2.update_fail_htlcs.is_empty());
586         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
587         assert!(updates_2.update_fee.is_none());
588         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
589         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
590         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
591         expect_payment_sent!(nodes[0], payment_preimage);
592
593         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
594         if recv_count > 0 {
595                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
596                 let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
597                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
598                 let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
599                 assert!(node_0_2nd_closing_signed.is_some());
600         }
601
602         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
603         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
604
605         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
606                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
607         }, true).unwrap();
608         let node_1_2nd_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
609         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
610                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
611         }, false).unwrap();
612         if recv_count == 0 {
613                 // If all closing_signeds weren't delivered we can just resume where we left off...
614                 let node_0_2nd_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
615
616                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
617                 let node_0_msgs = nodes[0].node.get_and_clear_pending_msg_events();
618                 assert_eq!(node_0_msgs.len(), 2);
619                 let node_0_2nd_closing_signed = match node_0_msgs[1] {
620                         MessageSendEvent::SendClosingSigned { ref msg, .. } => {
621                                 assert_eq!(node_0_closing_signed, *msg);
622                                 msg.clone()
623                         },
624                         _ => panic!(),
625                 };
626
627                 let node_0_3rd_shutdown = match node_0_msgs[0] {
628                         MessageSendEvent::SendShutdown { ref msg, .. } => {
629                                 assert_eq!(node_0_2nd_shutdown, *msg);
630                                 msg.clone()
631                         },
632                         _ => panic!(),
633                 };
634                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
635
636                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
637                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
638                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
639
640                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
641                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
642
643                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
644
645                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
646                 let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
647                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
648                 let (_, node_0_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
649                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.unwrap());
650                 let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
651                 assert!(node_1_none.is_none());
652                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
653         } else {
654                 // If one node, however, received + responded with an identical closing_signed we end
655                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
656                 // There isn't really anything better we can do simply, but in the future we might
657                 // explore storing a set of recently-closed channels that got disconnected during
658                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
659                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
660                 // transaction.
661                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
662
663                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
664                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
665                 assert_eq!(msg_events.len(), 2);
666                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[1] {
667                         match action {
668                                 &ErrorAction::SendErrorMessage { ref msg } => {
669                                         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &msg);
670                                         assert_eq!(msg.channel_id, chan_1.2);
671                                 },
672                                 _ => panic!("Unexpected event!"),
673                         }
674                 } else { panic!("Needed SendErrorMessage close"); }
675
676                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
677                 // checks it, but in this case nodes[1] didn't ever get a chance to receive a
678                 // closing_signed so we do it ourselves
679                 check_closed_broadcast!(nodes[1], false);
680                 check_added_monitors!(nodes[1], 1);
681                 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", &nodes[1].node.get_our_node_id())) }
682                         , [nodes[0].node.get_our_node_id()], 100000);
683         }
684
685         assert!(nodes[0].node.list_channels().is_empty());
686
687         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
688         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
689         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
690         assert!(nodes[1].node.list_channels().is_empty());
691         assert!(nodes[2].node.list_channels().is_empty());
692         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
693         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
694         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
695 }
696
697 #[test]
698 fn test_shutdown_rebroadcast() {
699         do_test_shutdown_rebroadcast(0);
700         do_test_shutdown_rebroadcast(1);
701         do_test_shutdown_rebroadcast(2);
702 }
703
704 #[test]
705 fn test_upfront_shutdown_script() {
706         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
707         // enforce it at shutdown message
708
709         let mut config = UserConfig::default();
710         config.channel_handshake_config.announced_channel = true;
711         config.channel_handshake_limits.force_announced_channel_preference = false;
712         config.channel_handshake_config.commit_upfront_shutdown_pubkey = false;
713         let user_cfgs = [None, Some(config), None];
714         let chanmon_cfgs = create_chanmon_cfgs(3);
715         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
716         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
717         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
718
719         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
720         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000);
721         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[2].node.get_our_node_id()).unwrap();
722         let node_0_orig_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
723         let mut node_0_shutdown = node_0_orig_shutdown.clone();
724         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
725         // Test we enforce upfront_scriptpbukey if by providing a different one at closing that we warn
726         // the peer and ignore the message.
727         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
728         assert!(regex::Regex::new(r"Got shutdown request with a scriptpubkey \([A-Fa-f0-9]+\) which did not match their previous scriptpubkey.")
729                         .unwrap().is_match(&check_warn_msg!(nodes[2], nodes[0].node.get_our_node_id(), chan.2)));
730         // This allows nodes[2] to retry the shutdown message, which should get a response:
731         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_orig_shutdown);
732         get_event_msg!(nodes[2], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
733
734         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
735         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000);
736         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[2].node.get_our_node_id()).unwrap();
737         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
738         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
739         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
740         let events = nodes[2].node.get_and_clear_pending_msg_events();
741         assert_eq!(events.len(), 1);
742         match events[0] {
743                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
744                 _ => panic!("Unexpected event"),
745         }
746
747         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
748         *nodes[0].override_init_features.borrow_mut() = Some(nodes[0].node.init_features().clear_upfront_shutdown_script());
749         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
750         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[1].node.get_our_node_id()).unwrap();
751         let node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
752         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
753         check_added_monitors!(nodes[1], 1);
754         let events = nodes[1].node.get_and_clear_pending_msg_events();
755         assert_eq!(events.len(), 1);
756         match events[0] {
757                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
758                 _ => panic!("Unexpected event"),
759         }
760
761         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
762         // channel smoothly, opt-out is from channel initiator here
763         *nodes[0].override_init_features.borrow_mut() = None;
764         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000);
765         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[0].node.get_our_node_id()).unwrap();
766         check_added_monitors!(nodes[1], 1);
767         let node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
768         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
769         let events = nodes[0].node.get_and_clear_pending_msg_events();
770         assert_eq!(events.len(), 1);
771         match events[0] {
772                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
773                 _ => panic!("Unexpected event"),
774         }
775
776         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
777         //// channel smoothly
778         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
779         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[0].node.get_our_node_id()).unwrap();
780         check_added_monitors!(nodes[1], 1);
781         let node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
782         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
783         let events = nodes[0].node.get_and_clear_pending_msg_events();
784         assert_eq!(events.len(), 2);
785         match events[0] {
786                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
787                 _ => panic!("Unexpected event"),
788         }
789         match events[1] {
790                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
791                 _ => panic!("Unexpected event"),
792         }
793 }
794
795 #[test]
796 fn test_unsupported_anysegwit_upfront_shutdown_script() {
797         let chanmon_cfgs = create_chanmon_cfgs(2);
798         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
799         // Clear shutdown_anysegwit on initiator
800         *node_cfgs[0].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_shutdown_anysegwit());
801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
802         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
803
804         // Use a non-v0 segwit script supported by option_shutdown_anysegwit
805         let anysegwit_shutdown_script = Builder::new()
806                 .push_int(16)
807                 .push_slice(&[0, 40])
808                 .into_script();
809
810         // Check script when handling an open_channel message
811         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
812         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
813         open_channel.shutdown_scriptpubkey = Some(anysegwit_shutdown_script.clone());
814         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
815
816         let events = nodes[1].node.get_and_clear_pending_msg_events();
817         assert_eq!(events.len(), 1);
818         match events[0] {
819                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
820                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
821                         assert_eq!(msg.data, "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: OP_PUSHNUM_16 OP_PUSHBYTES_2 0028");
822                 },
823                 _ => panic!("Unexpected event"),
824         }
825
826         let chanmon_cfgs = create_chanmon_cfgs(2);
827         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
828         // Clear shutdown_anysegwit on responder
829         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_shutdown_anysegwit());
830         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
831         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
832
833         // Check script when handling an accept_channel message
834         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
835         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
836         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
837         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
838         accept_channel.shutdown_scriptpubkey = Some(anysegwit_shutdown_script.clone());
839         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
840
841         let events = nodes[0].node.get_and_clear_pending_msg_events();
842         assert_eq!(events.len(), 1);
843         match events[0] {
844                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
845                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
846                         assert_eq!(msg.data, "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: OP_PUSHNUM_16 OP_PUSHBYTES_2 0028");
847                 },
848                 _ => panic!("Unexpected event"),
849         }
850         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: OP_PUSHNUM_16 OP_PUSHBYTES_2 0028".to_string() }
851                 , [nodes[1].node.get_our_node_id()], 100000);
852 }
853
854 #[test]
855 fn test_invalid_upfront_shutdown_script() {
856         let chanmon_cfgs = create_chanmon_cfgs(2);
857         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
858         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
859         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
860
861         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
862
863         // Use a segwit v0 script with an unsupported witness program
864         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
865         open_channel.shutdown_scriptpubkey = Some(Builder::new().push_int(0)
866                 .push_slice(&[0, 0])
867                 .into_script());
868         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
869
870         let events = nodes[1].node.get_and_clear_pending_msg_events();
871         assert_eq!(events.len(), 1);
872         match events[0] {
873                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
874                         assert_eq!(node_id, nodes[0].node.get_our_node_id());
875                         assert_eq!(msg.data, "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: OP_0 OP_PUSHBYTES_2 0000");
876                 },
877                 _ => panic!("Unexpected event"),
878         }
879 }
880
881 #[test]
882 fn test_segwit_v0_shutdown_script() {
883         let mut config = UserConfig::default();
884         config.channel_handshake_config.announced_channel = true;
885         config.channel_handshake_limits.force_announced_channel_preference = false;
886         config.channel_handshake_config.commit_upfront_shutdown_pubkey = false;
887         let user_cfgs = [None, Some(config), None];
888         let chanmon_cfgs = create_chanmon_cfgs(3);
889         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
890         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
891         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
892
893         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
894         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[0].node.get_our_node_id()).unwrap();
895         check_added_monitors!(nodes[1], 1);
896
897         // Use a segwit v0 script supported even without option_shutdown_anysegwit
898         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
899         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
900                 .push_slice(&[0; 20])
901                 .into_script();
902         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
903
904         let events = nodes[0].node.get_and_clear_pending_msg_events();
905         assert_eq!(events.len(), 2);
906         match events[0] {
907                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
908                 _ => panic!("Unexpected event"),
909         }
910         match events[1] {
911                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
912                 _ => panic!("Unexpected event"),
913         }
914 }
915
916 #[test]
917 fn test_anysegwit_shutdown_script() {
918         let mut config = UserConfig::default();
919         config.channel_handshake_config.announced_channel = true;
920         config.channel_handshake_limits.force_announced_channel_preference = false;
921         config.channel_handshake_config.commit_upfront_shutdown_pubkey = false;
922         let user_cfgs = [None, Some(config), None];
923         let chanmon_cfgs = create_chanmon_cfgs(3);
924         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
925         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
926         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
927
928         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
929         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[0].node.get_our_node_id()).unwrap();
930         check_added_monitors!(nodes[1], 1);
931
932         // Use a non-v0 segwit script supported by option_shutdown_anysegwit
933         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
934         node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
935                 .push_slice(&[0, 0])
936                 .into_script();
937         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
938
939         let events = nodes[0].node.get_and_clear_pending_msg_events();
940         assert_eq!(events.len(), 2);
941         match events[0] {
942                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
943                 _ => panic!("Unexpected event"),
944         }
945         match events[1] {
946                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
947                 _ => panic!("Unexpected event"),
948         }
949 }
950
951 #[test]
952 fn test_unsupported_anysegwit_shutdown_script() {
953         let mut config = UserConfig::default();
954         config.channel_handshake_config.announced_channel = true;
955         config.channel_handshake_limits.force_announced_channel_preference = false;
956         config.channel_handshake_config.commit_upfront_shutdown_pubkey = false;
957         let user_cfgs = [None, Some(config), None];
958         let chanmon_cfgs = create_chanmon_cfgs(3);
959         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
960         *node_cfgs[0].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&config).clear_shutdown_anysegwit());
961         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&config).clear_shutdown_anysegwit());
962         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
963         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
964
965         // Check that using an unsupported shutdown script fails and a supported one succeeds.
966         let supported_shutdown_script = chanmon_cfgs[1].keys_manager.get_shutdown_scriptpubkey().unwrap();
967         let unsupported_witness_program = WitnessProgram::new(WitnessVersion::V16, &[0, 40]).unwrap();
968         let unsupported_shutdown_script =
969                 ShutdownScript::new_witness_program(&unsupported_witness_program).unwrap();
970         chanmon_cfgs[1].keys_manager
971                 .expect(OnGetShutdownScriptpubkey { returns: unsupported_shutdown_script.clone() })
972                 .expect(OnGetShutdownScriptpubkey { returns: supported_shutdown_script });
973
974         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
975         match nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[0].node.get_our_node_id()) {
976                 Err(APIError::IncompatibleShutdownScript { script }) => {
977                         assert_eq!(script.into_inner(), unsupported_shutdown_script.clone().into_inner());
978                 },
979                 Err(e) => panic!("Unexpected error: {:?}", e),
980                 Ok(_) => panic!("Expected error"),
981         }
982         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[0].node.get_our_node_id()).unwrap();
983         check_added_monitors!(nodes[1], 1);
984
985         // Use a non-v0 segwit script unsupported without option_shutdown_anysegwit
986         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
987         node_0_shutdown.scriptpubkey = unsupported_shutdown_script.into_inner();
988         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
989
990         assert_eq!(&check_warn_msg!(nodes[0], nodes[1].node.get_our_node_id(), chan.2),
991                         "Got a nonstandard scriptpubkey (60020028) from remote peer");
992 }
993
994 #[test]
995 fn test_invalid_shutdown_script() {
996         let mut config = UserConfig::default();
997         config.channel_handshake_config.announced_channel = true;
998         config.channel_handshake_limits.force_announced_channel_preference = false;
999         config.channel_handshake_config.commit_upfront_shutdown_pubkey = false;
1000         let user_cfgs = [None, Some(config), None];
1001         let chanmon_cfgs = create_chanmon_cfgs(3);
1002         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1003         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
1004         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1005
1006         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1007         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[0].node.get_our_node_id()).unwrap();
1008         check_added_monitors!(nodes[1], 1);
1009
1010         // Use a segwit v0 script with an unsupported witness program
1011         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1012         node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
1013                 .push_slice(&[0, 0])
1014                 .into_script();
1015         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
1016
1017         assert_eq!(&check_warn_msg!(nodes[0], nodes[1].node.get_our_node_id(), chan.2),
1018                         "Got a nonstandard scriptpubkey (00020000) from remote peer");
1019 }
1020
1021 #[test]
1022 fn test_user_shutdown_script() {
1023         let mut config = test_default_channel_config();
1024         config.channel_handshake_config.announced_channel = true;
1025         config.channel_handshake_limits.force_announced_channel_preference = false;
1026         config.channel_handshake_config.commit_upfront_shutdown_pubkey = false;
1027         let user_cfgs = [None, Some(config), None];
1028         let chanmon_cfgs = create_chanmon_cfgs(3);
1029         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1030         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
1031         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1032
1033         // Segwit v0 script of the form OP_0 <20-byte hash>
1034         let script = Builder::new().push_int(0)
1035                 .push_slice(&[0; 20])
1036                 .into_script();
1037
1038         let shutdown_script = ShutdownScript::try_from(script.clone()).unwrap();
1039
1040         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1041         nodes[1].node.close_channel_with_feerate_and_script(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[0].node.get_our_node_id(), None, Some(shutdown_script)).unwrap();
1042         check_added_monitors!(nodes[1], 1);
1043
1044         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1045
1046         assert_eq!(node_0_shutdown.scriptpubkey, script);
1047 }
1048
1049 #[test]
1050 fn test_already_set_user_shutdown_script() {
1051         let mut config = test_default_channel_config();
1052         config.channel_handshake_config.announced_channel = true;
1053         config.channel_handshake_limits.force_announced_channel_preference = false;
1054         let user_cfgs = [None, Some(config), None];
1055         let chanmon_cfgs = create_chanmon_cfgs(3);
1056         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1057         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
1058         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1059
1060         // Segwit v0 script of the form OP_0 <20-byte hash>
1061         let script = Builder::new().push_int(0)
1062                 .push_slice(&[0; 20])
1063                 .into_script();
1064
1065         let shutdown_script = ShutdownScript::try_from(script).unwrap();
1066
1067         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1068         let result = nodes[1].node.close_channel_with_feerate_and_script(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[0].node.get_our_node_id(), None, Some(shutdown_script));
1069
1070         assert_eq!(result, Err(APIError::APIMisuseError { err: "Cannot override shutdown script for a channel with one already set".to_string() }));
1071 }
1072
1073 #[derive(PartialEq)]
1074 enum TimeoutStep {
1075         AfterShutdown,
1076         AfterClosingSigned,
1077         NoTimeout,
1078 }
1079
1080 fn do_test_closing_signed_reinit_timeout(timeout_step: TimeoutStep) {
1081         // The range-based closing signed negotiation allows the funder to restart the process with a
1082         // new range if the previous range did not overlap. This allows implementations to request user
1083         // intervention allowing users to enter a new fee range. We do not implement the sending side
1084         // of this, instead opting to allow users to enter an explicit "willing to pay up to X to avoid
1085         // force-closing" value and relying on that instead.
1086         //
1087         // Here we run test the fundee side of that restart mechanism, implementing the funder side of
1088         // it manually.
1089         let chanmon_cfgs = create_chanmon_cfgs(2);
1090         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1091         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1092         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1093         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1094
1095         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
1096
1097         nodes[0].node.close_channel(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
1098         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1099         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1100         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1101         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1102
1103         {
1104                 // Now we set nodes[1] to require a relatively high feerate for closing. This should result
1105                 // in it rejecting nodes[0]'s initial closing_signed, giving nodes[0] a chance to try
1106                 // again.
1107                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
1108                 *feerate_lock *= 10;
1109         }
1110
1111         let mut node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1112         // nodes[0] should use a "reasonable" feerate, well under the 10 sat/vByte that nodes[1] thinks
1113         // is the current prevailing feerate.
1114         assert!(node_0_closing_signed.fee_satoshis <= 500);
1115
1116         if timeout_step != TimeoutStep::AfterShutdown {
1117                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1118                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan_id)
1119                         .starts_with("Unable to come to consensus about closing feerate"));
1120
1121                 // Now deliver a mutated closing_signed indicating a higher acceptable fee range, which
1122                 // nodes[1] should happily accept and respond to.
1123                 node_0_closing_signed.fee_range.as_mut().unwrap().max_fee_satoshis *= 10;
1124                 {
1125                         let mut node_0_per_peer_lock;
1126                         let mut node_0_peer_state_lock;
1127                         get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_id).context_mut().closing_fee_limits.as_mut().unwrap().1 *= 10;
1128                 }
1129                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1130                 let node_1_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
1131                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
1132                 let node_0_2nd_closing_signed = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1133                 if timeout_step == TimeoutStep::NoTimeout {
1134                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed.1.unwrap());
1135                         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1136                 }
1137                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1138         }
1139
1140         if timeout_step != TimeoutStep::NoTimeout {
1141                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
1142         } else {
1143                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1144         }
1145
1146         nodes[1].node.timer_tick_occurred();
1147         nodes[1].node.timer_tick_occurred();
1148
1149         let txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1150         assert_eq!(txn.len(), 1);
1151         assert_eq!(txn[0].output.len(), 2);
1152
1153         if timeout_step != TimeoutStep::NoTimeout {
1154                 assert!((txn[0].output[0].script_pubkey.is_v0_p2wpkh() &&
1155                          txn[0].output[1].script_pubkey.is_v0_p2wsh()) ||
1156                         (txn[0].output[1].script_pubkey.is_v0_p2wpkh() &&
1157                          txn[0].output[0].script_pubkey.is_v0_p2wsh()));
1158                 check_closed_broadcast!(nodes[1], true);
1159                 check_added_monitors!(nodes[1], 1);
1160                 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "closing_signed negotiation failed to finish within two timer ticks".to_string() }
1161                         , [nodes[0].node.get_our_node_id()], 100000);
1162         } else {
1163                 assert!(txn[0].output[0].script_pubkey.is_v0_p2wpkh());
1164                 assert!(txn[0].output[1].script_pubkey.is_v0_p2wpkh());
1165
1166                 let events = nodes[1].node.get_and_clear_pending_msg_events();
1167                 assert_eq!(events.len(), 1);
1168                 match events[0] {
1169                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1170                                 assert_eq!(msg.contents.flags & 2, 2);
1171                         },
1172                         _ => panic!("Unexpected event"),
1173                 }
1174         }
1175 }
1176
1177 #[test]
1178 fn test_closing_signed_reinit_timeout() {
1179         do_test_closing_signed_reinit_timeout(TimeoutStep::AfterShutdown);
1180         do_test_closing_signed_reinit_timeout(TimeoutStep::AfterClosingSigned);
1181         do_test_closing_signed_reinit_timeout(TimeoutStep::NoTimeout);
1182 }
1183
1184 fn do_simple_legacy_shutdown_test(high_initiator_fee: bool) {
1185         // A simpe test of the legacy shutdown fee negotiation logic.
1186         let chanmon_cfgs = create_chanmon_cfgs(2);
1187         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1188         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1189         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1190
1191         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1192
1193         if high_initiator_fee {
1194                 // If high_initiator_fee is set, set nodes[0]'s feerate significantly higher. This
1195                 // shouldn't impact the flow at all given nodes[1] will happily accept the higher fee.
1196                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1197                 *feerate_lock *= 10;
1198         }
1199
1200         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id(), &nodes[1].node.get_our_node_id()).unwrap();
1201         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1202         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1203         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1204         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1205
1206         let mut node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1207         node_0_closing_signed.fee_range = None;
1208         if high_initiator_fee {
1209                 assert!(node_0_closing_signed.fee_satoshis > 500);
1210         } else {
1211                 assert!(node_0_closing_signed.fee_satoshis < 500);
1212         }
1213
1214         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1215         let (_, mut node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1216         node_1_closing_signed.as_mut().unwrap().fee_range = None;
1217
1218         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1219         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1220         assert!(node_0_none.is_none());
1221         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1222         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1223 }
1224
1225 #[test]
1226 fn simple_legacy_shutdown_test() {
1227         do_simple_legacy_shutdown_test(false);
1228         do_simple_legacy_shutdown_test(true);
1229 }
1230
1231 #[test]
1232 fn simple_target_feerate_shutdown() {
1233         // Simple test of target in `close_channel_with_target_feerate`.
1234         let chanmon_cfgs = create_chanmon_cfgs(2);
1235         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1236         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1237         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1238
1239         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1240         let chan_id = OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id();
1241
1242         nodes[0].node.close_channel_with_feerate_and_script(&chan_id, &nodes[1].node.get_our_node_id(), Some(253 * 10), None).unwrap();
1243         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1244         nodes[1].node.close_channel_with_feerate_and_script(&chan_id, &nodes[0].node.get_our_node_id(), Some(253 * 5), None).unwrap();
1245         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1246
1247         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1248         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1249
1250         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1251         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1252         let (_, node_1_closing_signed_opt) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1253         let node_1_closing_signed = node_1_closing_signed_opt.unwrap();
1254
1255         // nodes[1] was passed a target which was larger than the current channel feerate, which it
1256         // should ignore in favor of the channel fee, as there is no use demanding a minimum higher
1257         // than what will be paid on a force-close transaction. Note that we have to consider rounding,
1258         // so only check that we're within 10 sats.
1259         assert!(node_0_closing_signed.fee_range.as_ref().unwrap().min_fee_satoshis >=
1260                 node_1_closing_signed.fee_range.as_ref().unwrap().min_fee_satoshis * 10 - 5);
1261         assert!(node_0_closing_signed.fee_range.as_ref().unwrap().min_fee_satoshis <=
1262                 node_1_closing_signed.fee_range.as_ref().unwrap().min_fee_satoshis * 10 + 5);
1263
1264         // Further, because nodes[0]'s target fee is larger than the `Normal` fee estimation plus our
1265         // force-closure-avoidance buffer, min should equal max, and the nodes[1]-selected fee should
1266         // be the nodes[0] only available fee.
1267         assert_eq!(node_0_closing_signed.fee_range.as_ref().unwrap().min_fee_satoshis,
1268                    node_0_closing_signed.fee_range.as_ref().unwrap().max_fee_satoshis);
1269         assert_eq!(node_0_closing_signed.fee_range.as_ref().unwrap().min_fee_satoshis,
1270                    node_0_closing_signed.fee_satoshis);
1271         assert_eq!(node_0_closing_signed.fee_satoshis, node_1_closing_signed.fee_satoshis);
1272
1273         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed);
1274         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1275         assert!(node_0_none.is_none());
1276         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1277         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1278 }
1279
1280 fn do_outbound_update_no_early_closing_signed(use_htlc: bool) {
1281         // Previously, if we have a pending inbound HTLC (or fee update) on a channel which has
1282         // initiated shutdown, we'd send our initial closing_signed immediately after receiving the
1283         // peer's last RAA to remove the HTLC/fee update, but before receiving their final
1284         // commitment_signed for a commitment without the HTLC/with the new fee. This caused at least
1285         // LDK peers to force-close as we initiated closing_signed prior to the channel actually being
1286         // fully empty of pending updates/HTLCs.
1287         let chanmon_cfgs = create_chanmon_cfgs(2);
1288         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1289         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1290         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1291
1292         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1293
1294         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
1295         let payment_hash_opt = if use_htlc {
1296                 Some(route_payment(&nodes[1], &[&nodes[0]], 10_000).1)
1297         } else {
1298                 None
1299         };
1300
1301         if use_htlc {
1302                 nodes[0].node.fail_htlc_backwards(&payment_hash_opt.unwrap());
1303                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[0],
1304                         [HTLCDestination::FailedPayment { payment_hash: payment_hash_opt.unwrap() }]);
1305         } else {
1306                 *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap() *= 10;
1307                 nodes[0].node.timer_tick_occurred();
1308         }
1309         let updates = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
1310         check_added_monitors(&nodes[0], 1);
1311
1312         nodes[1].node.close_channel(&chan_id, &nodes[0].node.get_our_node_id()).unwrap();
1313         let node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1314         nodes[0].node.close_channel(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
1315         let node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1316
1317         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
1318         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
1319
1320         if use_htlc {
1321                 nodes[1].node.handle_update_fail_htlc(&nodes[0].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1322         } else {
1323                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &updates.update_fee.unwrap());
1324         }
1325         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
1326         check_added_monitors(&nodes[1], 1);
1327         let (bs_raa, bs_cs) = get_revoke_commit_msgs(&nodes[1], &nodes[0].node.get_our_node_id());
1328
1329         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1330         check_added_monitors(&nodes[0], 1);
1331
1332         // At this point the Channel on nodes[0] has no record of any HTLCs but the latest
1333         // broadcastable commitment does contain the HTLC (but only the ChannelMonitor knows this).
1334         // Thus, the channel should not yet initiate closing_signed negotiation (but previously did).
1335         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events(), Vec::new());
1336
1337         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
1338         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs);
1339         check_added_monitors(&nodes[0], 1);
1340         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events(), Vec::new());
1341
1342         expect_channel_shutdown_state!(nodes[0], chan_id, ChannelShutdownState::ResolvingHTLCs);
1343         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events(), Vec::new());
1344         let (outpoint, latest_update, _) = nodes[0].chain_monitor.latest_monitor_update_id.lock().unwrap().get(&chan_id).unwrap().clone();
1345         nodes[0].chain_monitor.chain_monitor.force_channel_monitor_updated(outpoint, latest_update);
1346
1347         let as_raa_closing_signed = nodes[0].node.get_and_clear_pending_msg_events();
1348         assert_eq!(as_raa_closing_signed.len(), 2);
1349
1350         if let MessageSendEvent::SendRevokeAndACK { msg, .. } = &as_raa_closing_signed[0] {
1351                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &msg);
1352                 check_added_monitors(&nodes[1], 1);
1353                 if use_htlc {
1354                         expect_payment_failed!(nodes[1], payment_hash_opt.unwrap(), true);
1355                 }
1356         } else { panic!("Unexpected message {:?}", as_raa_closing_signed[0]); }
1357
1358         if let MessageSendEvent::SendClosingSigned { msg, .. } = &as_raa_closing_signed[1] {
1359                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &msg);
1360         } else { panic!("Unexpected message {:?}", as_raa_closing_signed[1]); }
1361
1362         let bs_closing_signed = get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id());
1363         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &bs_closing_signed);
1364         let (_, as_2nd_closing_signed) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1365         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &as_2nd_closing_signed.unwrap());
1366         let (_, node_1_none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1367         assert!(node_1_none.is_none());
1368
1369         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1370         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1371 }
1372
1373 #[test]
1374 fn outbound_update_no_early_closing_signed() {
1375         do_outbound_update_no_early_closing_signed(true);
1376         do_outbound_update_no_early_closing_signed(false);
1377 }