Merge pull request #1935 from TheBlueMatt/2022-12-no-non-time-panic
[rust-lightning] / lightning / src / ln / reload_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 //! Functional tests which test for correct behavior across node restarts.
11
12 use crate::chain::{ChannelMonitorUpdateStatus, Watch};
13 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
14 use crate::chain::channelmonitor::ChannelMonitor;
15 use crate::chain::keysinterface::{EntropySource, KeysInterface};
16 use crate::chain::transaction::OutPoint;
17 use crate::ln::channelmanager::{self, ChannelManager, ChannelManagerReadArgs, PaymentId};
18 use crate::ln::msgs;
19 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
20 use crate::util::enforcing_trait_impls::EnforcingSigner;
21 use crate::util::test_utils;
22 use crate::util::errors::APIError;
23 use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
24 use crate::util::ser::{Writeable, ReadableArgs};
25 use crate::util::config::UserConfig;
26
27 use bitcoin::hash_types::BlockHash;
28
29 use crate::prelude::*;
30 use core::default::Default;
31 use crate::sync::Mutex;
32
33 use crate::ln::functional_test_utils::*;
34
35 #[test]
36 fn test_funding_peer_disconnect() {
37         // Test that we can lock in our funding tx while disconnected
38         let chanmon_cfgs = create_chanmon_cfgs(2);
39         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
40         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
41         let persister: test_utils::TestPersister;
42         let new_chain_monitor: test_utils::TestChainMonitor;
43         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
44         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
45         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
46
47         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
48         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
49
50         confirm_transaction(&nodes[0], &tx);
51         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
52         assert!(events_1.is_empty());
53
54         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
55
56         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
57         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
58
59         confirm_transaction(&nodes[1], &tx);
60         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
61         assert!(events_2.is_empty());
62
63         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
64         let as_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
65         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
66         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
67
68         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
69         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
70         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
71         assert_eq!(events_3.len(), 1);
72         let as_channel_ready = match events_3[0] {
73                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
74                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
75                         msg.clone()
76                 },
77                 _ => panic!("Unexpected event {:?}", events_3[0]),
78         };
79
80         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
81         // announcement_signatures as well as channel_update.
82         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
83         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
84         assert_eq!(events_4.len(), 3);
85         let chan_id;
86         let bs_channel_ready = match events_4[0] {
87                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
88                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
89                         chan_id = msg.channel_id;
90                         msg.clone()
91                 },
92                 _ => panic!("Unexpected event {:?}", events_4[0]),
93         };
94         let bs_announcement_sigs = match events_4[1] {
95                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
96                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
97                         msg.clone()
98                 },
99                 _ => panic!("Unexpected event {:?}", events_4[1]),
100         };
101         match events_4[2] {
102                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
103                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
104                 },
105                 _ => panic!("Unexpected event {:?}", events_4[2]),
106         }
107
108         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
109         // generates a duplicative private channel_update
110         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
111         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
112         assert_eq!(events_5.len(), 1);
113         match events_5[0] {
114                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
115                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
116                 },
117                 _ => panic!("Unexpected event {:?}", events_5[0]),
118         };
119
120         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
121         // announcement_signatures.
122         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
123         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
124         assert_eq!(events_6.len(), 1);
125         let as_announcement_sigs = match events_6[0] {
126                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
127                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
128                         msg.clone()
129                 },
130                 _ => panic!("Unexpected event {:?}", events_6[0]),
131         };
132         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
133         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
134
135         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
136         // broadcast the channel announcement globally, as well as re-send its (now-public)
137         // channel_update.
138         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
139         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
140         assert_eq!(events_7.len(), 1);
141         let (chan_announcement, as_update) = match events_7[0] {
142                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
143                         (msg.clone(), update_msg.clone())
144                 },
145                 _ => panic!("Unexpected event {:?}", events_7[0]),
146         };
147
148         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
149         // same channel_announcement.
150         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
151         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
152         assert_eq!(events_8.len(), 1);
153         let bs_update = match events_8[0] {
154                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
155                         assert_eq!(*msg, chan_announcement);
156                         update_msg.clone()
157                 },
158                 _ => panic!("Unexpected event {:?}", events_8[0]),
159         };
160
161         // Provide the channel announcement and public updates to the network graph
162         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
163         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
164         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
165
166         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
167         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
168         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
169
170         // Check that after deserialization and reconnection we can still generate an identical
171         // channel_announcement from the cached signatures.
172         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
173
174         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
175
176         reload_node!(nodes[0], &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
177
178         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
179 }
180
181 #[test]
182 fn test_no_txn_manager_serialize_deserialize() {
183         let chanmon_cfgs = create_chanmon_cfgs(2);
184         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
185         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
186         let persister: test_utils::TestPersister;
187         let new_chain_monitor: test_utils::TestChainMonitor;
188         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
189         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
190
191         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
192
193         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
194
195         let chan_0_monitor_serialized =
196                 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).encode();
197         reload_node!(nodes[0], nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
198
199         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
200         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
201         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
202         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
203
204         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
205         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
206         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
207         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
208
209         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
210         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
211         for node in nodes.iter() {
212                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
213                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
214                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
215         }
216
217         send_payment(&nodes[0], &[&nodes[1]], 1000000);
218 }
219
220 #[test]
221 fn test_manager_serialize_deserialize_events() {
222         // This test makes sure the events field in ChannelManager survives de/serialization
223         let chanmon_cfgs = create_chanmon_cfgs(2);
224         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
225         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
226         let persister: test_utils::TestPersister;
227         let new_chain_monitor: test_utils::TestChainMonitor;
228         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
229         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
230
231         // Start creating a channel, but stop right before broadcasting the funding transaction
232         let channel_value = 100000;
233         let push_msat = 10001;
234         let a_flags = channelmanager::provided_init_features();
235         let b_flags = channelmanager::provided_init_features();
236         let node_a = nodes.remove(0);
237         let node_b = nodes.remove(0);
238         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
239         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
240         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
241
242         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
243
244         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
245         check_added_monitors!(node_a, 0);
246
247         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
248         {
249                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
250                 assert_eq!(added_monitors.len(), 1);
251                 assert_eq!(added_monitors[0].0, funding_output);
252                 added_monitors.clear();
253         }
254
255         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
256         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
257         {
258                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
259                 assert_eq!(added_monitors.len(), 1);
260                 assert_eq!(added_monitors[0].0, funding_output);
261                 added_monitors.clear();
262         }
263         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
264
265         nodes.push(node_a);
266         nodes.push(node_b);
267
268         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
269         let chan_0_monitor_serialized = get_monitor!(nodes[0], bs_funding_signed.channel_id).encode();
270         reload_node!(nodes[0], nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
271
272         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
273
274         // After deserializing, make sure the funding_transaction is still held by the channel manager
275         let events_4 = nodes[0].node.get_and_clear_pending_events();
276         assert_eq!(events_4.len(), 0);
277         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
278         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
279
280         // Make sure the channel is functioning as though the de/serialization never happened
281         assert_eq!(nodes[0].node.list_channels().len(), 1);
282
283         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
284         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
285         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
286         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
287
288         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
289         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
290         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
291         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
292
293         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
294         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
295         for node in nodes.iter() {
296                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
297                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
298                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
299         }
300
301         send_payment(&nodes[0], &[&nodes[1]], 1000000);
302 }
303
304 #[test]
305 fn test_simple_manager_serialize_deserialize() {
306         let chanmon_cfgs = create_chanmon_cfgs(2);
307         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
308         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
309         let persister: test_utils::TestPersister;
310         let new_chain_monitor: test_utils::TestChainMonitor;
311         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
312         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
313         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
314
315         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
316         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
317
318         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
319
320         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
321         reload_node!(nodes[0], nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
322
323         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
324
325         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
326         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
327 }
328
329 #[test]
330 fn test_manager_serialize_deserialize_inconsistent_monitor() {
331         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
332         let chanmon_cfgs = create_chanmon_cfgs(4);
333         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
334         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
335         let logger: test_utils::TestLogger;
336         let fee_estimator: test_utils::TestFeeEstimator;
337         let persister: test_utils::TestPersister;
338         let new_chain_monitor: test_utils::TestChainMonitor;
339         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
340         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
341         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
342         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
343         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
344
345         let mut node_0_stale_monitors_serialized = Vec::new();
346         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
347                 let mut writer = test_utils::TestVecWriter(Vec::new());
348                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
349                 node_0_stale_monitors_serialized.push(writer.0);
350         }
351
352         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
353
354         // Serialize the ChannelManager here, but the monitor we keep up-to-date
355         let nodes_0_serialized = nodes[0].node.encode();
356
357         route_payment(&nodes[0], &[&nodes[3]], 1000000);
358         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
359         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
360         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
361
362         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
363         // nodes[3])
364         let mut node_0_monitors_serialized = Vec::new();
365         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
366                 node_0_monitors_serialized.push(get_monitor!(nodes[0], chan_id_iter).encode());
367         }
368
369         logger = test_utils::TestLogger::new();
370         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
371         persister = test_utils::TestPersister::new();
372         let keys_manager = &chanmon_cfgs[0].keys_manager;
373         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
374         nodes[0].chain_monitor = &new_chain_monitor;
375
376
377         let mut node_0_stale_monitors = Vec::new();
378         for serialized in node_0_stale_monitors_serialized.iter() {
379                 let mut read = &serialized[..];
380                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
381                 assert!(read.is_empty());
382                 node_0_stale_monitors.push(monitor);
383         }
384
385         let mut node_0_monitors = Vec::new();
386         for serialized in node_0_monitors_serialized.iter() {
387                 let mut read = &serialized[..];
388                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
389                 assert!(read.is_empty());
390                 node_0_monitors.push(monitor);
391         }
392
393         let mut nodes_0_read = &nodes_0_serialized[..];
394         if let Err(msgs::DecodeError::InvalidValue) =
395                 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
396                 default_config: UserConfig::default(),
397                 keys_manager,
398                 fee_estimator: &fee_estimator,
399                 chain_monitor: nodes[0].chain_monitor,
400                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
401                 logger: &logger,
402                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
403         }) { } else {
404                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
405         };
406
407         let mut nodes_0_read = &nodes_0_serialized[..];
408         let (_, nodes_0_deserialized_tmp) =
409                 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
410                 default_config: UserConfig::default(),
411                 keys_manager,
412                 fee_estimator: &fee_estimator,
413                 chain_monitor: nodes[0].chain_monitor,
414                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
415                 logger: &logger,
416                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
417         }).unwrap();
418         nodes_0_deserialized = nodes_0_deserialized_tmp;
419         assert!(nodes_0_read.is_empty());
420
421         { // Channel close should result in a commitment tx
422                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
423                 assert_eq!(txn.len(), 1);
424                 check_spends!(txn[0], funding_tx);
425                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
426         }
427
428         for monitor in node_0_monitors.drain(..) {
429                 assert_eq!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor),
430                         ChannelMonitorUpdateStatus::Completed);
431                 check_added_monitors!(nodes[0], 1);
432         }
433         nodes[0].node = &nodes_0_deserialized;
434         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
435
436         // nodes[1] and nodes[2] have no lost state with nodes[0]...
437         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
438         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
439         //... and we can even still claim the payment!
440         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
441
442         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
443         let reestablish = get_chan_reestablish_msgs!(nodes[3], nodes[0]).pop().unwrap();
444         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
445         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
446         let mut found_err = false;
447         for msg_event in nodes[0].node.get_and_clear_pending_msg_events() {
448                 if let MessageSendEvent::HandleError { ref action, .. } = msg_event {
449                         match action {
450                                 &ErrorAction::SendErrorMessage { ref msg } => {
451                                         assert_eq!(msg.channel_id, channel_id);
452                                         assert!(!found_err);
453                                         found_err = true;
454                                 },
455                                 _ => panic!("Unexpected event!"),
456                         }
457                 }
458         }
459         assert!(found_err);
460 }
461
462 fn do_test_data_loss_protect(reconnect_panicing: bool) {
463         // When we get a data_loss_protect proving we're behind, we immediately panic as the
464         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
465         // panic message informs the user they should force-close without broadcasting, which is tested
466         // if `reconnect_panicing` is not set.
467         let mut chanmon_cfgs = create_chanmon_cfgs(2);
468         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
469         // during signing due to revoked tx
470         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
471         let persister;
472         let new_chain_monitor;
473         let nodes_0_deserialized;
474         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
475         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
476         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
477
478         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
479
480         // Cache node A state before any channel update
481         let previous_node_state = nodes[0].node.encode();
482         let previous_chain_monitor_state = get_monitor!(nodes[0], chan.2).encode();
483
484         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
485         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
486
487         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
488         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
489
490         reload_node!(nodes[0], previous_node_state, &[&previous_chain_monitor_state], persister, new_chain_monitor, nodes_0_deserialized);
491
492         if reconnect_panicing {
493                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
494                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
495
496                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
497
498                 // Check we close channel detecting A is fallen-behind
499                 // Check that we sent the warning message when we detected that A has fallen behind,
500                 // and give the possibility for A to recover from the warning.
501                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
502                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
503                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
504
505                 {
506                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
507                         // The node B should not broadcast the transaction to force close the channel!
508                         assert!(node_txn.is_empty());
509                 }
510
511                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
512                 // Check A panics upon seeing proof it has fallen behind.
513                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
514                 return; // By this point we should have panic'ed!
515         }
516
517         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
518         check_added_monitors!(nodes[0], 1);
519         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
520         {
521                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
522                 assert_eq!(node_txn.len(), 0);
523         }
524
525         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
526                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
527                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
528                         match action {
529                                 &ErrorAction::SendErrorMessage { ref msg } => {
530                                         assert_eq!(msg.data, "Channel force-closed");
531                                 },
532                                 _ => panic!("Unexpected event!"),
533                         }
534                 } else {
535                         panic!("Unexpected event {:?}", msg)
536                 }
537         }
538
539         // after the warning message sent by B, we should not able to
540         // use the channel, or reconnect with success to the channel.
541         assert!(nodes[0].node.list_usable_channels().is_empty());
542         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
543         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
544         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
545
546         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
547         let mut err_msgs_0 = Vec::with_capacity(1);
548         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
549                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
550                         match action {
551                                 &ErrorAction::SendErrorMessage { ref msg } => {
552                                         assert_eq!(msg.data, "Failed to find corresponding channel");
553                                         err_msgs_0.push(msg.clone());
554                                 },
555                                 _ => panic!("Unexpected event!"),
556                         }
557                 } else {
558                         panic!("Unexpected event!");
559                 }
560         }
561         assert_eq!(err_msgs_0.len(), 1);
562         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
563         assert!(nodes[1].node.list_usable_channels().is_empty());
564         check_added_monitors!(nodes[1], 1);
565         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
566         check_closed_broadcast!(nodes[1], false);
567 }
568
569 #[test]
570 #[should_panic]
571 fn test_data_loss_protect_showing_stale_state_panics() {
572         do_test_data_loss_protect(true);
573 }
574
575 #[test]
576 fn test_force_close_without_broadcast() {
577         do_test_data_loss_protect(false);
578 }
579
580 #[test]
581 fn test_forwardable_regen() {
582         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
583         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
584         // HTLCs.
585         // We test it for both payment receipt and payment forwarding.
586
587         let chanmon_cfgs = create_chanmon_cfgs(3);
588         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
589         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
590         let persister: test_utils::TestPersister;
591         let new_chain_monitor: test_utils::TestChainMonitor;
592         let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
593         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
594         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
595         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
596
597         // First send a payment to nodes[1]
598         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
599         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
600         check_added_monitors!(nodes[0], 1);
601
602         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
603         assert_eq!(events.len(), 1);
604         let payment_event = SendEvent::from_event(events.pop().unwrap());
605         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
606         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
607
608         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
609
610         // Next send a payment which is forwarded by nodes[1]
611         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
612         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
613         check_added_monitors!(nodes[0], 1);
614
615         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
616         assert_eq!(events.len(), 1);
617         let payment_event = SendEvent::from_event(events.pop().unwrap());
618         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
619         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
620
621         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
622         // generated
623         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
624
625         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
626         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
627         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
628
629         let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id_1).encode();
630         let chan_1_monitor_serialized = get_monitor!(nodes[1], chan_id_2).encode();
631         reload_node!(nodes[1], nodes[1].node.encode(), &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
632
633         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
634         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
635         // the commitment state.
636         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
637
638         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
639
640         expect_pending_htlcs_forwardable!(nodes[1]);
641         expect_payment_claimable!(nodes[1], payment_hash, payment_secret, 100_000);
642         check_added_monitors!(nodes[1], 1);
643
644         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
645         assert_eq!(events.len(), 1);
646         let payment_event = SendEvent::from_event(events.pop().unwrap());
647         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
648         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
649         expect_pending_htlcs_forwardable!(nodes[2]);
650         expect_payment_claimable!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
651
652         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
653         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
654 }
655
656 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
657         // Test what happens if a node receives an MPP payment, claims it, but crashes before
658         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
659         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
660         // have the PaymentClaimable event, (b) have one (or two) channel(s) that goes on chain with the
661         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
662         // not have the preimage tied to the still-pending HTLC.
663         //
664         // To get to the correct state, on startup we should propagate the preimage to the
665         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
666         // receiving the preimage without a state update.
667         //
668         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
669         // definitely claimed.
670         let chanmon_cfgs = create_chanmon_cfgs(4);
671         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
672         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
673
674         let persister: test_utils::TestPersister;
675         let new_chain_monitor: test_utils::TestChainMonitor;
676         let nodes_3_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
677
678         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
679
680         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
681         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
682         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
683         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
684
685         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
686         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
687         assert_eq!(route.paths.len(), 2);
688         route.paths.sort_by(|path_a, _| {
689                 // Sort the path so that the path through nodes[1] comes first
690                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
691                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
692         });
693
694         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
695         check_added_monitors!(nodes[0], 2);
696
697         // Send the payment through to nodes[3] *without* clearing the PaymentClaimable event
698         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
699         assert_eq!(send_events.len(), 2);
700         do_pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[0].clone(), true, false, None);
701         do_pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[1].clone(), true, false, None);
702
703         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
704         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
705         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
706         if !persist_both_monitors {
707                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
708                         if outpoint.to_channel_id() == chan_id_not_persisted {
709                                 assert!(original_monitor.0.is_empty());
710                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
711                         }
712                 }
713         }
714
715         let original_manager = nodes[3].node.encode();
716
717         expect_payment_claimable!(nodes[3], payment_hash, payment_secret, 15_000_000);
718
719         nodes[3].node.claim_funds(payment_preimage);
720         check_added_monitors!(nodes[3], 2);
721         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
722
723         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
724         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
725         // with the old ChannelManager.
726         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
727         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
728                 if outpoint.to_channel_id() == chan_id_persisted {
729                         assert!(updated_monitor.0.is_empty());
730                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
731                 }
732         }
733         // If `persist_both_monitors` is set, get the second monitor here as well
734         if persist_both_monitors {
735                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
736                         if outpoint.to_channel_id() == chan_id_not_persisted {
737                                 assert!(original_monitor.0.is_empty());
738                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
739                         }
740                 }
741         }
742
743         // Now restart nodes[3].
744         reload_node!(nodes[3], original_manager, &[&updated_monitor.0, &original_monitor.0], persister, new_chain_monitor, nodes_3_deserialized);
745
746         // On startup the preimage should have been copied into the non-persisted monitor:
747         assert!(get_monitor!(nodes[3], chan_id_persisted).get_stored_preimages().contains_key(&payment_hash));
748         assert!(get_monitor!(nodes[3], chan_id_not_persisted).get_stored_preimages().contains_key(&payment_hash));
749
750         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
751         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
752
753         // During deserialization, we should have closed one channel and broadcast its latest
754         // commitment transaction. We should also still have the original PaymentClaimable event we
755         // never finished processing.
756         let events = nodes[3].node.get_and_clear_pending_events();
757         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
758         if let Event::PaymentClaimable { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
759         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
760         if persist_both_monitors {
761                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
762         }
763
764         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
765         // ChannelManager prior to handling the original one.
766         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
767                 events[if persist_both_monitors { 3 } else { 2 }]
768         {
769                 assert_eq!(payment_hash, our_payment_hash);
770         } else { panic!(); }
771
772         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
773         if !persist_both_monitors {
774                 // If one of the two channels is still live, reveal the payment preimage over it.
775
776                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
777                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
778                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
779                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
780
781                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
782                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
783                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
784
785                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
786
787                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
788                 // claim should fly.
789                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
790                 check_added_monitors!(nodes[3], 1);
791                 assert_eq!(ds_msgs.len(), 2);
792                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[0] {} else { panic!(); }
793
794                 let cs_updates = match ds_msgs[1] {
795                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
796                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
797                                 check_added_monitors!(nodes[2], 1);
798                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
799                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
800                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
801                                 cs_updates
802                         }
803                         _ => panic!(),
804                 };
805
806                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
807                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
808                 expect_payment_sent!(nodes[0], payment_preimage);
809         }
810 }
811
812 #[test]
813 fn test_partial_claim_before_restart() {
814         do_test_partial_claim_before_restart(false);
815         do_test_partial_claim_before_restart(true);
816 }
817
818 fn do_forwarded_payment_no_manager_persistence(use_cs_commitment: bool, claim_htlc: bool, use_intercept: bool) {
819         if !use_cs_commitment { assert!(!claim_htlc); }
820         // If we go to forward a payment, and the ChannelMonitor persistence completes, but the
821         // ChannelManager does not, we shouldn't try to forward the payment again, nor should we fail
822         // it back until the ChannelMonitor decides the fate of the HTLC.
823         // This was never an issue, but it may be easy to regress here going forward.
824         let chanmon_cfgs = create_chanmon_cfgs(3);
825         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
826         let mut intercept_forwards_config = test_default_channel_config();
827         intercept_forwards_config.accept_intercept_htlcs = true;
828         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), None]);
829
830         let persister;
831         let new_chain_monitor;
832         let nodes_1_deserialized;
833
834         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
835
836         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
837         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
838
839         let intercept_scid = nodes[1].node.get_intercept_scid();
840
841         let (mut route, payment_hash, payment_preimage, payment_secret) =
842                 get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
843         if use_intercept {
844                 route.paths[0][1].short_channel_id = intercept_scid;
845         }
846         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
847         let htlc_expiry = nodes[0].best_block_info().1 + TEST_FINAL_CLTV;
848         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), payment_id).unwrap();
849         check_added_monitors!(nodes[0], 1);
850
851         let payment_event = SendEvent::from_node(&nodes[0]);
852         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
853         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
854
855         // Store the `ChannelManager` before handling the `PendingHTLCsForwardable`/`HTLCIntercepted`
856         // events, expecting either event (and the HTLC itself) to be missing on reload even though its
857         // present when we serialized.
858         let node_encoded = nodes[1].node.encode();
859
860         let mut intercept_id = None;
861         let mut expected_outbound_amount_msat = None;
862         if use_intercept {
863                 let events = nodes[1].node.get_and_clear_pending_events();
864                 assert_eq!(events.len(), 1);
865                 match events[0] {
866                         Event::HTLCIntercepted { intercept_id: ev_id, expected_outbound_amount_msat: ev_amt, .. } => {
867                                 intercept_id = Some(ev_id);
868                                 expected_outbound_amount_msat = Some(ev_amt);
869                         },
870                         _ => panic!()
871                 }
872                 nodes[1].node.forward_intercepted_htlc(intercept_id.unwrap(), &chan_id_2,
873                         nodes[2].node.get_our_node_id(), expected_outbound_amount_msat.unwrap()).unwrap();
874         }
875
876         expect_pending_htlcs_forwardable!(nodes[1]);
877
878         let payment_event = SendEvent::from_node(&nodes[1]);
879         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
880         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
881         check_added_monitors!(nodes[2], 1);
882
883         if claim_htlc {
884                 get_monitor!(nodes[2], chan_id_2).provide_payment_preimage(&payment_hash, &payment_preimage,
885                         &nodes[2].tx_broadcaster, &LowerBoundedFeeEstimator(nodes[2].fee_estimator), &nodes[2].logger);
886         }
887         assert!(nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
888
889         let _ = nodes[2].node.get_and_clear_pending_msg_events();
890
891         nodes[2].node.force_close_broadcasting_latest_txn(&chan_id_2, &nodes[1].node.get_our_node_id()).unwrap();
892         let cs_commitment_tx = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
893         assert_eq!(cs_commitment_tx.len(), if claim_htlc { 2 } else { 1 });
894
895         check_added_monitors!(nodes[2], 1);
896         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
897         check_closed_broadcast!(nodes[2], true);
898
899         let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id_1).encode();
900         let chan_1_monitor_serialized = get_monitor!(nodes[1], chan_id_2).encode();
901         reload_node!(nodes[1], node_encoded, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
902
903         // Note that this checks that this is the only event on nodes[1], implying the
904         // `HTLCIntercepted` event has been removed in the `use_intercept` case.
905         check_closed_event!(nodes[1], 1, ClosureReason::OutdatedChannelManager);
906
907         if use_intercept {
908                 // Attempt to forward the HTLC back out over nodes[1]' still-open channel, ensuring we get
909                 // a intercept-doesn't-exist error.
910                 let forward_err = nodes[1].node.forward_intercepted_htlc(intercept_id.unwrap(), &chan_id_1,
911                         nodes[0].node.get_our_node_id(), expected_outbound_amount_msat.unwrap()).unwrap_err();
912                 assert_eq!(forward_err, APIError::APIMisuseError {
913                         err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.unwrap().0))
914                 });
915         }
916
917         let bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
918         assert_eq!(bs_commitment_tx.len(), 1);
919
920         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
921         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
922
923         if use_cs_commitment {
924                 // If we confirm a commitment transaction that has the HTLC on-chain, nodes[1] should wait
925                 // for an HTLC-spending transaction before it does anything with the HTLC upstream.
926                 confirm_transaction(&nodes[1], &cs_commitment_tx[0]);
927                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
928                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
929
930                 if claim_htlc {
931                         confirm_transaction(&nodes[1], &cs_commitment_tx[1]);
932                 } else {
933                         connect_blocks(&nodes[1], htlc_expiry - nodes[1].best_block_info().1);
934                         let bs_htlc_timeout_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
935                         assert_eq!(bs_htlc_timeout_tx.len(), 1);
936                         confirm_transaction(&nodes[1], &bs_htlc_timeout_tx[0]);
937                 }
938         } else {
939                 confirm_transaction(&nodes[1], &bs_commitment_tx[0]);
940         }
941
942         if !claim_htlc {
943                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
944         } else {
945                 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(1000), false, true);
946         }
947         check_added_monitors!(nodes[1], 1);
948
949         let events = nodes[1].node.get_and_clear_pending_msg_events();
950         assert_eq!(events.len(), 1);
951         match &events[0] {
952                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { update_fulfill_htlcs, update_fail_htlcs, commitment_signed, .. }, .. } => {
953                         if claim_htlc {
954                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
955                         } else {
956                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
957                         }
958                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
959                 },
960                 _ => panic!("Unexpected event"),
961         }
962
963         if claim_htlc {
964                 expect_payment_sent!(nodes[0], payment_preimage);
965         } else {
966                 expect_payment_failed!(nodes[0], payment_hash, false);
967         }
968 }
969
970 #[test]
971 fn forwarded_payment_no_manager_persistence() {
972         do_forwarded_payment_no_manager_persistence(true, true, false);
973         do_forwarded_payment_no_manager_persistence(true, false, false);
974         do_forwarded_payment_no_manager_persistence(false, false, false);
975 }
976
977 #[test]
978 fn intercepted_payment_no_manager_persistence() {
979         do_forwarded_payment_no_manager_persistence(true, true, true);
980         do_forwarded_payment_no_manager_persistence(true, false, true);
981         do_forwarded_payment_no_manager_persistence(false, false, true);
982 }
983
984 #[test]
985 fn removed_payment_no_manager_persistence() {
986         // If an HTLC is failed to us on a channel, and the ChannelMonitor persistence completes, but
987         // the corresponding ChannelManager persistence does not, we need to ensure that the HTLC is
988         // still failed back to the previous hop even though the ChannelMonitor now no longer is aware
989         // of the HTLC. This was previously broken as no attempt was made to figure out which HTLCs
990         // were left dangling when a channel was force-closed due to a stale ChannelManager.
991         let chanmon_cfgs = create_chanmon_cfgs(3);
992         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
993         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
994
995         let persister;
996         let new_chain_monitor;
997         let nodes_1_deserialized;
998
999         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1000
1001         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1002         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1003
1004         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
1005
1006         let node_encoded = nodes[1].node.encode();
1007
1008         nodes[2].node.fail_htlc_backwards(&payment_hash);
1009         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
1010         check_added_monitors!(nodes[2], 1);
1011         let events = nodes[2].node.get_and_clear_pending_msg_events();
1012         assert_eq!(events.len(), 1);
1013         match &events[0] {
1014                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. }, .. } => {
1015                         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_htlcs[0]);
1016                         commitment_signed_dance!(nodes[1], nodes[2], commitment_signed, false);
1017                 },
1018                 _ => panic!("Unexpected event"),
1019         }
1020
1021         let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id_1).encode();
1022         let chan_1_monitor_serialized = get_monitor!(nodes[1], chan_id_2).encode();
1023         reload_node!(nodes[1], node_encoded, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1024
1025         match nodes[1].node.pop_pending_event().unwrap() {
1026                 Event::ChannelClosed { ref reason, .. } => {
1027                         assert_eq!(*reason, ClosureReason::OutdatedChannelManager);
1028                 },
1029                 _ => panic!("Unexpected event"),
1030         }
1031
1032         // Now that the ChannelManager has force-closed the channel which had the HTLC removed, it is
1033         // now forgotten everywhere. The ChannelManager should have, as a side-effect of reload,
1034         // learned that the HTLC is gone from the ChannelMonitor and added it to the to-fail-back set.
1035         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
1036         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
1037
1038         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
1039         check_added_monitors!(nodes[1], 1);
1040         let events = nodes[1].node.get_and_clear_pending_msg_events();
1041         assert_eq!(events.len(), 1);
1042         match &events[0] {
1043                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. }, .. } => {
1044                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
1045                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
1046                 },
1047                 _ => panic!("Unexpected event"),
1048         }
1049
1050         expect_payment_failed!(nodes[0], payment_hash, false);
1051 }