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