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