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