cd75d48ebcbf29dbd758039b4448b2012696d28a
[rust-lightning] / lightning / src / ln / payment_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test the payment retry logic in ChannelManager, including various edge-cases around
11 //! serialization ordering between ChannelManager/ChannelMonitors and ensuring we can still retry
12 //! payments thereafter.
13
14 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
15 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::sign::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason};
19 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
20 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails, RecipientOnionFields, HTLCForwardInfo, PendingHTLCRouting, PendingAddHTLCInfo};
21 use crate::ln::features::Bolt11InvoiceFeatures;
22 use crate::ln::{msgs, PaymentSecret, PaymentPreimage};
23 use crate::ln::msgs::ChannelMessageHandler;
24 use crate::ln::outbound_payment::Retry;
25 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
26 use crate::routing::router::{get_route, Path, PaymentParameters, Route, Router, RouteHint, RouteHintHop, RouteHop, RouteParameters, find_route};
27 use crate::routing::scoring::ChannelUsage;
28 use crate::util::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
31 use crate::util::string::UntrustedString;
32
33 use bitcoin::network::constants::Network;
34
35 use crate::prelude::*;
36
37 use crate::ln::functional_test_utils::*;
38 use crate::routing::gossip::NodeId;
39 #[cfg(feature = "std")]
40 use {
41         crate::util::time::tests::SinceEpoch,
42         std::time::{SystemTime, Instant, Duration}
43 };
44
45 #[test]
46 fn mpp_failure() {
47         let chanmon_cfgs = create_chanmon_cfgs(4);
48         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
49         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
50         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
51
52         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
53         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
54         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
55         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
56
57         let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
58         let path = route.paths[0].clone();
59         route.paths.push(path);
60         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
61         route.paths[0].hops[0].short_channel_id = chan_1_id;
62         route.paths[0].hops[1].short_channel_id = chan_3_id;
63         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
64         route.paths[1].hops[0].short_channel_id = chan_2_id;
65         route.paths[1].hops[1].short_channel_id = chan_4_id;
66         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
67         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
68 }
69
70 #[test]
71 fn mpp_retry() {
72         let chanmon_cfgs = create_chanmon_cfgs(4);
73         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
74         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
75         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
76
77         let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
78         let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
79         let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
80         let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
81         // Rebalance
82         send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
83
84         let amt_msat = 1_000_000;
85         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
86         let path = route.paths[0].clone();
87         route.paths.push(path);
88         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
89         route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
90         route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
91         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
92         route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
93         route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
94
95         // Initiate the MPP payment.
96         let payment_id = PaymentId(payment_hash.0);
97         let mut route_params = RouteParameters {
98                 payment_params: route.payment_params.clone().unwrap(),
99                 final_value_msat: amt_msat,
100         };
101
102         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
103         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
104                 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
105         check_added_monitors!(nodes[0], 2); // one monitor per path
106         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
107         assert_eq!(events.len(), 2);
108
109         // Pass half of the payment along the success path.
110         let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
111         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
112
113         // Add the HTLC along the first hop.
114         let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
115         let (update_add, commitment_signed) = match fail_path_msgs_1 {
116                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
117                         assert_eq!(update_add_htlcs.len(), 1);
118                         assert!(update_fail_htlcs.is_empty());
119                         assert!(update_fulfill_htlcs.is_empty());
120                         assert!(update_fail_malformed_htlcs.is_empty());
121                         assert!(update_fee.is_none());
122                         (update_add_htlcs[0].clone(), commitment_signed.clone())
123                 },
124                 _ => panic!("Unexpected event"),
125         };
126         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
127         commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
128
129         // Attempt to forward the payment and complete the 2nd path's failure.
130         expect_pending_htlcs_forwardable!(&nodes[2]);
131         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_4_id }]);
132         let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
133         assert!(htlc_updates.update_add_htlcs.is_empty());
134         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
135         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
136         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
137         check_added_monitors!(nodes[2], 1);
138         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
139         commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
140         let mut events = nodes[0].node.get_and_clear_pending_events();
141         match events[1] {
142                 Event::PendingHTLCsForwardable { .. } => {},
143                 _ => panic!("Unexpected event")
144         }
145         events.remove(1);
146         expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
147
148         // Rebalance the channel so the second half of the payment can succeed.
149         send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
150
151         // Retry the second half of the payment and make sure it succeeds.
152         route.paths.remove(0);
153         route_params.final_value_msat = 1_000_000;
154         route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
155         nodes[0].router.expect_find_route(route_params, Ok(route));
156         nodes[0].node.process_pending_htlc_forwards();
157         check_added_monitors!(nodes[0], 1);
158         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
159         assert_eq!(events.len(), 1);
160         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
161         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
162 }
163
164 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
165         let chanmon_cfgs = create_chanmon_cfgs(4);
166         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
167         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
168         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
169
170         let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
171         let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
172         let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
173         let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
174
175         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
176         let path = route.paths[0].clone();
177         route.paths.push(path);
178         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
179         route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
180         route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
181         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
182         route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
183         route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
184
185         // Initiate the MPP payment.
186         nodes[0].node.send_payment_with_route(&route, payment_hash,
187                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
188         check_added_monitors!(nodes[0], 2); // one monitor per path
189         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
190         assert_eq!(events.len(), 2);
191
192         // Pass half of the payment along the first path.
193         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
194         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
195
196         if send_partial_mpp {
197                 // Time out the partial MPP
198                 for _ in 0..MPP_TIMEOUT_TICKS {
199                         nodes[3].node.timer_tick_occurred();
200                 }
201
202                 // Failed HTLC from node 3 -> 1
203                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
204                 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
205                 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
206                 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
207                 check_added_monitors!(nodes[3], 1);
208                 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
209
210                 // Failed HTLC from node 1 -> 0
211                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_3_id }]);
212                 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
213                 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
214                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
215                 check_added_monitors!(nodes[1], 1);
216                 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
217
218                 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
219         } else {
220                 // Pass half of the payment along the second path.
221                 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
222                 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
223
224                 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
225                 for _ in 0..MPP_TIMEOUT_TICKS {
226                         nodes[3].node.timer_tick_occurred();
227                 }
228
229                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
230         }
231 }
232
233 #[test]
234 fn mpp_receive_timeout() {
235         do_mpp_receive_timeout(true);
236         do_mpp_receive_timeout(false);
237 }
238
239 #[test]
240 fn test_mpp_keysend() {
241         let mut mpp_keysend_config = test_default_channel_config();
242         mpp_keysend_config.accept_mpp_keysend = true;
243         let chanmon_cfgs = create_chanmon_cfgs(4);
244         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
245         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
246         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
247
248         create_announced_chan_between_nodes(&nodes, 0, 1);
249         create_announced_chan_between_nodes(&nodes, 0, 2);
250         create_announced_chan_between_nodes(&nodes, 1, 3);
251         create_announced_chan_between_nodes(&nodes, 2, 3);
252         let network_graph = nodes[0].network_graph.clone();
253
254         let payer_pubkey = nodes[0].node.get_our_node_id();
255         let payee_pubkey = nodes[3].node.get_our_node_id();
256         let recv_value = 15_000_000;
257         let route_params = RouteParameters {
258                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, true),
259                 final_value_msat: recv_value,
260         };
261         let scorer = test_utils::TestScorer::new();
262         let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
263         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger,
264                 &scorer, &(), &random_seed_bytes).unwrap();
265
266         let payment_preimage = PaymentPreimage([42; 32]);
267         let payment_secret = PaymentSecret(payment_preimage.0);
268         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
269                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_preimage.0)).unwrap();
270         check_added_monitors!(nodes[0], 2);
271
272         let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
273         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
274         assert_eq!(events.len(), 2);
275
276         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
277         pass_along_path(&nodes[0], expected_route[0], recv_value, payment_hash.clone(),
278                 Some(payment_secret), ev.clone(), false, Some(payment_preimage));
279
280         let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
281         pass_along_path(&nodes[0], expected_route[1], recv_value, payment_hash.clone(),
282                 Some(payment_secret), ev.clone(), true, Some(payment_preimage));
283         claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
284 }
285
286 #[test]
287 fn test_reject_mpp_keysend_htlc() {
288         // This test enforces that we reject MPP keysend HTLCs if our config states we don't support
289         // MPP keysend. When receiving a payment, if we don't support MPP keysend we'll reject the
290         // payment if it's keysend and has a payment secret, never reaching our payment validation
291         // logic. To check that we enforce rejecting MPP keysends in our payment logic, here we send
292         // keysend payments without payment secrets, then modify them by adding payment secrets in the
293         // final node in between receiving the HTLCs and actually processing them.
294         let mut reject_mpp_keysend_cfg = test_default_channel_config();
295         reject_mpp_keysend_cfg.accept_mpp_keysend = false;
296
297         let chanmon_cfgs = create_chanmon_cfgs(4);
298         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
299         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(reject_mpp_keysend_cfg)]);
300         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
301         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
302         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
303         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
304         let (update_a, _, chan_4_channel_id, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
305         let chan_4_id = update_a.contents.short_channel_id;
306         let amount = 40_000;
307         let (mut route, payment_hash, payment_preimage, _) = get_route_and_payment_hash!(nodes[0], nodes[3], amount);
308
309         // Pay along nodes[1]
310         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
311         route.paths[0].hops[0].short_channel_id = chan_1_id;
312         route.paths[0].hops[1].short_channel_id = chan_3_id;
313
314         let payment_id_0 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
315         nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_0).unwrap();
316         check_added_monitors!(nodes[0], 1);
317
318         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
319         let update_add_0 = update_0.update_add_htlcs[0].clone();
320         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
321         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
322         expect_pending_htlcs_forwardable!(nodes[1]);
323
324         check_added_monitors!(&nodes[1], 1);
325         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[3].node.get_our_node_id());
326         let update_add_1 = update_1.update_add_htlcs[0].clone();
327         nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
328         commitment_signed_dance!(nodes[3], nodes[1], update_1.commitment_signed, false, true);
329
330         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
331         for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
332                 for f in pending_forwards.iter_mut() {
333                         match f {
334                                 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
335                                         match forward_info.routing {
336                                                 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
337                                                         *payment_data = Some(msgs::FinalOnionHopData {
338                                                                 payment_secret: PaymentSecret([42; 32]),
339                                                                 total_msat: amount * 2,
340                                                         });
341                                                 },
342                                                 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
343                                         }
344                                 },
345                                 _ => {},
346                         }
347                 }
348         }
349         expect_pending_htlcs_forwardable!(nodes[3]);
350
351         // Pay along nodes[2]
352         route.paths[0].hops[0].pubkey = nodes[2].node.get_our_node_id();
353         route.paths[0].hops[0].short_channel_id = chan_2_id;
354         route.paths[0].hops[1].short_channel_id = chan_4_id;
355
356         let payment_id_1 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
357         nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
358         check_added_monitors!(nodes[0], 1);
359
360         let update_2 = get_htlc_update_msgs!(nodes[0], nodes[2].node.get_our_node_id());
361         let update_add_2 = update_2.update_add_htlcs[0].clone();
362         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_2);
363         commitment_signed_dance!(nodes[2], nodes[0], &update_2.commitment_signed, false, true);
364         expect_pending_htlcs_forwardable!(nodes[2]);
365
366         check_added_monitors!(&nodes[2], 1);
367         let update_3 = get_htlc_update_msgs!(nodes[2], nodes[3].node.get_our_node_id());
368         let update_add_3 = update_3.update_add_htlcs[0].clone();
369         nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &update_add_3);
370         commitment_signed_dance!(nodes[3], nodes[2], update_3.commitment_signed, false, true);
371
372         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
373         for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
374                 for f in pending_forwards.iter_mut() {
375                         match f {
376                                 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
377                                         match forward_info.routing {
378                                                 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
379                                                         *payment_data = Some(msgs::FinalOnionHopData {
380                                                                 payment_secret: PaymentSecret([42; 32]),
381                                                                 total_msat: amount * 2,
382                                                         });
383                                                 },
384                                                 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
385                                         }
386                                 },
387                                 _ => {},
388                         }
389                 }
390         }
391         expect_pending_htlcs_forwardable!(nodes[3]);
392         check_added_monitors!(nodes[3], 1);
393
394         // Fail back along nodes[2]
395         let update_fail_0 = get_htlc_update_msgs!(&nodes[3], &nodes[2].node.get_our_node_id());
396         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &update_fail_0.update_fail_htlcs[0]);
397         commitment_signed_dance!(nodes[2], nodes[3], update_fail_0.commitment_signed, false);
398         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_4_channel_id }]);
399         check_added_monitors!(nodes[2], 1);
400
401         let update_fail_1 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
402         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_1.update_fail_htlcs[0]);
403         commitment_signed_dance!(nodes[0], nodes[2], update_fail_1.commitment_signed, false);
404
405         expect_payment_failed_conditions(&nodes[0], payment_hash, true, PaymentFailedConditions::new());
406         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
407 }
408
409
410 #[test]
411 fn no_pending_leak_on_initial_send_failure() {
412         // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
413         // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
414         // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
415         // pending payment forever and never time it out.
416         // Here we test exactly that - retrying a payment when a peer was disconnected on the first
417         // try, and then check that no pending payment is being tracked.
418         let chanmon_cfgs = create_chanmon_cfgs(2);
419         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
420         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
421         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
422
423         create_announced_chan_between_nodes(&nodes, 0, 1);
424
425         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
426
427         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
428         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
429
430         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
431                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
432                 ), true, APIError::ChannelUnavailable { ref err },
433                 assert_eq!(err, "Peer for first hop currently disconnected"));
434
435         assert!(!nodes[0].node.has_pending_payments());
436 }
437
438 fn do_retry_with_no_persist(confirm_before_reload: bool) {
439         // If we send a pending payment and `send_payment` returns success, we should always either
440         // return a payment failure event or a payment success event, and on failure the payment should
441         // be retryable.
442         //
443         // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
444         // always persisted asynchronously), the ChannelManager has to reload some payment data from
445         // ChannelMonitor(s) in some cases. This tests that reloading.
446         //
447         // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
448         // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
449         // which has separate codepaths for "commitment transaction already confirmed" and not.
450         let chanmon_cfgs = create_chanmon_cfgs(3);
451         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
452         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
453         let persister: test_utils::TestPersister;
454         let new_chain_monitor: test_utils::TestChainMonitor;
455         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>;
456         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
457
458         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
459         let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
460
461         // Serialize the ChannelManager prior to sending payments
462         let nodes_0_serialized = nodes[0].node.encode();
463
464         // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
465         // out and retry.
466         let amt_msat = 1_000_000;
467         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
468         let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
469         let route_params = RouteParameters {
470                 payment_params: route.payment_params.clone().unwrap(),
471                 final_value_msat: amt_msat,
472         };
473         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
474                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
475         check_added_monitors!(nodes[0], 1);
476
477         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
478         assert_eq!(events.len(), 1);
479         let payment_event = SendEvent::from_event(events.pop().unwrap());
480         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
481
482         // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
483         // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
484         // which would prevent retry.
485         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
486         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
487
488         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
489         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
490         // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
491         let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
492
493         reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
494
495         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
496         if confirm_before_reload {
497                 mine_transaction(&nodes[0], &as_commitment_tx);
498                 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
499         }
500
501         // The ChannelMonitor should always be the latest version, as we're required to persist it
502         // during the `commitment_signed_dance!()`.
503         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
504         reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
505
506         // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
507         // force-close the channel.
508         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
509         assert!(nodes[0].node.list_channels().is_empty());
510         assert!(nodes[0].node.has_pending_payments());
511         nodes[0].node.timer_tick_occurred();
512         if !confirm_before_reload {
513                 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
514                 assert_eq!(as_broadcasted_txn.len(), 1);
515                 assert_eq!(as_broadcasted_txn[0].txid(), as_commitment_tx.txid());
516         } else {
517                 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
518         }
519         check_added_monitors!(nodes[0], 1);
520
521         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
522         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
523                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
524         }, true).unwrap();
525         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
526
527         // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
528         // error, as the channel has hit the chain.
529         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
530                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
531         }, false).unwrap();
532         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
533         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
534         let as_err = nodes[0].node.get_and_clear_pending_msg_events();
535         assert_eq!(as_err.len(), 1);
536         match as_err[0] {
537                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
538                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
539                         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
540                         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())) });
541                         check_added_monitors!(nodes[1], 1);
542                         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
543                 },
544                 _ => panic!("Unexpected event"),
545         }
546         check_closed_broadcast!(nodes[1], false);
547
548         // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
549         // we close in a moment.
550         nodes[2].node.claim_funds(payment_preimage_1);
551         check_added_monitors!(nodes[2], 1);
552         expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
553
554         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
555         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
556         check_added_monitors!(nodes[1], 1);
557         commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
558         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
559
560         if confirm_before_reload {
561                 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
562                 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
563         }
564
565         // Create a new channel on which to retry the payment before we fail the payment via the
566         // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
567         // connecting several blocks while creating the channel (implying time has passed).
568         create_announced_chan_between_nodes(&nodes, 0, 1);
569         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
570
571         mine_transaction(&nodes[1], &as_commitment_tx);
572         let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
573         assert_eq!(bs_htlc_claim_txn.len(), 1);
574         check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
575
576         if !confirm_before_reload {
577                 mine_transaction(&nodes[0], &as_commitment_tx);
578         }
579         mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
580         expect_payment_sent!(nodes[0], payment_preimage_1);
581         connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
582         let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
583                 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
584                 assert_eq!(txn.len(), 2);
585                 (txn.remove(0), txn.remove(0))
586         };
587         check_spends!(first_htlc_timeout_tx, as_commitment_tx);
588         check_spends!(second_htlc_timeout_tx, as_commitment_tx);
589         if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
590                 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
591         } else {
592                 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
593         }
594         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
595         expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
596
597         // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
598         // reloaded) via a route over the new channel, which work without issue and eventually be
599         // received and claimed at the recipient just like any other payment.
600         let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
601
602         // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
603         // and not the original fee. We also update node[1]'s relevant config as
604         // do_claim_payment_along_route expects us to never overpay.
605         {
606                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
607                 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
608                         .unwrap().lock().unwrap();
609                 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
610                 let mut new_config = channel.context.config();
611                 new_config.forwarding_fee_base_msat += 100_000;
612                 channel.context.update_config(&new_config);
613                 new_route.paths[0].hops[0].fee_msat += 100_000;
614         }
615
616         // Force expiration of the channel's previous config.
617         for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
618                 nodes[1].node.timer_tick_occurred();
619         }
620
621         assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
622                 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
623         nodes[0].node.send_payment_with_route(&new_route, payment_hash,
624                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
625         check_added_monitors!(nodes[0], 1);
626         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
627         assert_eq!(events.len(), 1);
628         pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
629         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
630         expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
631 }
632
633 #[test]
634 fn retry_with_no_persist() {
635         do_retry_with_no_persist(true);
636         do_retry_with_no_persist(false);
637 }
638
639 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
640         // Test that an off-chain completed payment is not retryable on restart. This was previously
641         // broken for dust payments, but we test for both dust and non-dust payments.
642         //
643         // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
644         // output at all.
645         let chanmon_cfgs = create_chanmon_cfgs(3);
646         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
647
648         let mut manually_accept_config = test_default_channel_config();
649         manually_accept_config.manually_accept_inbound_channels = true;
650
651         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
652
653         let first_persister: test_utils::TestPersister;
654         let first_new_chain_monitor: test_utils::TestChainMonitor;
655         let first_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>;
656         let second_persister: test_utils::TestPersister;
657         let second_new_chain_monitor: test_utils::TestChainMonitor;
658         let second_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>;
659         let third_persister: test_utils::TestPersister;
660         let third_new_chain_monitor: test_utils::TestChainMonitor;
661         let third_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>;
662
663         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
664
665         // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
666         let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
667         confirm_transaction(&nodes[0], &funding_tx);
668         confirm_transaction(&nodes[1], &funding_tx);
669         // Ignore the announcement_signatures messages
670         nodes[0].node.get_and_clear_pending_msg_events();
671         nodes[1].node.get_and_clear_pending_msg_events();
672         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
673
674         // Serialize the ChannelManager prior to sending payments
675         let mut nodes_0_serialized = nodes[0].node.encode();
676
677         let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
678         let (payment_preimage, payment_hash, payment_secret, payment_id) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], if use_dust { 1_000 } else { 1_000_000 });
679
680         // The ChannelMonitor should always be the latest version, as we're required to persist it
681         // during the `commitment_signed_dance!()`.
682         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
683
684         reload_node!(nodes[0], test_default_channel_config(), nodes_0_serialized, &[&chan_0_monitor_serialized], first_persister, first_new_chain_monitor, first_nodes_0_deserialized);
685         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
686
687         // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
688         // force-close the channel.
689         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
690         nodes[0].node.timer_tick_occurred();
691         assert!(nodes[0].node.list_channels().is_empty());
692         assert!(nodes[0].node.has_pending_payments());
693         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
694         check_added_monitors!(nodes[0], 1);
695
696         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
697                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
698         }, true).unwrap();
699         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
700
701         // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
702         // error, as the channel has hit the chain.
703         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
704                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
705         }, false).unwrap();
706         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
707         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
708         let as_err = nodes[0].node.get_and_clear_pending_msg_events();
709         assert_eq!(as_err.len(), 1);
710         let bs_commitment_tx;
711         match as_err[0] {
712                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
713                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
714                         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
715                         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())) });
716                         check_added_monitors!(nodes[1], 1);
717                         bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
718                 },
719                 _ => panic!("Unexpected event"),
720         }
721         check_closed_broadcast!(nodes[1], false);
722
723         // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
724         // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
725         // incoming HTLCs with the same payment hash later.
726         nodes[2].node.fail_htlc_backwards(&payment_hash);
727         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
728         check_added_monitors!(nodes[2], 1);
729
730         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
731         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
732         commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
733         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
734                 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
735
736         // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
737         // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
738         // after the commitment transaction, so always connect the commitment transaction.
739         mine_transaction(&nodes[0], &bs_commitment_tx[0]);
740         mine_transaction(&nodes[1], &bs_commitment_tx[0]);
741         if !use_dust {
742                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
743                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
744                 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
745                 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
746                 assert_eq!(as_htlc_timeout.len(), 1);
747
748                 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
749                 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
750                 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
751                 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
752         }
753
754         // Create a new channel on which to retry the payment before we fail the payment via the
755         // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
756         // connecting several blocks while creating the channel (implying time has passed).
757         // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
758         let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
759         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
760
761         // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
762         // confirming, we will fail as it's considered still-pending...
763         let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
764         match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
765                 Err(PaymentSendFailure::DuplicatePayment) => {},
766                 _ => panic!("Unexpected error")
767         }
768         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
769
770         // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
771         // again. We serialize the node first as we'll then test retrying the HTLC after a restart
772         // (which should also still work).
773         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
774         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
775         expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
776
777         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
778         let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
779         nodes_0_serialized = nodes[0].node.encode();
780
781         // After the payment failed, we're free to send it again.
782         assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
783                 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
784         assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
785
786         reload_node!(nodes[0], test_default_channel_config(), nodes_0_serialized, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], second_persister, second_new_chain_monitor, second_nodes_0_deserialized);
787         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
788
789         nodes[0].node.test_process_background_events();
790         check_added_monitors(&nodes[0], 1);
791
792         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
793         reconnect_args.send_channel_ready = (true, true);
794         reconnect_nodes(reconnect_args);
795
796         // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
797         // the payment is not (spuriously) listed as still pending.
798         assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
799                 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
800         check_added_monitors!(nodes[0], 1);
801         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
802         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
803
804         match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
805                 Err(PaymentSendFailure::DuplicatePayment) => {},
806                 _ => panic!("Unexpected error")
807         }
808         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
809
810         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
811         let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
812         nodes_0_serialized = nodes[0].node.encode();
813
814         // Check that after reload we can send the payment again (though we shouldn't, since it was
815         // claimed previously).
816         reload_node!(nodes[0], test_default_channel_config(), nodes_0_serialized, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], third_persister, third_new_chain_monitor, third_nodes_0_deserialized);
817         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
818
819         nodes[0].node.test_process_background_events();
820         check_added_monitors(&nodes[0], 1);
821
822         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
823
824         match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
825                 Err(PaymentSendFailure::DuplicatePayment) => {},
826                 _ => panic!("Unexpected error")
827         }
828         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
829 }
830
831 #[test]
832 fn test_completed_payment_not_retryable_on_reload() {
833         do_test_completed_payment_not_retryable_on_reload(true);
834         do_test_completed_payment_not_retryable_on_reload(false);
835 }
836
837
838 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
839         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
840         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
841         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
842         // the ChannelMonitor tells it to.
843         //
844         // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
845         // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
846         // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
847         let chanmon_cfgs = create_chanmon_cfgs(2);
848         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
849         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
850         let persister: test_utils::TestPersister;
851         let new_chain_monitor: test_utils::TestChainMonitor;
852         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>;
853         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
854
855         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
856
857         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
858         // nodes[0].
859         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
860         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
861         check_closed_broadcast!(nodes[0], true);
862         check_added_monitors!(nodes[0], 1);
863         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
864
865         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
866         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
867
868         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
869         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
870         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
871         assert_eq!(node_txn.len(), 3);
872         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
873         check_spends!(node_txn[1], funding_tx);
874         check_spends!(node_txn[2], node_txn[1]);
875         let timeout_txn = vec![node_txn[2].clone()];
876
877         nodes[1].node.claim_funds(payment_preimage);
878         check_added_monitors!(nodes[1], 1);
879         expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
880
881         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[1].clone()]));
882         check_closed_broadcast!(nodes[1], true);
883         check_added_monitors!(nodes[1], 1);
884         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
885         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
886         assert_eq!(claim_txn.len(), 1);
887         check_spends!(claim_txn[0], node_txn[1]);
888
889         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[1].clone()]));
890
891         if confirm_commitment_tx {
892                 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
893         }
894
895         let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] });
896
897         if payment_timeout {
898                 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
899                 connect_block(&nodes[0], &claim_block);
900                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
901         }
902
903         // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
904         // returning InProgress. This should cause the claim event to never make its way to the
905         // ChannelManager.
906         chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
907         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
908
909         if payment_timeout {
910                 connect_blocks(&nodes[0], 1);
911         } else {
912                 connect_block(&nodes[0], &claim_block);
913         }
914
915         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
916         let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
917                 .get_mut(&funding_txo).unwrap().drain().collect();
918         // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
919         // If we're testing connection idempotency we may get substantially more.
920         assert!(mon_updates.len() >= 1);
921         assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
922         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
923
924         // If we persist the ChannelManager here, we should get the PaymentSent event after
925         // deserialization.
926         let mut chan_manager_serialized = Vec::new();
927         if !persist_manager_post_event {
928                 chan_manager_serialized = nodes[0].node.encode();
929         }
930
931         // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
932         // payment sent event.
933         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
934         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
935         for update in mon_updates {
936                 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
937         }
938         if payment_timeout {
939                 expect_payment_failed!(nodes[0], payment_hash, false);
940         } else {
941                 expect_payment_sent!(nodes[0], payment_preimage);
942         }
943
944         // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
945         // twice.
946         if persist_manager_post_event {
947                 chan_manager_serialized = nodes[0].node.encode();
948         }
949
950         // Now reload nodes[0]...
951         reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
952
953         if persist_manager_post_event {
954                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
955         } else if payment_timeout {
956                 expect_payment_failed!(nodes[0], payment_hash, false);
957         } else {
958                 expect_payment_sent!(nodes[0], payment_preimage);
959         }
960
961         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
962         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
963         // payment events should kick in, leaving us with no pending events here.
964         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
965         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
966         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
967         check_added_monitors(&nodes[0], 1);
968 }
969
970 #[test]
971 fn test_dup_htlc_onchain_fails_on_reload() {
972         do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
973         do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
974         do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
975         do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
976         do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
977         do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
978 }
979
980 #[test]
981 fn test_fulfill_restart_failure() {
982         // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
983         // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
984         // again, or fail it, giving us free money.
985         //
986         // Of course probably they won't fail it and give us free money, but because we have code to
987         // handle it, we should test the logic for it anyway. We do that here.
988         let chanmon_cfgs = create_chanmon_cfgs(2);
989         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
990         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
991         let persister: test_utils::TestPersister;
992         let new_chain_monitor: test_utils::TestChainMonitor;
993         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>;
994         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
995
996         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
997         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
998
999         // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
1000         // pre-fulfill, which we do by serializing it here.
1001         let chan_manager_serialized = nodes[1].node.encode();
1002         let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1003
1004         nodes[1].node.claim_funds(payment_preimage);
1005         check_added_monitors!(nodes[1], 1);
1006         expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1007
1008         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1009         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1010         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
1011
1012         // Now reload nodes[1]...
1013         reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1014
1015         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1016         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1017
1018         nodes[1].node.fail_htlc_backwards(&payment_hash);
1019         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1020         check_added_monitors!(nodes[1], 1);
1021         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1022         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1023         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1024         // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1025         // it had already considered the payment fulfilled, and now they just got free money.
1026         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1027 }
1028
1029 #[test]
1030 fn get_ldk_payment_preimage() {
1031         // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1032         let chanmon_cfgs = create_chanmon_cfgs(2);
1033         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1034         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1035         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1036         create_announced_chan_between_nodes(&nodes, 0, 1);
1037
1038         let amt_msat = 60_000;
1039         let expiry_secs = 60 * 60;
1040         let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1041
1042         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1043                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
1044         let scorer = test_utils::TestScorer::new();
1045         let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1046         let random_seed_bytes = keys_manager.get_secure_random_bytes();
1047         let route = get_route(
1048                 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
1049                 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
1050                 amt_msat, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
1051         nodes[0].node.send_payment_with_route(&route, payment_hash,
1052                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1053         check_added_monitors!(nodes[0], 1);
1054
1055         // Make sure to use `get_payment_preimage`
1056         let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1057         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1058         assert_eq!(events.len(), 1);
1059         pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1060         claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1061 }
1062
1063 #[test]
1064 fn sent_probe_is_probe_of_sending_node() {
1065         let chanmon_cfgs = create_chanmon_cfgs(3);
1066         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1067         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1068         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1069
1070         create_announced_chan_between_nodes(&nodes, 0, 1);
1071         create_announced_chan_between_nodes(&nodes, 1, 2);
1072
1073         // First check we refuse to build a single-hop probe
1074         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1075         assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1076
1077         // Then build an actual two-hop probing path
1078         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1079
1080         match nodes[0].node.send_probe(route.paths[0].clone()) {
1081                 Ok((payment_hash, payment_id)) => {
1082                         assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1083                         assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1084                         assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1085                 },
1086                 _ => panic!(),
1087         }
1088
1089         get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1090         check_added_monitors!(nodes[0], 1);
1091 }
1092
1093 #[test]
1094 fn successful_probe_yields_event() {
1095         let chanmon_cfgs = create_chanmon_cfgs(3);
1096         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1097         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1098         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1099
1100         create_announced_chan_between_nodes(&nodes, 0, 1);
1101         create_announced_chan_between_nodes(&nodes, 1, 2);
1102
1103         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1104
1105         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1106
1107         // node[0] -- update_add_htlcs -> node[1]
1108         check_added_monitors!(nodes[0], 1);
1109         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1110         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1111         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1112         check_added_monitors!(nodes[1], 0);
1113         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1114         expect_pending_htlcs_forwardable!(nodes[1]);
1115
1116         // node[1] -- update_add_htlcs -> node[2]
1117         check_added_monitors!(nodes[1], 1);
1118         let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1119         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1120         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1121         check_added_monitors!(nodes[2], 0);
1122         commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
1123
1124         // node[1] <- update_fail_htlcs -- node[2]
1125         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1126         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1127         check_added_monitors!(nodes[1], 0);
1128         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1129
1130         // node[0] <- update_fail_htlcs -- node[1]
1131         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1132         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1133         check_added_monitors!(nodes[0], 0);
1134         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1135
1136         let mut events = nodes[0].node.get_and_clear_pending_events();
1137         assert_eq!(events.len(), 1);
1138         match events.drain(..).next().unwrap() {
1139                 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1140                         assert_eq!(payment_id, ev_pid);
1141                         assert_eq!(payment_hash, ev_ph);
1142                 },
1143                 _ => panic!(),
1144         };
1145         assert!(!nodes[0].node.has_pending_payments());
1146 }
1147
1148 #[test]
1149 fn failed_probe_yields_event() {
1150         let chanmon_cfgs = create_chanmon_cfgs(3);
1151         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1152         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1153         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1154
1155         create_announced_chan_between_nodes(&nodes, 0, 1);
1156         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1157
1158         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1159
1160         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000);
1161
1162         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1163
1164         // node[0] -- update_add_htlcs -> node[1]
1165         check_added_monitors!(nodes[0], 1);
1166         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1167         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1168         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1169         check_added_monitors!(nodes[1], 0);
1170         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1171         expect_pending_htlcs_forwardable!(nodes[1]);
1172
1173         // node[0] <- update_fail_htlcs -- node[1]
1174         check_added_monitors!(nodes[1], 1);
1175         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1176         // Skip the PendingHTLCsForwardable event
1177         let _events = nodes[1].node.get_and_clear_pending_events();
1178         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1179         check_added_monitors!(nodes[0], 0);
1180         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1181
1182         let mut events = nodes[0].node.get_and_clear_pending_events();
1183         assert_eq!(events.len(), 1);
1184         match events.drain(..).next().unwrap() {
1185                 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1186                         assert_eq!(payment_id, ev_pid);
1187                         assert_eq!(payment_hash, ev_ph);
1188                 },
1189                 _ => panic!(),
1190         };
1191         assert!(!nodes[0].node.has_pending_payments());
1192 }
1193
1194 #[test]
1195 fn onchain_failed_probe_yields_event() {
1196         // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1197         // event.
1198         let chanmon_cfgs = create_chanmon_cfgs(3);
1199         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1200         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1201         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1202
1203         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1204         create_announced_chan_between_nodes(&nodes, 1, 2);
1205
1206         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1207
1208         // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1209         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000);
1210         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1211
1212         // node[0] -- update_add_htlcs -> node[1]
1213         check_added_monitors!(nodes[0], 1);
1214         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1215         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1216         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1217         check_added_monitors!(nodes[1], 0);
1218         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1219         expect_pending_htlcs_forwardable!(nodes[1]);
1220
1221         check_added_monitors!(nodes[1], 1);
1222         let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1223
1224         // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1225         // Node A, which after 6 confirmations should result in a probe failure event.
1226         let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1227         confirm_transaction(&nodes[0], &bs_txn[0]);
1228         check_closed_broadcast!(&nodes[0], true);
1229         check_added_monitors!(nodes[0], 1);
1230
1231         let mut events = nodes[0].node.get_and_clear_pending_events();
1232         assert_eq!(events.len(), 2);
1233         let mut found_probe_failed = false;
1234         for event in events.drain(..) {
1235                 match event {
1236                         Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1237                                 assert_eq!(payment_id, ev_pid);
1238                                 assert_eq!(payment_hash, ev_ph);
1239                                 found_probe_failed = true;
1240                         },
1241                         Event::ChannelClosed { .. } => {},
1242                         _ => panic!(),
1243                 }
1244         }
1245         assert!(found_probe_failed);
1246         assert!(!nodes[0].node.has_pending_payments());
1247 }
1248
1249 #[test]
1250 fn claimed_send_payment_idempotent() {
1251         // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1252         let chanmon_cfgs = create_chanmon_cfgs(2);
1253         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1254         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1255         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1256
1257         create_announced_chan_between_nodes(&nodes, 0, 1).2;
1258
1259         let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1260         let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1261
1262         macro_rules! check_send_rejected {
1263                 () => {
1264                         // If we try to resend a new payment with a different payment_hash but with the same
1265                         // payment_id, it should be rejected.
1266                         let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1267                                 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1268                         match send_result {
1269                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1270                                 _ => panic!("Unexpected send result: {:?}", send_result),
1271                         }
1272
1273                         // Further, if we try to send a spontaneous payment with the same payment_id it should
1274                         // also be rejected.
1275                         let send_result = nodes[0].node.send_spontaneous_payment(
1276                                 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1277                         match send_result {
1278                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1279                                 _ => panic!("Unexpected send result: {:?}", send_result),
1280                         }
1281                 }
1282         }
1283
1284         check_send_rejected!();
1285
1286         // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1287         // not been seen by the user. At this point, from the user perspective nothing has changed, so
1288         // we must remain just as idempotent as we were before.
1289         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1290
1291         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1292                 nodes[0].node.timer_tick_occurred();
1293         }
1294
1295         check_send_rejected!();
1296
1297         // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1298         // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1299         // the payment complete. However, they could have called `send_payment` while the event was
1300         // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1301         // after the event is handled a duplicate payment should sitll be rejected.
1302         expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1303         check_send_rejected!();
1304
1305         // If relatively little time has passed, a duplicate payment should still fail.
1306         nodes[0].node.timer_tick_occurred();
1307         check_send_rejected!();
1308
1309         // However, after some time has passed (at least more than the one timer tick above), a
1310         // duplicate payment should go through, as ChannelManager should no longer have any remaining
1311         // references to the old payment data.
1312         for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1313                 nodes[0].node.timer_tick_occurred();
1314         }
1315
1316         nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1317                 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1318         check_added_monitors!(nodes[0], 1);
1319         pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1320         claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1321 }
1322
1323 #[test]
1324 fn abandoned_send_payment_idempotent() {
1325         // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1326         // abandon_payment.
1327         let chanmon_cfgs = create_chanmon_cfgs(2);
1328         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1329         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1330         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1331
1332         create_announced_chan_between_nodes(&nodes, 0, 1).2;
1333
1334         let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1335         let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1336
1337         macro_rules! check_send_rejected {
1338                 () => {
1339                         // If we try to resend a new payment with a different payment_hash but with the same
1340                         // payment_id, it should be rejected.
1341                         let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1342                                 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1343                         match send_result {
1344                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1345                                 _ => panic!("Unexpected send result: {:?}", send_result),
1346                         }
1347
1348                         // Further, if we try to send a spontaneous payment with the same payment_id it should
1349                         // also be rejected.
1350                         let send_result = nodes[0].node.send_spontaneous_payment(
1351                                 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1352                         match send_result {
1353                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1354                                 _ => panic!("Unexpected send result: {:?}", send_result),
1355                         }
1356                 }
1357         }
1358
1359         check_send_rejected!();
1360
1361         nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1362         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1363
1364         // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1365         // PaymentId.
1366         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1367                 nodes[0].node.timer_tick_occurred();
1368         }
1369         check_send_rejected!();
1370
1371         pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1372
1373         // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1374         // failed payment back.
1375         nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1376                 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1377         check_added_monitors!(nodes[0], 1);
1378         pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1379         claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1380 }
1381
1382 #[derive(PartialEq)]
1383 enum InterceptTest {
1384         Forward,
1385         Fail,
1386         Timeout,
1387 }
1388
1389 #[test]
1390 fn test_trivial_inflight_htlc_tracking(){
1391         // In this test, we test three scenarios:
1392         // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1393         // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1394         // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1395         let chanmon_cfgs = create_chanmon_cfgs(3);
1396         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1397         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1398         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1399
1400         let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1401         let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1402
1403         // Send and claim the payment. Inflight HTLCs should be empty.
1404         let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1405         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1406         {
1407                 let mut node_0_per_peer_lock;
1408                 let mut node_0_peer_state_lock;
1409                 let channel_1 =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1410
1411                 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1412                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1413                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1414                         channel_1.context.get_short_channel_id().unwrap()
1415                 );
1416                 assert_eq!(chan_1_used_liquidity, None);
1417         }
1418         {
1419                 let mut node_1_per_peer_lock;
1420                 let mut node_1_peer_state_lock;
1421                 let channel_2 =  get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1422
1423                 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1424                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1425                         &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1426                         channel_2.context.get_short_channel_id().unwrap()
1427                 );
1428
1429                 assert_eq!(chan_2_used_liquidity, None);
1430         }
1431         let pending_payments = nodes[0].node.list_recent_payments();
1432         assert_eq!(pending_payments.len(), 1);
1433         assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1434
1435         // Remove fulfilled payment
1436         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1437                 nodes[0].node.timer_tick_occurred();
1438         }
1439
1440         // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1441         let (payment_preimage, payment_hash,  _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1442         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1443         {
1444                 let mut node_0_per_peer_lock;
1445                 let mut node_0_peer_state_lock;
1446                 let channel_1 =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1447
1448                 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1449                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1450                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1451                         channel_1.context.get_short_channel_id().unwrap()
1452                 );
1453                 // First hop accounts for expected 1000 msat fee
1454                 assert_eq!(chan_1_used_liquidity, Some(501000));
1455         }
1456         {
1457                 let mut node_1_per_peer_lock;
1458                 let mut node_1_peer_state_lock;
1459                 let channel_2 =  get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1460
1461                 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1462                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1463                         &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1464                         channel_2.context.get_short_channel_id().unwrap()
1465                 );
1466
1467                 assert_eq!(chan_2_used_liquidity, Some(500000));
1468         }
1469         let pending_payments = nodes[0].node.list_recent_payments();
1470         assert_eq!(pending_payments.len(), 1);
1471         assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1472
1473         // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1474         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1475
1476         // Remove fulfilled payment
1477         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1478                 nodes[0].node.timer_tick_occurred();
1479         }
1480
1481         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1482         {
1483                 let mut node_0_per_peer_lock;
1484                 let mut node_0_peer_state_lock;
1485                 let channel_1 =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1486
1487                 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1488                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1489                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1490                         channel_1.context.get_short_channel_id().unwrap()
1491                 );
1492                 assert_eq!(chan_1_used_liquidity, None);
1493         }
1494         {
1495                 let mut node_1_per_peer_lock;
1496                 let mut node_1_peer_state_lock;
1497                 let channel_2 =  get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1498
1499                 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1500                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1501                         &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1502                         channel_2.context.get_short_channel_id().unwrap()
1503                 );
1504                 assert_eq!(chan_2_used_liquidity, None);
1505         }
1506
1507         let pending_payments = nodes[0].node.list_recent_payments();
1508         assert_eq!(pending_payments.len(), 0);
1509 }
1510
1511 #[test]
1512 fn test_holding_cell_inflight_htlcs() {
1513         let chanmon_cfgs = create_chanmon_cfgs(2);
1514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1516         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1517         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1518
1519         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1520         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1521
1522         // Queue up two payments - one will be delivered right away, one immediately goes into the
1523         // holding cell as nodes[0] is AwaitingRAA.
1524         {
1525                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1526                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1527                 check_added_monitors!(nodes[0], 1);
1528                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1529                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1530                 check_added_monitors!(nodes[0], 0);
1531         }
1532
1533         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1534
1535         {
1536                 let mut node_0_per_peer_lock;
1537                 let mut node_0_peer_state_lock;
1538                 let channel =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1539
1540                 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1541                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1542                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1543                         channel.context.get_short_channel_id().unwrap()
1544                 );
1545
1546                 assert_eq!(used_liquidity, Some(2000000));
1547         }
1548
1549         // Clear pending events so test doesn't throw a "Had excess message on node..." error
1550         nodes[0].node.get_and_clear_pending_msg_events();
1551 }
1552
1553 #[test]
1554 fn intercepted_payment() {
1555         // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1556         // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1557         // payment or (b) fail the payment.
1558         do_test_intercepted_payment(InterceptTest::Forward);
1559         do_test_intercepted_payment(InterceptTest::Fail);
1560         // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1561         do_test_intercepted_payment(InterceptTest::Timeout);
1562 }
1563
1564 fn do_test_intercepted_payment(test: InterceptTest) {
1565         let chanmon_cfgs = create_chanmon_cfgs(3);
1566         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1567
1568         let mut zero_conf_chan_config = test_default_channel_config();
1569         zero_conf_chan_config.manually_accept_inbound_channels = true;
1570         let mut intercept_forwards_config = test_default_channel_config();
1571         intercept_forwards_config.accept_intercept_htlcs = true;
1572         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1573
1574         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1575         let scorer = test_utils::TestScorer::new();
1576         let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1577
1578         let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1579
1580         let amt_msat = 100_000;
1581         let intercept_scid = nodes[1].node.get_intercept_scid();
1582         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1583                 .with_route_hints(vec![
1584                         RouteHint(vec![RouteHintHop {
1585                                 src_node_id: nodes[1].node.get_our_node_id(),
1586                                 short_channel_id: intercept_scid,
1587                                 fees: RoutingFees {
1588                                         base_msat: 1000,
1589                                         proportional_millionths: 0,
1590                                 },
1591                                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1592                                 htlc_minimum_msat: None,
1593                                 htlc_maximum_msat: None,
1594                         }])
1595                 ]).unwrap()
1596                 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1597         let route_params = RouteParameters {
1598                 payment_params,
1599                 final_value_msat: amt_msat,
1600         };
1601         let route = get_route(
1602                 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1603                 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1604                 nodes[0].logger, &scorer, &(), &random_seed_bytes,
1605         ).unwrap();
1606
1607         let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1608         nodes[0].node.send_payment_with_route(&route, payment_hash,
1609                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1610         let payment_event = {
1611                 {
1612                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1613                         assert_eq!(added_monitors.len(), 1);
1614                         added_monitors.clear();
1615                 }
1616                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1617                 assert_eq!(events.len(), 1);
1618                 SendEvent::from_event(events.remove(0))
1619         };
1620         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1621         commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1622
1623         // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1624         let events = nodes[1].node.get_and_clear_pending_events();
1625         assert_eq!(events.len(), 1);
1626         let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1627                 crate::events::Event::HTLCIntercepted {
1628                         intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1629                 } => {
1630                         assert_eq!(pmt_hash, payment_hash);
1631                         assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1632                         assert_eq!(short_channel_id, intercept_scid);
1633                         (intercept_id, expected_outbound_amount_msat)
1634                 },
1635                 _ => panic!()
1636         };
1637
1638         // Check for unknown channel id error.
1639         let unknown_chan_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &[42; 32], nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1640         assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable  {
1641                 err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1642                         log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1643
1644         if test == InterceptTest::Fail {
1645                 // Ensure we can fail the intercepted payment back.
1646                 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1647                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1648                 nodes[1].node.process_pending_htlc_forwards();
1649                 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1650                 check_added_monitors!(&nodes[1], 1);
1651                 assert!(update_fail.update_fail_htlcs.len() == 1);
1652                 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1653                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1654                 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1655
1656                 // Ensure the payment fails with the expected error.
1657                 let fail_conditions = PaymentFailedConditions::new()
1658                         .blamed_scid(intercept_scid)
1659                         .blamed_chan_closed(true)
1660                         .expected_htlc_error_data(0x4000 | 10, &[]);
1661                 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1662         } else if test == InterceptTest::Forward {
1663                 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1664                 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1665                 let unusable_chan_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &temp_chan_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1666                 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1667                         err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1668                                 log_bytes!(temp_chan_id), nodes[2].node.get_our_node_id()) });
1669                 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1670
1671                 // Open the just-in-time channel so the payment can then be forwarded.
1672                 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1673
1674                 // Finally, forward the intercepted payment through and claim it.
1675                 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1676                 expect_pending_htlcs_forwardable!(nodes[1]);
1677
1678                 let payment_event = {
1679                         {
1680                                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1681                                 assert_eq!(added_monitors.len(), 1);
1682                                 added_monitors.clear();
1683                         }
1684                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1685                         assert_eq!(events.len(), 1);
1686                         SendEvent::from_event(events.remove(0))
1687                 };
1688                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1689                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1690                 expect_pending_htlcs_forwardable!(nodes[2]);
1691
1692                 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1693                 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1694                 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1695                 let events = nodes[0].node.get_and_clear_pending_events();
1696                 assert_eq!(events.len(), 2);
1697                 match events[0] {
1698                         Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1699                                 assert_eq!(payment_preimage, *ev_preimage);
1700                                 assert_eq!(payment_hash, *ev_hash);
1701                                 assert_eq!(fee_paid_msat, &Some(1000));
1702                         },
1703                         _ => panic!("Unexpected event")
1704                 }
1705                 match events[1] {
1706                         Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1707                                 assert_eq!(hash, Some(payment_hash));
1708                         },
1709                         _ => panic!("Unexpected event")
1710                 }
1711         } else if test == InterceptTest::Timeout {
1712                 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
1713                 connect_block(&nodes[0], &block);
1714                 connect_block(&nodes[1], &block);
1715                 for _ in 0..TEST_FINAL_CLTV {
1716                         block.header.prev_blockhash = block.block_hash();
1717                         connect_block(&nodes[0], &block);
1718                         connect_block(&nodes[1], &block);
1719                 }
1720                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1721                 check_added_monitors!(nodes[1], 1);
1722                 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1723                 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1724                 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1725                 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1726                 assert!(htlc_timeout_updates.update_fee.is_none());
1727
1728                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1729                 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1730                 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1731
1732                 // Check for unknown intercept id error.
1733                 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1734                 let unknown_intercept_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1735                 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1736                 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1737                 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1738         }
1739 }
1740
1741 #[test]
1742 fn accept_underpaying_htlcs_config() {
1743         do_accept_underpaying_htlcs_config(1);
1744         do_accept_underpaying_htlcs_config(2);
1745         do_accept_underpaying_htlcs_config(3);
1746 }
1747
1748 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
1749         let chanmon_cfgs = create_chanmon_cfgs(3);
1750         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1751         let mut intercept_forwards_config = test_default_channel_config();
1752         intercept_forwards_config.accept_intercept_htlcs = true;
1753         let mut underpay_config = test_default_channel_config();
1754         underpay_config.channel_config.accept_underpaying_htlcs = true;
1755         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
1756         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1757
1758         let mut chan_ids = Vec::new();
1759         for _ in 0..num_mpp_parts {
1760                 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000, 0);
1761                 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 2_000_000, 0).0.channel_id;
1762                 chan_ids.push(channel_id);
1763         }
1764
1765         // Send the initial payment.
1766         let amt_msat = 900_000;
1767         let skimmed_fee_msat = 20;
1768         let mut route_hints = Vec::new();
1769         for _ in 0..num_mpp_parts {
1770                 route_hints.push(RouteHint(vec![RouteHintHop {
1771                         src_node_id: nodes[1].node.get_our_node_id(),
1772                         short_channel_id: nodes[1].node.get_intercept_scid(),
1773                         fees: RoutingFees {
1774                                 base_msat: 1000,
1775                                 proportional_millionths: 0,
1776                         },
1777                         cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1778                         htlc_minimum_msat: None,
1779                         htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
1780                 }]));
1781         }
1782         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1783                 .with_route_hints(route_hints).unwrap()
1784                 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1785         let route_params = RouteParameters {
1786                 payment_params,
1787                 final_value_msat: amt_msat,
1788         };
1789         let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1790         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1791                 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
1792         check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
1793         let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
1794         assert_eq!(events.len(), num_mpp_parts);
1795
1796         // Forward the intercepted payments.
1797         for (idx, ev) in events.into_iter().enumerate() {
1798                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
1799                 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
1800
1801                 let events = nodes[1].node.get_and_clear_pending_events();
1802                 assert_eq!(events.len(), 1);
1803                 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
1804                         crate::events::Event::HTLCIntercepted {
1805                                 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
1806                         } => {
1807                                 assert_eq!(pmt_hash, payment_hash);
1808                                 (intercept_id, expected_outbound_amount_msat)
1809                         },
1810                         _ => panic!()
1811                 };
1812                 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
1813                         nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
1814                 expect_pending_htlcs_forwardable!(nodes[1]);
1815                 let payment_event = {
1816                         {
1817                                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1818                                 assert_eq!(added_monitors.len(), 1);
1819                                 added_monitors.clear();
1820                         }
1821                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1822                         assert_eq!(events.len(), 1);
1823                         SendEvent::from_event(events.remove(0))
1824                 };
1825                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1826                 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
1827                 if idx == num_mpp_parts - 1 {
1828                         expect_pending_htlcs_forwardable!(nodes[2]);
1829                 }
1830         }
1831
1832         // Claim the payment and check that the skimmed fee is as expected.
1833         let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1834         let events = nodes[2].node.get_and_clear_pending_events();
1835         assert_eq!(events.len(), 1);
1836         match events[0] {
1837                 crate::events::Event::PaymentClaimable {
1838                         ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
1839                 } => {
1840                         assert_eq!(payment_hash, payment_hash);
1841                         assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
1842                         assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
1843                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1844                         match purpose {
1845                                 crate::events::PaymentPurpose::InvoicePayment { payment_preimage: ev_payment_preimage,
1846                                         payment_secret: ev_payment_secret, .. } =>
1847                                 {
1848                                         assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
1849                                         assert_eq!(payment_secret, *ev_payment_secret);
1850                                 },
1851                                 _ => panic!(),
1852                         }
1853                 },
1854                 _ => panic!("Unexpected event"),
1855         }
1856         let mut expected_paths_vecs = Vec::new();
1857         let mut expected_paths = Vec::new();
1858         for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
1859         for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
1860         let total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
1861                 &nodes[0], &expected_paths[..], &vec![skimmed_fee_msat as u32; num_mpp_parts][..], false,
1862                 payment_preimage);
1863         // The sender doesn't know that the penultimate hop took an extra fee.
1864         expect_payment_sent(&nodes[0], payment_preimage,
1865                 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true);
1866 }
1867
1868 #[derive(PartialEq)]
1869 enum AutoRetry {
1870         Success,
1871         Spontaneous,
1872         FailAttempts,
1873         FailTimeout,
1874         FailOnRestart,
1875         FailOnRetry,
1876 }
1877
1878 #[test]
1879 fn automatic_retries() {
1880         do_automatic_retries(AutoRetry::Success);
1881         do_automatic_retries(AutoRetry::Spontaneous);
1882         do_automatic_retries(AutoRetry::FailAttempts);
1883         do_automatic_retries(AutoRetry::FailTimeout);
1884         do_automatic_retries(AutoRetry::FailOnRestart);
1885         do_automatic_retries(AutoRetry::FailOnRetry);
1886 }
1887 fn do_automatic_retries(test: AutoRetry) {
1888         // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1889         // below.
1890         let chanmon_cfgs = create_chanmon_cfgs(3);
1891         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1892         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1893
1894         let persister;
1895         let new_chain_monitor;
1896         let node_0_deserialized;
1897
1898         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1899         let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1900         let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1901
1902         // Marshall data to send the payment
1903         #[cfg(feature = "std")]
1904         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1905         #[cfg(not(feature = "std"))]
1906         let payment_expiry_secs = 60 * 60;
1907         let amt_msat = 1000;
1908         let mut invoice_features = Bolt11InvoiceFeatures::empty();
1909         invoice_features.set_variable_length_onion_required();
1910         invoice_features.set_payment_secret_required();
1911         invoice_features.set_basic_mpp_optional();
1912         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1913                 .with_expiry_time(payment_expiry_secs as u64)
1914                 .with_bolt11_features(invoice_features).unwrap();
1915         let route_params = RouteParameters {
1916                 payment_params,
1917                 final_value_msat: amt_msat,
1918         };
1919         let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1920
1921         macro_rules! pass_failed_attempt_with_retry_along_path {
1922                 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1923                         // Send a payment attempt that fails due to lack of liquidity on the second hop
1924                         check_added_monitors!(nodes[0], 1);
1925                         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1926                         let mut update_add = update_0.update_add_htlcs[0].clone();
1927                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1928                         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1929                         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1930                         nodes[1].node.process_pending_htlc_forwards();
1931                         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1932                                 vec![HTLCDestination::NextHopChannel {
1933                                         node_id: Some(nodes[2].node.get_our_node_id()),
1934                                         channel_id: $failing_channel_id,
1935                                 }]);
1936                         nodes[1].node.process_pending_htlc_forwards();
1937                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1938                         check_added_monitors!(&nodes[1], 1);
1939                         assert!(update_1.update_fail_htlcs.len() == 1);
1940                         let fail_msg = update_1.update_fail_htlcs[0].clone();
1941                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1942                         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1943
1944                         // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1945                         let mut events = nodes[0].node.get_and_clear_pending_events();
1946                         assert_eq!(events.len(), 2);
1947                         match events[0] {
1948                                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
1949                                         assert_eq!(payment_hash, ev_payment_hash);
1950                                         assert_eq!(payment_failed_permanently, false);
1951                                 },
1952                                 _ => panic!("Unexpected event"),
1953                         }
1954                         if $expect_pending_htlcs_forwardable {
1955                                 match events[1] {
1956                                         Event::PendingHTLCsForwardable { .. } => {},
1957                                         _ => panic!("Unexpected event"),
1958                                 }
1959                         } else {
1960                                 match events[1] {
1961                                         Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1962                                                 assert_eq!(payment_hash, ev_payment_hash);
1963                                         },
1964                                         _ => panic!("Unexpected event"),
1965                                 }
1966                         }
1967                 }
1968         }
1969
1970         if test == AutoRetry::Success {
1971                 // Test that we can succeed on the first retry.
1972                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1973                         PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1974                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1975
1976                 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1977                 // attempt, since the initial second hop channel will be excluded from pathfinding
1978                 create_announced_chan_between_nodes(&nodes, 1, 2);
1979
1980                 // We retry payments in `process_pending_htlc_forwards`
1981                 nodes[0].node.process_pending_htlc_forwards();
1982                 check_added_monitors!(nodes[0], 1);
1983                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1984                 assert_eq!(msg_events.len(), 1);
1985                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1986                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1987         } else if test == AutoRetry::Spontaneous {
1988                 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
1989                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
1990                         Retry::Attempts(1)).unwrap();
1991                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1992
1993                 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1994                 // attempt, since the initial second hop channel will be excluded from pathfinding
1995                 create_announced_chan_between_nodes(&nodes, 1, 2);
1996
1997                 // We retry payments in `process_pending_htlc_forwards`
1998                 nodes[0].node.process_pending_htlc_forwards();
1999                 check_added_monitors!(nodes[0], 1);
2000                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2001                 assert_eq!(msg_events.len(), 1);
2002                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2003                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2004         } else if test == AutoRetry::FailAttempts {
2005                 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2006                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2007                         PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2008                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2009
2010                 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2011                 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2012                 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2013
2014                 // We retry payments in `process_pending_htlc_forwards`
2015                 nodes[0].node.process_pending_htlc_forwards();
2016                 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2017
2018                 // Ensure we won't retry a second time.
2019                 nodes[0].node.process_pending_htlc_forwards();
2020                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2021                 assert_eq!(msg_events.len(), 0);
2022         } else if test == AutoRetry::FailTimeout {
2023                 #[cfg(not(feature = "no-std"))] {
2024                         // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2025                         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2026                                 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2027                         pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2028
2029                         // Advance the time so the second attempt fails due to timeout.
2030                         SinceEpoch::advance(Duration::from_secs(61));
2031
2032                         // Make sure we don't retry again.
2033                         nodes[0].node.process_pending_htlc_forwards();
2034                         let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2035                         assert_eq!(msg_events.len(), 0);
2036
2037                         let mut events = nodes[0].node.get_and_clear_pending_events();
2038                         assert_eq!(events.len(), 1);
2039                         match events[0] {
2040                                 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2041                                         assert_eq!(payment_hash, *ev_payment_hash);
2042                                         assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2043                                         assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2044                                 },
2045                                 _ => panic!("Unexpected event"),
2046                         }
2047                 }
2048         } else if test == AutoRetry::FailOnRestart {
2049                 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2050                 // attempts remaining prior to restart.
2051                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2052                         PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2053                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2054
2055                 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2056                 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2057                 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2058
2059                 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2060                 nodes[0].node.process_pending_htlc_forwards();
2061                 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2062
2063                 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2064                 let node_encoded = nodes[0].node.encode();
2065                 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2066                 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2067
2068                 let mut events = nodes[0].node.get_and_clear_pending_events();
2069                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2070                 // Make sure we don't retry again.
2071                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2072                 assert_eq!(msg_events.len(), 0);
2073
2074                 let mut events = nodes[0].node.get_and_clear_pending_events();
2075                 assert_eq!(events.len(), 1);
2076                 match events[0] {
2077                         Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2078                                 assert_eq!(payment_hash, *ev_payment_hash);
2079                                 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2080                                 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2081                         },
2082                         _ => panic!("Unexpected event"),
2083                 }
2084         } else if test == AutoRetry::FailOnRetry {
2085                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2086                         PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2087                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2088
2089                 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2090                 // fail to find a route.
2091                 nodes[0].node.process_pending_htlc_forwards();
2092                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2093                 assert_eq!(msg_events.len(), 0);
2094
2095                 let mut events = nodes[0].node.get_and_clear_pending_events();
2096                 assert_eq!(events.len(), 1);
2097                 match events[0] {
2098                         Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2099                                 assert_eq!(payment_hash, *ev_payment_hash);
2100                                 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2101                                 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2102                         },
2103                         _ => panic!("Unexpected event"),
2104                 }
2105         }
2106 }
2107
2108 #[test]
2109 fn auto_retry_partial_failure() {
2110         // Test that we'll retry appropriately on send partial failure and retry partial failure.
2111         let chanmon_cfgs = create_chanmon_cfgs(2);
2112         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2113         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2114         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2115
2116         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2117         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2118         let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2119
2120         // Marshall data to send the payment
2121         let amt_msat = 20_000;
2122         let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2123         #[cfg(feature = "std")]
2124         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2125         #[cfg(not(feature = "std"))]
2126         let payment_expiry_secs = 60 * 60;
2127         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2128         invoice_features.set_variable_length_onion_required();
2129         invoice_features.set_payment_secret_required();
2130         invoice_features.set_basic_mpp_optional();
2131         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2132                 .with_expiry_time(payment_expiry_secs as u64)
2133                 .with_bolt11_features(invoice_features).unwrap();
2134         let route_params = RouteParameters {
2135                 payment_params,
2136                 final_value_msat: amt_msat,
2137         };
2138
2139         // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
2140         // second (for the initial send path2 over chan_2) fails.
2141         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2142         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2143         // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
2144         // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
2145         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2146         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2147         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2148
2149         // Configure the initial send, retry1 and retry2's paths.
2150         let send_route = Route {
2151                 paths: vec![
2152                         Path { hops: vec![RouteHop {
2153                                 pubkey: nodes[1].node.get_our_node_id(),
2154                                 node_features: nodes[1].node.node_features(),
2155                                 short_channel_id: chan_1_id,
2156                                 channel_features: nodes[1].node.channel_features(),
2157                                 fee_msat: amt_msat / 2,
2158                                 cltv_expiry_delta: 100,
2159                         }], blinded_tail: None },
2160                         Path { hops: vec![RouteHop {
2161                                 pubkey: nodes[1].node.get_our_node_id(),
2162                                 node_features: nodes[1].node.node_features(),
2163                                 short_channel_id: chan_2_id,
2164                                 channel_features: nodes[1].node.channel_features(),
2165                                 fee_msat: amt_msat / 2,
2166                                 cltv_expiry_delta: 100,
2167                         }], blinded_tail: None },
2168                 ],
2169                 payment_params: Some(route_params.payment_params.clone()),
2170         };
2171         let retry_1_route = Route {
2172                 paths: vec![
2173                         Path { hops: vec![RouteHop {
2174                                 pubkey: nodes[1].node.get_our_node_id(),
2175                                 node_features: nodes[1].node.node_features(),
2176                                 short_channel_id: chan_1_id,
2177                                 channel_features: nodes[1].node.channel_features(),
2178                                 fee_msat: amt_msat / 4,
2179                                 cltv_expiry_delta: 100,
2180                         }], blinded_tail: None },
2181                         Path { hops: vec![RouteHop {
2182                                 pubkey: nodes[1].node.get_our_node_id(),
2183                                 node_features: nodes[1].node.node_features(),
2184                                 short_channel_id: chan_3_id,
2185                                 channel_features: nodes[1].node.channel_features(),
2186                                 fee_msat: amt_msat / 4,
2187                                 cltv_expiry_delta: 100,
2188                         }], blinded_tail: None },
2189                 ],
2190                 payment_params: Some(route_params.payment_params.clone()),
2191         };
2192         let retry_2_route = Route {
2193                 paths: vec![
2194                         Path { hops: vec![RouteHop {
2195                                 pubkey: nodes[1].node.get_our_node_id(),
2196                                 node_features: nodes[1].node.node_features(),
2197                                 short_channel_id: chan_1_id,
2198                                 channel_features: nodes[1].node.channel_features(),
2199                                 fee_msat: amt_msat / 4,
2200                                 cltv_expiry_delta: 100,
2201                         }], blinded_tail: None },
2202                 ],
2203                 payment_params: Some(route_params.payment_params.clone()),
2204         };
2205         nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2206         let mut payment_params = route_params.payment_params.clone();
2207         payment_params.previously_failed_channels.push(chan_2_id);
2208         nodes[0].router.expect_find_route(RouteParameters {
2209                         payment_params, final_value_msat: amt_msat / 2,
2210                 }, Ok(retry_1_route));
2211         let mut payment_params = route_params.payment_params.clone();
2212         payment_params.previously_failed_channels.push(chan_3_id);
2213         nodes[0].router.expect_find_route(RouteParameters {
2214                         payment_params, final_value_msat: amt_msat / 4,
2215                 }, Ok(retry_2_route));
2216
2217         // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2218         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2219                 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2220         let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
2221         assert_eq!(closed_chan_events.len(), 4);
2222         match closed_chan_events[0] {
2223                 Event::ChannelClosed { .. } => {},
2224                 _ => panic!("Unexpected event"),
2225         }
2226         match closed_chan_events[1] {
2227                 Event::PaymentPathFailed { .. } => {},
2228                 _ => panic!("Unexpected event"),
2229         }
2230         match closed_chan_events[2] {
2231                 Event::ChannelClosed { .. } => {},
2232                 _ => panic!("Unexpected event"),
2233         }
2234         match closed_chan_events[3] {
2235                 Event::PaymentPathFailed { .. } => {},
2236                 _ => panic!("Unexpected event"),
2237         }
2238
2239         // Pass the first part of the payment along the path.
2240         check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
2241         let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2242
2243         // First message is the first update_add, remaining messages are broadcasting channel updates and
2244         // errors for the permfailed channels
2245         assert_eq!(msg_events.len(), 5);
2246         let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2247
2248         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2249         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2250         check_added_monitors!(nodes[1], 1);
2251         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2252
2253         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2254         check_added_monitors!(nodes[0], 1);
2255         let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2256
2257         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2258         check_added_monitors!(nodes[0], 1);
2259         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2260
2261         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2262         check_added_monitors!(nodes[1], 1);
2263
2264         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2265         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2266         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2267         check_added_monitors!(nodes[1], 1);
2268         let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2269
2270         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2271         check_added_monitors!(nodes[0], 1);
2272
2273         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2274         check_added_monitors!(nodes[0], 1);
2275         let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2276
2277         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2278         check_added_monitors!(nodes[1], 1);
2279
2280         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2281         nodes[1].node.process_pending_htlc_forwards();
2282         expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2283         nodes[1].node.claim_funds(payment_preimage);
2284         expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2285         let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2286         assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2287
2288         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2289         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2290         check_added_monitors!(nodes[0], 1);
2291         let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2292
2293         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2294         check_added_monitors!(nodes[1], 4);
2295         let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2296
2297         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2298         check_added_monitors!(nodes[1], 1);
2299         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2300
2301         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2302         check_added_monitors!(nodes[0], 1);
2303
2304         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2305         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2306         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2307         check_added_monitors!(nodes[0], 1);
2308         let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2309
2310         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2311         check_added_monitors!(nodes[1], 1);
2312
2313         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2314         check_added_monitors!(nodes[1], 1);
2315         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2316
2317         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2318         check_added_monitors!(nodes[0], 1);
2319         expect_payment_sent!(nodes[0], payment_preimage);
2320 }
2321
2322 #[test]
2323 fn auto_retry_zero_attempts_send_error() {
2324         let chanmon_cfgs = create_chanmon_cfgs(2);
2325         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2326         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2327         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2328
2329         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2330         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2331
2332         // Marshall data to send the payment
2333         let amt_msat = 20_000;
2334         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2335         #[cfg(feature = "std")]
2336         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2337         #[cfg(not(feature = "std"))]
2338         let payment_expiry_secs = 60 * 60;
2339         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2340         invoice_features.set_variable_length_onion_required();
2341         invoice_features.set_payment_secret_required();
2342         invoice_features.set_basic_mpp_optional();
2343         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2344                 .with_expiry_time(payment_expiry_secs as u64)
2345                 .with_bolt11_features(invoice_features).unwrap();
2346         let route_params = RouteParameters {
2347                 payment_params,
2348                 final_value_msat: amt_msat,
2349         };
2350
2351         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2352         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2353                 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2354         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2355         let events = nodes[0].node.get_and_clear_pending_events();
2356         assert_eq!(events.len(), 3);
2357         if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2358         if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2359         if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2360         check_added_monitors!(nodes[0], 2);
2361 }
2362
2363 #[test]
2364 fn fails_paying_after_rejected_by_payee() {
2365         let chanmon_cfgs = create_chanmon_cfgs(2);
2366         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2367         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2368         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2369
2370         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2371
2372         // Marshall data to send the payment
2373         let amt_msat = 20_000;
2374         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2375         #[cfg(feature = "std")]
2376         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2377         #[cfg(not(feature = "std"))]
2378         let payment_expiry_secs = 60 * 60;
2379         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2380         invoice_features.set_variable_length_onion_required();
2381         invoice_features.set_payment_secret_required();
2382         invoice_features.set_basic_mpp_optional();
2383         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2384                 .with_expiry_time(payment_expiry_secs as u64)
2385                 .with_bolt11_features(invoice_features).unwrap();
2386         let route_params = RouteParameters {
2387                 payment_params,
2388                 final_value_msat: amt_msat,
2389         };
2390
2391         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2392                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2393         check_added_monitors!(nodes[0], 1);
2394         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2395         assert_eq!(events.len(), 1);
2396         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2397         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2398         check_added_monitors!(nodes[1], 0);
2399         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2400         expect_pending_htlcs_forwardable!(nodes[1]);
2401         expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2402
2403         nodes[1].node.fail_htlc_backwards(&payment_hash);
2404         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2405         pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2406 }
2407
2408 #[test]
2409 fn retry_multi_path_single_failed_payment() {
2410         // Tests that we can/will retry after a single path of an MPP payment failed immediately
2411         let chanmon_cfgs = create_chanmon_cfgs(2);
2412         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2413         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2414         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2415
2416         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2417         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2418
2419         let amt_msat = 100_010_000;
2420
2421         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2422         #[cfg(feature = "std")]
2423         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2424         #[cfg(not(feature = "std"))]
2425         let payment_expiry_secs = 60 * 60;
2426         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2427         invoice_features.set_variable_length_onion_required();
2428         invoice_features.set_payment_secret_required();
2429         invoice_features.set_basic_mpp_optional();
2430         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2431                 .with_expiry_time(payment_expiry_secs as u64)
2432                 .with_bolt11_features(invoice_features).unwrap();
2433         let route_params = RouteParameters {
2434                 payment_params: payment_params.clone(),
2435                 final_value_msat: amt_msat,
2436         };
2437
2438         let chans = nodes[0].node.list_usable_channels();
2439         let mut route = Route {
2440                 paths: vec![
2441                         Path { hops: vec![RouteHop {
2442                                 pubkey: nodes[1].node.get_our_node_id(),
2443                                 node_features: nodes[1].node.node_features(),
2444                                 short_channel_id: chans[0].short_channel_id.unwrap(),
2445                                 channel_features: nodes[1].node.channel_features(),
2446                                 fee_msat: 10_000,
2447                                 cltv_expiry_delta: 100,
2448                         }], blinded_tail: None },
2449                         Path { hops: vec![RouteHop {
2450                                 pubkey: nodes[1].node.get_our_node_id(),
2451                                 node_features: nodes[1].node.node_features(),
2452                                 short_channel_id: chans[1].short_channel_id.unwrap(),
2453                                 channel_features: nodes[1].node.channel_features(),
2454                                 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2455                                 cltv_expiry_delta: 100,
2456                         }], blinded_tail: None },
2457                 ],
2458                 payment_params: Some(payment_params),
2459         };
2460         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2461         // On retry, split the payment across both channels.
2462         route.paths[0].hops[0].fee_msat = 50_000_001;
2463         route.paths[1].hops[0].fee_msat = 50_000_000;
2464         let mut pay_params = route.payment_params.clone().unwrap();
2465         pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2466         nodes[0].router.expect_find_route(RouteParameters {
2467                         payment_params: pay_params,
2468                         // Note that the second request here requests the amount we originally failed to send,
2469                         // not the amount remaining on the full payment, which should be changed.
2470                         final_value_msat: 100_000_001,
2471                 }, Ok(route.clone()));
2472
2473         {
2474                 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2475                 // The initial send attempt, 2 paths
2476                 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2477                 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2478                 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2479                 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2480                 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2481         }
2482
2483         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2484                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2485         let events = nodes[0].node.get_and_clear_pending_events();
2486         assert_eq!(events.len(), 1);
2487         match events[0] {
2488                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2489                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2490                         short_channel_id: Some(expected_scid), .. } =>
2491                 {
2492                         assert_eq!(payment_hash, ev_payment_hash);
2493                         assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2494                 },
2495                 _ => panic!("Unexpected event"),
2496         }
2497         let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2498         assert_eq!(htlc_msgs.len(), 2);
2499         check_added_monitors!(nodes[0], 2);
2500 }
2501
2502 #[test]
2503 fn immediate_retry_on_failure() {
2504         // Tests that we can/will retry immediately after a failure
2505         let chanmon_cfgs = create_chanmon_cfgs(2);
2506         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2507         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2508         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2509
2510         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2511         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2512
2513         let amt_msat = 100_000_001;
2514         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2515         #[cfg(feature = "std")]
2516         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2517         #[cfg(not(feature = "std"))]
2518         let payment_expiry_secs = 60 * 60;
2519         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2520         invoice_features.set_variable_length_onion_required();
2521         invoice_features.set_payment_secret_required();
2522         invoice_features.set_basic_mpp_optional();
2523         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2524                 .with_expiry_time(payment_expiry_secs as u64)
2525                 .with_bolt11_features(invoice_features).unwrap();
2526         let route_params = RouteParameters {
2527                 payment_params,
2528                 final_value_msat: amt_msat,
2529         };
2530
2531         let chans = nodes[0].node.list_usable_channels();
2532         let mut route = Route {
2533                 paths: vec![
2534                         Path { hops: vec![RouteHop {
2535                                 pubkey: nodes[1].node.get_our_node_id(),
2536                                 node_features: nodes[1].node.node_features(),
2537                                 short_channel_id: chans[0].short_channel_id.unwrap(),
2538                                 channel_features: nodes[1].node.channel_features(),
2539                                 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2540                                 cltv_expiry_delta: 100,
2541                         }], blinded_tail: None },
2542                 ],
2543                 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2544         };
2545         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2546         // On retry, split the payment across both channels.
2547         route.paths.push(route.paths[0].clone());
2548         route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2549         route.paths[0].hops[0].fee_msat = 50_000_000;
2550         route.paths[1].hops[0].fee_msat = 50_000_001;
2551         let mut pay_params = route_params.payment_params.clone();
2552         pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2553         nodes[0].router.expect_find_route(RouteParameters {
2554                         payment_params: pay_params, final_value_msat: amt_msat,
2555                 }, Ok(route.clone()));
2556
2557         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2558                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2559         let events = nodes[0].node.get_and_clear_pending_events();
2560         assert_eq!(events.len(), 1);
2561         match events[0] {
2562                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2563                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2564                         short_channel_id: Some(expected_scid), .. } =>
2565                 {
2566                         assert_eq!(payment_hash, ev_payment_hash);
2567                         assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2568                 },
2569                 _ => panic!("Unexpected event"),
2570         }
2571         let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2572         assert_eq!(htlc_msgs.len(), 2);
2573         check_added_monitors!(nodes[0], 2);
2574 }
2575
2576 #[test]
2577 fn no_extra_retries_on_back_to_back_fail() {
2578         // In a previous release, we had a race where we may exceed the payment retry count if we
2579         // get two failures in a row with the second indicating that all paths had failed (this field,
2580         // `all_paths_failed`, has since been removed).
2581         // Generally, when we give up trying to retry a payment, we don't know for sure what the
2582         // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2583         // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2584         // pending which we will see later. Thus, when we previously removed the retry tracking map
2585         // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2586         // retry entry even though more events for the same payment were still pending. This led to
2587         // us retrying a payment again even though we'd already given up on it.
2588         //
2589         // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2590         // is used to remove the payment retry counter entries instead. This tests for the specific
2591         // excess-retry case while also testing `PaymentFailed` generation.
2592
2593         let chanmon_cfgs = create_chanmon_cfgs(3);
2594         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2595         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2596         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2597
2598         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2599         let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2600
2601         let amt_msat = 200_000_000;
2602         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2603         #[cfg(feature = "std")]
2604         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2605         #[cfg(not(feature = "std"))]
2606         let payment_expiry_secs = 60 * 60;
2607         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2608         invoice_features.set_variable_length_onion_required();
2609         invoice_features.set_payment_secret_required();
2610         invoice_features.set_basic_mpp_optional();
2611         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2612                 .with_expiry_time(payment_expiry_secs as u64)
2613                 .with_bolt11_features(invoice_features).unwrap();
2614         let route_params = RouteParameters {
2615                 payment_params,
2616                 final_value_msat: amt_msat,
2617         };
2618
2619         let mut route = Route {
2620                 paths: vec![
2621                         Path { hops: vec![RouteHop {
2622                                 pubkey: nodes[1].node.get_our_node_id(),
2623                                 node_features: nodes[1].node.node_features(),
2624                                 short_channel_id: chan_1_scid,
2625                                 channel_features: nodes[1].node.channel_features(),
2626                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2627                                 cltv_expiry_delta: 100,
2628                         }, RouteHop {
2629                                 pubkey: nodes[2].node.get_our_node_id(),
2630                                 node_features: nodes[2].node.node_features(),
2631                                 short_channel_id: chan_2_scid,
2632                                 channel_features: nodes[2].node.channel_features(),
2633                                 fee_msat: 100_000_000,
2634                                 cltv_expiry_delta: 100,
2635                         }], blinded_tail: None },
2636                         Path { hops: vec![RouteHop {
2637                                 pubkey: nodes[1].node.get_our_node_id(),
2638                                 node_features: nodes[1].node.node_features(),
2639                                 short_channel_id: chan_1_scid,
2640                                 channel_features: nodes[1].node.channel_features(),
2641                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2642                                 cltv_expiry_delta: 100,
2643                         }, RouteHop {
2644                                 pubkey: nodes[2].node.get_our_node_id(),
2645                                 node_features: nodes[2].node.node_features(),
2646                                 short_channel_id: chan_2_scid,
2647                                 channel_features: nodes[2].node.channel_features(),
2648                                 fee_msat: 100_000_000,
2649                                 cltv_expiry_delta: 100,
2650                         }], blinded_tail: None }
2651                 ],
2652                 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2653         };
2654         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2655         let mut second_payment_params = route_params.payment_params.clone();
2656         second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2657         // On retry, we'll only return one path
2658         route.paths.remove(1);
2659         route.paths[0].hops[1].fee_msat = amt_msat;
2660         nodes[0].router.expect_find_route(RouteParameters {
2661                         payment_params: second_payment_params,
2662                         final_value_msat: amt_msat,
2663                 }, Ok(route.clone()));
2664
2665         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2666                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2667         let htlc_updates = SendEvent::from_node(&nodes[0]);
2668         check_added_monitors!(nodes[0], 1);
2669         assert_eq!(htlc_updates.msgs.len(), 1);
2670
2671         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2672         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2673         check_added_monitors!(nodes[1], 1);
2674         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2675
2676         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2677         check_added_monitors!(nodes[0], 1);
2678         let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2679
2680         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2681         check_added_monitors!(nodes[0], 1);
2682         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2683
2684         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2685         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2686         check_added_monitors!(nodes[1], 1);
2687         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2688
2689         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2690         check_added_monitors!(nodes[1], 1);
2691         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2692
2693         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2694         check_added_monitors!(nodes[0], 1);
2695
2696         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2697         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2698         check_added_monitors!(nodes[0], 1);
2699         let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2700
2701         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2702         check_added_monitors!(nodes[1], 1);
2703         let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2704
2705         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2706         check_added_monitors!(nodes[1], 1);
2707         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2708
2709         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2710         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2711         check_added_monitors!(nodes[0], 1);
2712
2713         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2714         check_added_monitors!(nodes[0], 1);
2715         let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2716
2717         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2718         check_added_monitors!(nodes[1], 1);
2719         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2720         check_added_monitors!(nodes[1], 1);
2721         let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2722
2723         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2724         check_added_monitors!(nodes[0], 1);
2725
2726         // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2727         // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2728         // with it set.
2729         //
2730         // Previously, we retried payments in an event consumer, which would retry each
2731         // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2732         // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2733         // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2734         // by adding the `PaymentFailed` event.
2735         //
2736         // Because we now retry payments as a batch, we simply return a single-path route in the
2737         // second, batched, request, have that fail, ensure the payment was abandoned.
2738         let mut events = nodes[0].node.get_and_clear_pending_events();
2739         assert_eq!(events.len(), 3);
2740         match events[0] {
2741                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2742                         assert_eq!(payment_hash, ev_payment_hash);
2743                         assert_eq!(payment_failed_permanently, false);
2744                 },
2745                 _ => panic!("Unexpected event"),
2746         }
2747         match events[1] {
2748                 Event::PendingHTLCsForwardable { .. } => {},
2749                 _ => panic!("Unexpected event"),
2750         }
2751         match events[2] {
2752                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2753                         assert_eq!(payment_hash, ev_payment_hash);
2754                         assert_eq!(payment_failed_permanently, false);
2755                 },
2756                 _ => panic!("Unexpected event"),
2757         }
2758
2759         nodes[0].node.process_pending_htlc_forwards();
2760         let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2761         check_added_monitors!(nodes[0], 1);
2762
2763         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2764         commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2765         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2766         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2767         commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2768
2769         let mut events = nodes[0].node.get_and_clear_pending_events();
2770         assert_eq!(events.len(), 2);
2771         match events[0] {
2772                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2773                         assert_eq!(payment_hash, ev_payment_hash);
2774                         assert_eq!(payment_failed_permanently, false);
2775                 },
2776                 _ => panic!("Unexpected event"),
2777         }
2778         match events[1] {
2779                 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2780                         assert_eq!(payment_hash, *ev_payment_hash);
2781                         assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2782                         assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2783                 },
2784                 _ => panic!("Unexpected event"),
2785         }
2786 }
2787
2788 #[test]
2789 fn test_simple_partial_retry() {
2790         // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2791         // full amount of the payment, rather than only the missing amount. Here we simply test for
2792         // this by sending a payment with two parts, failing one, and retrying the second. Note that
2793         // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2794         // request.
2795         let chanmon_cfgs = create_chanmon_cfgs(3);
2796         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2797         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2798         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2799
2800         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2801         let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2802
2803         let amt_msat = 200_000_000;
2804         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2805         #[cfg(feature = "std")]
2806         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2807         #[cfg(not(feature = "std"))]
2808         let payment_expiry_secs = 60 * 60;
2809         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2810         invoice_features.set_variable_length_onion_required();
2811         invoice_features.set_payment_secret_required();
2812         invoice_features.set_basic_mpp_optional();
2813         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2814                 .with_expiry_time(payment_expiry_secs as u64)
2815                 .with_bolt11_features(invoice_features).unwrap();
2816         let route_params = RouteParameters {
2817                 payment_params,
2818                 final_value_msat: amt_msat,
2819         };
2820
2821         let mut route = Route {
2822                 paths: vec![
2823                         Path { hops: vec![RouteHop {
2824                                 pubkey: nodes[1].node.get_our_node_id(),
2825                                 node_features: nodes[1].node.node_features(),
2826                                 short_channel_id: chan_1_scid,
2827                                 channel_features: nodes[1].node.channel_features(),
2828                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2829                                 cltv_expiry_delta: 100,
2830                         }, RouteHop {
2831                                 pubkey: nodes[2].node.get_our_node_id(),
2832                                 node_features: nodes[2].node.node_features(),
2833                                 short_channel_id: chan_2_scid,
2834                                 channel_features: nodes[2].node.channel_features(),
2835                                 fee_msat: 100_000_000,
2836                                 cltv_expiry_delta: 100,
2837                         }], blinded_tail: None },
2838                         Path { hops: vec![RouteHop {
2839                                 pubkey: nodes[1].node.get_our_node_id(),
2840                                 node_features: nodes[1].node.node_features(),
2841                                 short_channel_id: chan_1_scid,
2842                                 channel_features: nodes[1].node.channel_features(),
2843                                 fee_msat: 100_000,
2844                                 cltv_expiry_delta: 100,
2845                         }, RouteHop {
2846                                 pubkey: nodes[2].node.get_our_node_id(),
2847                                 node_features: nodes[2].node.node_features(),
2848                                 short_channel_id: chan_2_scid,
2849                                 channel_features: nodes[2].node.channel_features(),
2850                                 fee_msat: 100_000_000,
2851                                 cltv_expiry_delta: 100,
2852                         }], blinded_tail: None }
2853                 ],
2854                 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2855         };
2856         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2857         let mut second_payment_params = route_params.payment_params.clone();
2858         second_payment_params.previously_failed_channels = vec![chan_2_scid];
2859         // On retry, we'll only be asked for one path (or 100k sats)
2860         route.paths.remove(0);
2861         nodes[0].router.expect_find_route(RouteParameters {
2862                         payment_params: second_payment_params,
2863                         final_value_msat: amt_msat / 2,
2864                 }, Ok(route.clone()));
2865
2866         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2867                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2868         let htlc_updates = SendEvent::from_node(&nodes[0]);
2869         check_added_monitors!(nodes[0], 1);
2870         assert_eq!(htlc_updates.msgs.len(), 1);
2871
2872         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2873         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2874         check_added_monitors!(nodes[1], 1);
2875         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2876
2877         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2878         check_added_monitors!(nodes[0], 1);
2879         let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2880
2881         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2882         check_added_monitors!(nodes[0], 1);
2883         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2884
2885         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2886         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2887         check_added_monitors!(nodes[1], 1);
2888         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2889
2890         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2891         check_added_monitors!(nodes[1], 1);
2892         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2893
2894         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2895         check_added_monitors!(nodes[0], 1);
2896
2897         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2898         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2899         check_added_monitors!(nodes[0], 1);
2900         let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2901
2902         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2903         check_added_monitors!(nodes[1], 1);
2904
2905         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2906         check_added_monitors!(nodes[1], 1);
2907
2908         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2909
2910         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2911         check_added_monitors!(nodes[0], 1);
2912
2913         let mut events = nodes[0].node.get_and_clear_pending_events();
2914         assert_eq!(events.len(), 2);
2915         match events[0] {
2916                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2917                         assert_eq!(payment_hash, ev_payment_hash);
2918                         assert_eq!(payment_failed_permanently, false);
2919                 },
2920                 _ => panic!("Unexpected event"),
2921         }
2922         match events[1] {
2923                 Event::PendingHTLCsForwardable { .. } => {},
2924                 _ => panic!("Unexpected event"),
2925         }
2926
2927         nodes[0].node.process_pending_htlc_forwards();
2928         let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2929         check_added_monitors!(nodes[0], 1);
2930
2931         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2932         commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2933
2934         expect_pending_htlcs_forwardable!(nodes[1]);
2935         check_added_monitors!(nodes[1], 1);
2936
2937         let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2938         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2939         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2940         commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2941
2942         expect_pending_htlcs_forwardable!(nodes[2]);
2943         expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2944 }
2945
2946 #[test]
2947 #[cfg(feature = "std")]
2948 fn test_threaded_payment_retries() {
2949         // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2950         // a single thread and would happily let multiple threads run retries at the same time. Because
2951         // retries are done by first calculating the amount we need to retry, then dropping the
2952         // relevant lock, then actually sending, we would happily let multiple threads retry the same
2953         // amount at the same time, overpaying our original HTLC!
2954         let chanmon_cfgs = create_chanmon_cfgs(4);
2955         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2956         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2957         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2958
2959         // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2960         // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2961         // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2962         // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2963         // our channel.
2964         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2965         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2966         let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2967         let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2968
2969         let amt_msat = 100_000_000;
2970         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2971         #[cfg(feature = "std")]
2972         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2973         #[cfg(not(feature = "std"))]
2974         let payment_expiry_secs = 60 * 60;
2975         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2976         invoice_features.set_variable_length_onion_required();
2977         invoice_features.set_payment_secret_required();
2978         invoice_features.set_basic_mpp_optional();
2979         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2980                 .with_expiry_time(payment_expiry_secs as u64)
2981                 .with_bolt11_features(invoice_features).unwrap();
2982         let mut route_params = RouteParameters {
2983                 payment_params,
2984                 final_value_msat: amt_msat,
2985         };
2986
2987         let mut route = Route {
2988                 paths: vec![
2989                         Path { hops: vec![RouteHop {
2990                                 pubkey: nodes[1].node.get_our_node_id(),
2991                                 node_features: nodes[1].node.node_features(),
2992                                 short_channel_id: chan_1_scid,
2993                                 channel_features: nodes[1].node.channel_features(),
2994                                 fee_msat: 0,
2995                                 cltv_expiry_delta: 100,
2996                         }, RouteHop {
2997                                 pubkey: nodes[3].node.get_our_node_id(),
2998                                 node_features: nodes[2].node.node_features(),
2999                                 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3000                                 channel_features: nodes[2].node.channel_features(),
3001                                 fee_msat: amt_msat / 1000,
3002                                 cltv_expiry_delta: 100,
3003                         }], blinded_tail: None },
3004                         Path { hops: vec![RouteHop {
3005                                 pubkey: nodes[2].node.get_our_node_id(),
3006                                 node_features: nodes[2].node.node_features(),
3007                                 short_channel_id: chan_3_scid,
3008                                 channel_features: nodes[2].node.channel_features(),
3009                                 fee_msat: 100_000,
3010                                 cltv_expiry_delta: 100,
3011                         }, RouteHop {
3012                                 pubkey: nodes[3].node.get_our_node_id(),
3013                                 node_features: nodes[3].node.node_features(),
3014                                 short_channel_id: chan_4_scid,
3015                                 channel_features: nodes[3].node.channel_features(),
3016                                 fee_msat: amt_msat - amt_msat / 1000,
3017                                 cltv_expiry_delta: 100,
3018                         }], blinded_tail: None }
3019                 ],
3020                 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
3021         };
3022         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3023
3024         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3025                 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3026         check_added_monitors!(nodes[0], 2);
3027         let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3028         assert_eq!(send_msg_events.len(), 2);
3029         send_msg_events.retain(|msg|
3030                 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3031                         // Drop the commitment update for nodes[2], we can just let that one sit pending
3032                         // forever.
3033                         *node_id == nodes[1].node.get_our_node_id()
3034                 } else { panic!(); }
3035         );
3036
3037         // from here on out, the retry `RouteParameters` amount will be amt/1000
3038         route_params.final_value_msat /= 1000;
3039         route.paths.pop();
3040
3041         let end_time = Instant::now() + Duration::from_secs(1);
3042         macro_rules! thread_body { () => { {
3043                 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3044                 let node_ref = NodePtr::from_node(&nodes[0]);
3045                 move || {
3046                         let node_a = unsafe { &*node_ref.0 };
3047                         while Instant::now() < end_time {
3048                                 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3049                                 // Ignore if we have any pending events, just always pretend we just got a
3050                                 // PendingHTLCsForwardable
3051                                 node_a.node.process_pending_htlc_forwards();
3052                         }
3053                 }
3054         } } }
3055         let mut threads = Vec::new();
3056         for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3057
3058         // Back in the main thread, poll pending messages and make sure that we never have more than
3059         // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3060         // there are HTLC messages shoved in while its running. This allows us to test that we never
3061         // generate an additional update_add_htlc until we've fully failed the first.
3062         let mut previously_failed_channels = Vec::new();
3063         loop {
3064                 assert_eq!(send_msg_events.len(), 1);
3065                 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3066                 assert_eq!(send_event.msgs.len(), 1);
3067
3068                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3069                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3070
3071                 // Note that we only push one route into `expect_find_route` at a time, because that's all
3072                 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3073                 // we should still ultimately fail for the same reason - because we're trying to send too
3074                 // many HTLCs at once.
3075                 let mut new_route_params = route_params.clone();
3076                 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3077                 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3078                 route.paths[0].hops[1].short_channel_id += 1;
3079                 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3080
3081                 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3082                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3083                 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3084                 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3085                 // This races with our other threads which may generate an add-HTLCs commitment update via
3086                 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3087                 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3088                 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3089                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3090
3091                 let cur_time = Instant::now();
3092                 if cur_time > end_time {
3093                         for thread in threads.drain(..) { thread.join().unwrap(); }
3094                 }
3095
3096                 // Make sure we have some events to handle when we go around...
3097                 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3098                 nodes[0].node.process_pending_htlc_forwards();
3099                 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3100                 check_added_monitors!(nodes[0], 2);
3101
3102                 if cur_time > end_time {
3103                         break;
3104                 }
3105         }
3106 }
3107
3108 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
3109         // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3110         // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3111         // it was last persisted.
3112         let chanmon_cfgs = create_chanmon_cfgs(2);
3113         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3114         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3115         let (persister_a, persister_b, persister_c);
3116         let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3117         let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3118         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3119
3120         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3121
3122         let mut nodes_0_serialized = Vec::new();
3123         if !persist_manager_with_payment {
3124                 nodes_0_serialized = nodes[0].node.encode();
3125         }
3126
3127         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3128
3129         if persist_manager_with_payment {
3130                 nodes_0_serialized = nodes[0].node.encode();
3131         }
3132
3133         nodes[1].node.claim_funds(our_payment_preimage);
3134         check_added_monitors!(nodes[1], 1);
3135         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3136
3137         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3138         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3139         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3140         check_added_monitors!(nodes[0], 1);
3141
3142         // The ChannelMonitor should always be the latest version, as we're required to persist it
3143         // during the commitment signed handling.
3144         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3145         reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3146
3147         let events = nodes[0].node.get_and_clear_pending_events();
3148         assert_eq!(events.len(), 2);
3149         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3150         if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3151         // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3152         // the double-claim that would otherwise appear at the end of this test.
3153         nodes[0].node.timer_tick_occurred();
3154         let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3155         assert_eq!(as_broadcasted_txn.len(), 1);
3156
3157         // Ensure that, even after some time, if we restart we still include *something* in the current
3158         // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3159         // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3160         // A naive implementation of the fix here would wipe the pending payments set, causing a
3161         // failure event when we restart.
3162         for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3163
3164         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3165         reload_node!(nodes[0], test_default_channel_config(), &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister_b, chain_monitor_b, nodes_0_deserialized_b);
3166         let events = nodes[0].node.get_and_clear_pending_events();
3167         assert!(events.is_empty());
3168
3169         // Ensure that we don't generate any further events even after the channel-closing commitment
3170         // transaction is confirmed on-chain.
3171         confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3172         for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3173
3174         let events = nodes[0].node.get_and_clear_pending_events();
3175         assert!(events.is_empty());
3176
3177         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3178         reload_node!(nodes[0], test_default_channel_config(), &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister_c, chain_monitor_c, nodes_0_deserialized_c);
3179         let events = nodes[0].node.get_and_clear_pending_events();
3180         assert!(events.is_empty());
3181         check_added_monitors(&nodes[0], 1);
3182 }
3183
3184 #[test]
3185 fn no_missing_sent_on_midpoint_reload() {
3186         do_no_missing_sent_on_midpoint_reload(false);
3187         do_no_missing_sent_on_midpoint_reload(true);
3188 }
3189
3190 fn do_claim_from_closed_chan(fail_payment: bool) {
3191         // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3192         // received had been closed between when the HTLC was received and when we went to claim it.
3193         // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3194         // presumably the sender may retry later. Long ago it also reduced total code in the claim
3195         // pipeline.
3196         //
3197         // However, this doesn't make sense if you're trying to do an atomic swap or some other
3198         // protocol that requires atomicity with some other action - if your money got claimed
3199         // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3200         // is an over-optimization - there should be a very, very low likelihood that a channel closes
3201         // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3202         // Since we now have code to handle this anyway we should allow it.
3203
3204         // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3205         // CLTVs on the paths to different value resulting in a different claim deadline.
3206         let chanmon_cfgs = create_chanmon_cfgs(4);
3207         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3208         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3209         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3210
3211         create_announced_chan_between_nodes(&nodes, 0, 1);
3212         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3213         let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3214         create_announced_chan_between_nodes(&nodes, 2, 3);
3215
3216         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3217         let mut route_params = RouteParameters {
3218                 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3219                         .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
3220                 final_value_msat: 10_000_000,
3221         };
3222         let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3223                 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3224         // Make sure the route is ordered as the B->D path before C->D
3225         route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3226                 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3227
3228         // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3229         // the HTLC is being relayed.
3230         route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3231         route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3232         let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3233
3234         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3235         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3236                 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3237         check_added_monitors(&nodes[0], 2);
3238         let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3239         send_msgs.sort_by(|a, _| {
3240                 let a_node_id =
3241                         if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3242                 let node_b_id = nodes[1].node.get_our_node_id();
3243                 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3244         });
3245
3246         assert_eq!(send_msgs.len(), 2);
3247         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3248                 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3249         let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3250                 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3251
3252         match receive_event.unwrap() {
3253                 Event::PaymentClaimable { claim_deadline, .. } => {
3254                         assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3255                 },
3256                 _ => panic!(),
3257         }
3258
3259         // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3260         // height.
3261         connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3262                 - if fail_payment { 0 } else { 2 });
3263         if fail_payment {
3264                 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3265                 // and expire both immediately, though, by connecting another 4 blocks.
3266                 let reason = HTLCDestination::FailedPayment { payment_hash };
3267                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3268                 connect_blocks(&nodes[3], 4);
3269                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3270                 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3271         } else {
3272                 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3273                 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false);
3274                 check_closed_broadcast(&nodes[1], 1, true);
3275                 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3276                 assert_eq!(bs_tx.len(), 1);
3277
3278                 mine_transaction(&nodes[3], &bs_tx[0]);
3279                 check_added_monitors(&nodes[3], 1);
3280                 check_closed_broadcast(&nodes[3], 1, true);
3281                 check_closed_event(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false);
3282
3283                 nodes[3].node.claim_funds(payment_preimage);
3284                 check_added_monitors(&nodes[3], 2);
3285                 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3286
3287                 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3288                 assert_eq!(ds_tx.len(), 1);
3289                 check_spends!(&ds_tx[0], &bs_tx[0]);
3290
3291                 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3292                 check_added_monitors(&nodes[1], 1);
3293                 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3294
3295                 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3296                 check_added_monitors(&nodes[1], 1);
3297                 assert_eq!(bs_claims.len(), 1);
3298                 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3299                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3300                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3301                 } else { panic!(); }
3302
3303                 expect_payment_sent!(nodes[0], payment_preimage);
3304
3305                 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3306                 assert_eq!(ds_claim_msgs.len(), 1);
3307                 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3308                         nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3309                         let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3310                         check_added_monitors(&nodes[2], 1);
3311                         commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3312                         expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3313                         cs_claim_msgs
3314                 } else { panic!(); };
3315
3316                 assert_eq!(cs_claim_msgs.len(), 1);
3317                 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3318                         nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3319                         commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3320                 } else { panic!(); }
3321
3322                 expect_payment_path_successful!(nodes[0]);
3323         }
3324 }
3325
3326 #[test]
3327 fn claim_from_closed_chan() {
3328         do_claim_from_closed_chan(true);
3329         do_claim_from_closed_chan(false);
3330 }
3331
3332 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3333         // Check that a payment metadata received on one HTLC that doesn't match the one received on
3334         // another results in the HTLC being rejected.
3335         //
3336         // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3337         // first of which we'll deliver and the second of which we'll fail and then re-send with
3338         // modified payment metadata, which will in turn result in it being failed by the recipient.
3339         let chanmon_cfgs = create_chanmon_cfgs(4);
3340         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3341         let mut config = test_default_channel_config();
3342         config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3343         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3344
3345         let persister;
3346         let new_chain_monitor;
3347         let nodes_0_deserialized;
3348
3349         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3350
3351         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3352         let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3353         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3354         let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3355
3356         // Pay more than half of each channel's max, requiring MPP
3357         let amt_msat = 750_000_000;
3358         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3359         let payment_id = PaymentId(payment_hash.0);
3360         let payment_metadata = vec![44, 49, 52, 142];
3361
3362         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3363                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3364         let mut route_params = RouteParameters {
3365                 payment_params,
3366                 final_value_msat: amt_msat,
3367         };
3368
3369         // Send the MPP payment, delivering the updated commitment state to nodes[1].
3370         nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3371                         payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata),
3372                 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3373         check_added_monitors!(nodes[0], 2);
3374
3375         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3376         assert_eq!(send_events.len(), 2);
3377         let first_send = SendEvent::from_event(send_events.pop().unwrap());
3378         let second_send = SendEvent::from_event(send_events.pop().unwrap());
3379
3380         let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3381                 (&first_send, &second_send)
3382         } else {
3383                 (&second_send, &first_send)
3384         };
3385         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3386         commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3387
3388         expect_pending_htlcs_forwardable!(nodes[1]);
3389         check_added_monitors(&nodes[1], 1);
3390         let b_forward_ev = SendEvent::from_node(&nodes[1]);
3391         nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3392         commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3393
3394         expect_pending_htlcs_forwardable!(nodes[3]);
3395
3396         // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3397         // will result in nodes[2] failing the HTLC back.
3398         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3399         nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3400
3401         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3402         commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3403
3404         let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3405         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3406         commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3407
3408         let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3409         assert_eq!(payment_fail_retryable_evs.len(), 2);
3410         if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3411         if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3412
3413         // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3414         // stored for our payment.
3415         if do_modify {
3416                 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3417         }
3418
3419         // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3420         // the payment state.
3421         if do_reload {
3422                 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3423                 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3424                 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3425                         persister, new_chain_monitor, nodes_0_deserialized);
3426                 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3427                 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
3428         }
3429         let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
3430         reconnect_args.send_channel_ready = (true, true);
3431         reconnect_nodes(reconnect_args);
3432
3433         // Create a new channel between C and D as A will refuse to retry on the existing one because
3434         // it just failed.
3435         let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3436
3437         // Now retry the failed HTLC.
3438         nodes[0].node.process_pending_htlc_forwards();
3439         check_added_monitors(&nodes[0], 1);
3440         let as_resend = SendEvent::from_node(&nodes[0]);
3441         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3442         commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3443
3444         expect_pending_htlcs_forwardable!(nodes[2]);
3445         check_added_monitors(&nodes[2], 1);
3446         let cs_forward = SendEvent::from_node(&nodes[2]);
3447         nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3448         commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3449
3450         // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3451         // the payment metadata was modified, failing only the one modified HTLC and retaining the
3452         // other.
3453         if do_modify {
3454                 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3455                 nodes[3].node.process_pending_htlc_forwards();
3456                 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3457                         &[HTLCDestination::FailedPayment {payment_hash}]);
3458                 nodes[3].node.process_pending_htlc_forwards();
3459
3460                 check_added_monitors(&nodes[3], 1);
3461                 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3462
3463                 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3464                 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3465                 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3466                         &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3467         } else {
3468                 expect_pending_htlcs_forwardable!(nodes[3]);
3469                 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3470                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3471         }
3472 }
3473
3474 #[test]
3475 fn test_payment_metadata_consistency() {
3476         do_test_payment_metadata_consistency(true, true);
3477         do_test_payment_metadata_consistency(true, false);
3478         do_test_payment_metadata_consistency(false, true);
3479         do_test_payment_metadata_consistency(false, false);
3480 }