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