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