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