1 // This file is Copyright its original authors, visible in version control
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
10 //! Functional tests which test for correct behavior across node restarts.
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::ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId};
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;
27 use bitcoin::hash_types::BlockHash;
29 use crate::prelude::*;
30 use core::default::Default;
31 use crate::sync::Mutex;
33 use crate::ln::functional_test_utils::*;
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::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &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);
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);
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());
54 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
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);
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());
63 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.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: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
66 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
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());
77 _ => panic!("Unexpected event {:?}", events_3[0]),
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);
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;
92 _ => panic!("Unexpected event {:?}", events_4[0]),
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());
99 _ => panic!("Unexpected event {:?}", events_4[1]),
102 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
103 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
105 _ => panic!("Unexpected event {:?}", events_4[2]),
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);
114 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
115 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
117 _ => panic!("Unexpected event {:?}", events_5[0]),
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());
130 _ => panic!("Unexpected event {:?}", events_6[0]),
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());
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)
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())
145 _ => panic!("Unexpected event {:?}", events_7[0]),
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);
158 _ => panic!("Unexpected event {:?}", events_8[0]),
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();
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);
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);
174 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
176 reload_node!(nodes[0], &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
178 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
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::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
189 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
191 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
193 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
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);
199 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.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: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
202 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
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());
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();
217 send_payment(&nodes[0], &[&nodes[1]], 1000000);
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::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
229 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
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 node_a = nodes.remove(0);
235 let node_b = nodes.remove(0);
236 let a_flags = node_a.node.init_features();
237 let b_flags = node_b.node.init_features();
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()));
242 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
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);
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()));
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();
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);
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();
263 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
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);
272 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
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);
280 // Make sure the channel is functioning as though the de/serialization never happened
281 assert_eq!(nodes[0].node.list_channels().len(), 1);
283 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.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: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
286 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
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());
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();
301 send_payment(&nodes[0], &[&nodes[1]], 1000000);
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::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &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).2;
315 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
316 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
318 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
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);
323 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
325 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
326 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
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::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &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).2;
342 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0).2;
343 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
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);
352 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
354 // Serialize the ChannelManager here, but the monitor we keep up-to-date
355 let nodes_0_serialized = nodes[0].node.encode();
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);
362 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
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());
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;
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, keys_manager)).unwrap();
381 assert!(read.is_empty());
382 node_0_stale_monitors.push(monitor);
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, keys_manager)).unwrap();
389 assert!(read.is_empty());
390 node_0_monitors.push(monitor);
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::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
396 default_config: UserConfig::default(),
397 entropy_source: keys_manager,
398 node_signer: keys_manager,
399 signer_provider: keys_manager,
400 fee_estimator: &fee_estimator,
401 router: &nodes[0].router,
402 chain_monitor: nodes[0].chain_monitor,
403 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
405 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
407 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
410 let mut nodes_0_read = &nodes_0_serialized[..];
411 let (_, nodes_0_deserialized_tmp) =
412 <(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 {
413 default_config: UserConfig::default(),
414 entropy_source: keys_manager,
415 node_signer: keys_manager,
416 signer_provider: keys_manager,
417 fee_estimator: &fee_estimator,
418 router: nodes[0].router,
419 chain_monitor: nodes[0].chain_monitor,
420 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
422 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
424 nodes_0_deserialized = nodes_0_deserialized_tmp;
425 assert!(nodes_0_read.is_empty());
427 { // Channel close should result in a commitment tx
428 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
429 assert_eq!(txn.len(), 1);
430 check_spends!(txn[0], funding_tx);
431 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
434 for monitor in node_0_monitors.drain(..) {
435 assert_eq!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor),
436 ChannelMonitorUpdateStatus::Completed);
437 check_added_monitors!(nodes[0], 1);
439 nodes[0].node = &nodes_0_deserialized;
440 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
442 // nodes[1] and nodes[2] have no lost state with nodes[0]...
443 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
444 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
445 //... and we can even still claim the payment!
446 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
448 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
449 let reestablish = get_chan_reestablish_msgs!(nodes[3], nodes[0]).pop().unwrap();
450 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: nodes[3].node.init_features(), remote_network_address: None }).unwrap();
451 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
452 let mut found_err = false;
453 for msg_event in nodes[0].node.get_and_clear_pending_msg_events() {
454 if let MessageSendEvent::HandleError { ref action, .. } = msg_event {
456 &ErrorAction::SendErrorMessage { ref msg } => {
457 assert_eq!(msg.channel_id, channel_id);
461 _ => panic!("Unexpected event!"),
468 fn do_test_data_loss_protect(reconnect_panicing: bool) {
469 // When we get a data_loss_protect proving we're behind, we immediately panic as the
470 // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
471 // panic message informs the user they should force-close without broadcasting, which is tested
472 // if `reconnect_panicing` is not set.
473 let mut chanmon_cfgs = create_chanmon_cfgs(2);
474 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
475 // during signing due to revoked tx
476 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
478 let new_chain_monitor;
479 let nodes_0_deserialized;
480 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
481 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
482 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
484 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
486 // Cache node A state before any channel update
487 let previous_node_state = nodes[0].node.encode();
488 let previous_chain_monitor_state = get_monitor!(nodes[0], chan.2).encode();
490 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
491 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
493 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
494 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
496 reload_node!(nodes[0], previous_node_state, &[&previous_chain_monitor_state], persister, new_chain_monitor, nodes_0_deserialized);
498 if reconnect_panicing {
499 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
500 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
502 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
504 // Check we close channel detecting A is fallen-behind
505 // Check that we sent the warning message when we detected that A has fallen behind,
506 // and give the possibility for A to recover from the warning.
507 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
508 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
509 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
512 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
513 // The node B should not broadcast the transaction to force close the channel!
514 assert!(node_txn.is_empty());
517 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
518 // Check A panics upon seeing proof it has fallen behind.
519 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
520 return; // By this point we should have panic'ed!
523 nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
524 check_added_monitors!(nodes[0], 1);
525 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
527 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
528 assert_eq!(node_txn.len(), 0);
531 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
532 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
533 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
535 &ErrorAction::SendErrorMessage { ref msg } => {
536 assert_eq!(msg.data, "Channel force-closed");
538 _ => panic!("Unexpected event!"),
541 panic!("Unexpected event {:?}", msg)
545 // after the warning message sent by B, we should not able to
546 // use the channel, or reconnect with success to the channel.
547 assert!(nodes[0].node.list_usable_channels().is_empty());
548 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
549 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
550 let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
552 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
553 let mut err_msgs_0 = Vec::with_capacity(1);
554 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
555 if let MessageSendEvent::HandleError { ref action, .. } = msg {
557 &ErrorAction::SendErrorMessage { ref msg } => {
558 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()));
559 err_msgs_0.push(msg.clone());
561 _ => panic!("Unexpected event!"),
564 panic!("Unexpected event!");
567 assert_eq!(err_msgs_0.len(), 1);
568 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
569 assert!(nodes[1].node.list_usable_channels().is_empty());
570 check_added_monitors!(nodes[1], 1);
571 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: 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()) });
572 check_closed_broadcast!(nodes[1], false);
577 fn test_data_loss_protect_showing_stale_state_panics() {
578 do_test_data_loss_protect(true);
582 fn test_force_close_without_broadcast() {
583 do_test_data_loss_protect(false);
587 fn test_forwardable_regen() {
588 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
589 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
591 // We test it for both payment receipt and payment forwarding.
593 let chanmon_cfgs = create_chanmon_cfgs(3);
594 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
595 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
596 let persister: test_utils::TestPersister;
597 let new_chain_monitor: test_utils::TestChainMonitor;
598 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>;
599 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
600 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
601 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
603 // First send a payment to nodes[1]
604 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
605 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
606 check_added_monitors!(nodes[0], 1);
608 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
609 assert_eq!(events.len(), 1);
610 let payment_event = SendEvent::from_event(events.pop().unwrap());
611 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
612 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
614 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
616 // Next send a payment which is forwarded by nodes[1]
617 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
618 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
619 check_added_monitors!(nodes[0], 1);
621 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
622 assert_eq!(events.len(), 1);
623 let payment_event = SendEvent::from_event(events.pop().unwrap());
624 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
625 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
627 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
629 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
631 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
632 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
633 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
635 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id_1).encode();
636 let chan_1_monitor_serialized = get_monitor!(nodes[1], chan_id_2).encode();
637 reload_node!(nodes[1], nodes[1].node.encode(), &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
639 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
640 // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
641 // the commitment state.
642 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
644 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
646 expect_pending_htlcs_forwardable!(nodes[1]);
647 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, 100_000);
648 check_added_monitors!(nodes[1], 1);
650 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
651 assert_eq!(events.len(), 1);
652 let payment_event = SendEvent::from_event(events.pop().unwrap());
653 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
654 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
655 expect_pending_htlcs_forwardable!(nodes[2]);
656 expect_payment_claimable!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
658 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
659 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
662 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
663 // Test what happens if a node receives an MPP payment, claims it, but crashes before
664 // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
665 // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
666 // have the PaymentClaimable event, (b) have one (or two) channel(s) that goes on chain with the
667 // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
668 // not have the preimage tied to the still-pending HTLC.
670 // To get to the correct state, on startup we should propagate the preimage to the
671 // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
672 // receiving the preimage without a state update.
674 // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
675 // definitely claimed.
676 let chanmon_cfgs = create_chanmon_cfgs(4);
677 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
678 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
680 let persister: test_utils::TestPersister;
681 let new_chain_monitor: test_utils::TestChainMonitor;
682 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>;
684 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
686 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
687 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
688 let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0).2;
689 let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0).2;
691 // Create an MPP route for 15k sats, more than the default htlc-max of 10%
692 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
693 assert_eq!(route.paths.len(), 2);
694 route.paths.sort_by(|path_a, _| {
695 // Sort the path so that the path through nodes[1] comes first
696 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
697 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
700 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
701 check_added_monitors!(nodes[0], 2);
703 // Send the payment through to nodes[3] *without* clearing the PaymentClaimable event
704 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
705 assert_eq!(send_events.len(), 2);
706 let (node_1_msgs, mut send_events) = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &send_events);
707 let (node_2_msgs, _send_events) = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &send_events);
708 do_pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, true, false, None);
709 do_pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_2_msgs, true, false, None);
711 // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
712 // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
713 let mut original_monitor = test_utils::TestVecWriter(Vec::new());
714 if !persist_both_monitors {
715 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
716 if outpoint.to_channel_id() == chan_id_not_persisted {
717 assert!(original_monitor.0.is_empty());
718 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
723 let original_manager = nodes[3].node.encode();
725 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, 15_000_000);
727 nodes[3].node.claim_funds(payment_preimage);
728 check_added_monitors!(nodes[3], 2);
729 expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
731 // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
732 // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
733 // with the old ChannelManager.
734 let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
735 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
736 if outpoint.to_channel_id() == chan_id_persisted {
737 assert!(updated_monitor.0.is_empty());
738 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
741 // If `persist_both_monitors` is set, get the second monitor here as well
742 if persist_both_monitors {
743 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
744 if outpoint.to_channel_id() == chan_id_not_persisted {
745 assert!(original_monitor.0.is_empty());
746 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
751 // Now restart nodes[3].
752 reload_node!(nodes[3], original_manager, &[&updated_monitor.0, &original_monitor.0], persister, new_chain_monitor, nodes_3_deserialized);
754 // On startup the preimage should have been copied into the non-persisted monitor:
755 assert!(get_monitor!(nodes[3], chan_id_persisted).get_stored_preimages().contains_key(&payment_hash));
756 assert!(get_monitor!(nodes[3], chan_id_not_persisted).get_stored_preimages().contains_key(&payment_hash));
758 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
759 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
761 // During deserialization, we should have closed one channel and broadcast its latest
762 // commitment transaction. We should also still have the original PaymentClaimable event we
763 // never finished processing.
764 let events = nodes[3].node.get_and_clear_pending_events();
765 assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
766 if let Event::PaymentClaimable { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
767 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
768 if persist_both_monitors {
769 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
772 // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
773 // ChannelManager prior to handling the original one.
774 if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
775 events[if persist_both_monitors { 3 } else { 2 }]
777 assert_eq!(payment_hash, our_payment_hash);
780 assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
781 if !persist_both_monitors {
782 // If one of the two channels is still live, reveal the payment preimage over it.
784 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: nodes[2].node.init_features(), remote_network_address: None }).unwrap();
785 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
786 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: nodes[3].node.init_features(), remote_network_address: None }).unwrap();
787 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
789 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
790 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
791 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
793 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
795 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
797 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
798 check_added_monitors!(nodes[3], 1);
799 assert_eq!(ds_msgs.len(), 2);
800 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[0] {} else { panic!(); }
802 let cs_updates = match ds_msgs[1] {
803 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
804 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
805 check_added_monitors!(nodes[2], 1);
806 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
807 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
808 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
814 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
815 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
816 expect_payment_sent!(nodes[0], payment_preimage);
821 fn test_partial_claim_before_restart() {
822 do_test_partial_claim_before_restart(false);
823 do_test_partial_claim_before_restart(true);
826 fn do_forwarded_payment_no_manager_persistence(use_cs_commitment: bool, claim_htlc: bool, use_intercept: bool) {
827 if !use_cs_commitment { assert!(!claim_htlc); }
828 // If we go to forward a payment, and the ChannelMonitor persistence completes, but the
829 // ChannelManager does not, we shouldn't try to forward the payment again, nor should we fail
830 // it back until the ChannelMonitor decides the fate of the HTLC.
831 // This was never an issue, but it may be easy to regress here going forward.
832 let chanmon_cfgs = create_chanmon_cfgs(3);
833 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
834 let mut intercept_forwards_config = test_default_channel_config();
835 intercept_forwards_config.accept_intercept_htlcs = true;
836 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), None]);
839 let new_chain_monitor;
840 let nodes_1_deserialized;
842 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
844 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
845 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
847 let intercept_scid = nodes[1].node.get_intercept_scid();
849 let (mut route, payment_hash, payment_preimage, payment_secret) =
850 get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
852 route.paths[0][1].short_channel_id = intercept_scid;
854 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
855 let htlc_expiry = nodes[0].best_block_info().1 + TEST_FINAL_CLTV;
856 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), payment_id).unwrap();
857 check_added_monitors!(nodes[0], 1);
859 let payment_event = SendEvent::from_node(&nodes[0]);
860 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
861 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
863 // Store the `ChannelManager` before handling the `PendingHTLCsForwardable`/`HTLCIntercepted`
864 // events, expecting either event (and the HTLC itself) to be missing on reload even though its
865 // present when we serialized.
866 let node_encoded = nodes[1].node.encode();
868 let mut intercept_id = None;
869 let mut expected_outbound_amount_msat = None;
871 let events = nodes[1].node.get_and_clear_pending_events();
872 assert_eq!(events.len(), 1);
874 Event::HTLCIntercepted { intercept_id: ev_id, expected_outbound_amount_msat: ev_amt, .. } => {
875 intercept_id = Some(ev_id);
876 expected_outbound_amount_msat = Some(ev_amt);
880 nodes[1].node.forward_intercepted_htlc(intercept_id.unwrap(), &chan_id_2,
881 nodes[2].node.get_our_node_id(), expected_outbound_amount_msat.unwrap()).unwrap();
884 expect_pending_htlcs_forwardable!(nodes[1]);
886 let payment_event = SendEvent::from_node(&nodes[1]);
887 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
888 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
889 check_added_monitors!(nodes[2], 1);
892 get_monitor!(nodes[2], chan_id_2).provide_payment_preimage(&payment_hash, &payment_preimage,
893 &nodes[2].tx_broadcaster, &LowerBoundedFeeEstimator(nodes[2].fee_estimator), &nodes[2].logger);
895 assert!(nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
897 let _ = nodes[2].node.get_and_clear_pending_msg_events();
899 nodes[2].node.force_close_broadcasting_latest_txn(&chan_id_2, &nodes[1].node.get_our_node_id()).unwrap();
900 let cs_commitment_tx = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
901 assert_eq!(cs_commitment_tx.len(), if claim_htlc { 2 } else { 1 });
903 check_added_monitors!(nodes[2], 1);
904 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
905 check_closed_broadcast!(nodes[2], true);
907 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id_1).encode();
908 let chan_1_monitor_serialized = get_monitor!(nodes[1], chan_id_2).encode();
909 reload_node!(nodes[1], node_encoded, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
911 // Note that this checks that this is the only event on nodes[1], implying the
912 // `HTLCIntercepted` event has been removed in the `use_intercept` case.
913 check_closed_event!(nodes[1], 1, ClosureReason::OutdatedChannelManager);
916 // Attempt to forward the HTLC back out over nodes[1]' still-open channel, ensuring we get
917 // a intercept-doesn't-exist error.
918 let forward_err = nodes[1].node.forward_intercepted_htlc(intercept_id.unwrap(), &chan_id_1,
919 nodes[0].node.get_our_node_id(), expected_outbound_amount_msat.unwrap()).unwrap_err();
920 assert_eq!(forward_err, APIError::APIMisuseError {
921 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.unwrap().0))
925 let bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
926 assert_eq!(bs_commitment_tx.len(), 1);
928 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
929 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
931 if use_cs_commitment {
932 // If we confirm a commitment transaction that has the HTLC on-chain, nodes[1] should wait
933 // for an HTLC-spending transaction before it does anything with the HTLC upstream.
934 confirm_transaction(&nodes[1], &cs_commitment_tx[0]);
935 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
936 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
939 confirm_transaction(&nodes[1], &cs_commitment_tx[1]);
941 connect_blocks(&nodes[1], htlc_expiry - nodes[1].best_block_info().1);
942 let bs_htlc_timeout_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
943 assert_eq!(bs_htlc_timeout_tx.len(), 1);
944 confirm_transaction(&nodes[1], &bs_htlc_timeout_tx[0]);
947 confirm_transaction(&nodes[1], &bs_commitment_tx[0]);
951 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 }]);
953 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(1000), false, true);
955 check_added_monitors!(nodes[1], 1);
957 let events = nodes[1].node.get_and_clear_pending_msg_events();
958 assert_eq!(events.len(), 1);
960 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { update_fulfill_htlcs, update_fail_htlcs, commitment_signed, .. }, .. } => {
962 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
964 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
966 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
968 _ => panic!("Unexpected event"),
972 expect_payment_sent!(nodes[0], payment_preimage);
974 expect_payment_failed!(nodes[0], payment_hash, false);
979 fn forwarded_payment_no_manager_persistence() {
980 do_forwarded_payment_no_manager_persistence(true, true, false);
981 do_forwarded_payment_no_manager_persistence(true, false, false);
982 do_forwarded_payment_no_manager_persistence(false, false, false);
986 fn intercepted_payment_no_manager_persistence() {
987 do_forwarded_payment_no_manager_persistence(true, true, true);
988 do_forwarded_payment_no_manager_persistence(true, false, true);
989 do_forwarded_payment_no_manager_persistence(false, false, true);
993 fn removed_payment_no_manager_persistence() {
994 // If an HTLC is failed to us on a channel, and the ChannelMonitor persistence completes, but
995 // the corresponding ChannelManager persistence does not, we need to ensure that the HTLC is
996 // still failed back to the previous hop even though the ChannelMonitor now no longer is aware
997 // of the HTLC. This was previously broken as no attempt was made to figure out which HTLCs
998 // were left dangling when a channel was force-closed due to a stale ChannelManager.
999 let chanmon_cfgs = create_chanmon_cfgs(3);
1000 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1001 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1004 let new_chain_monitor;
1005 let nodes_1_deserialized;
1007 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1009 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1010 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
1012 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
1014 let node_encoded = nodes[1].node.encode();
1016 nodes[2].node.fail_htlc_backwards(&payment_hash);
1017 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
1018 check_added_monitors!(nodes[2], 1);
1019 let events = nodes[2].node.get_and_clear_pending_msg_events();
1020 assert_eq!(events.len(), 1);
1022 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. }, .. } => {
1023 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_htlcs[0]);
1024 commitment_signed_dance!(nodes[1], nodes[2], commitment_signed, false);
1026 _ => panic!("Unexpected event"),
1029 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id_1).encode();
1030 let chan_1_monitor_serialized = get_monitor!(nodes[1], chan_id_2).encode();
1031 reload_node!(nodes[1], node_encoded, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1033 match nodes[1].node.pop_pending_event().unwrap() {
1034 Event::ChannelClosed { ref reason, .. } => {
1035 assert_eq!(*reason, ClosureReason::OutdatedChannelManager);
1037 _ => panic!("Unexpected event"),
1040 // Now that the ChannelManager has force-closed the channel which had the HTLC removed, it is
1041 // now forgotten everywhere. The ChannelManager should have, as a side-effect of reload,
1042 // learned that the HTLC is gone from the ChannelMonitor and added it to the to-fail-back set.
1043 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
1044 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
1046 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 }]);
1047 check_added_monitors!(nodes[1], 1);
1048 let events = nodes[1].node.get_and_clear_pending_msg_events();
1049 assert_eq!(events.len(), 1);
1051 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. }, .. } => {
1052 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
1053 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
1055 _ => panic!("Unexpected event"),
1058 expect_payment_failed!(nodes[0], payment_hash, false);