835ad67f1bc458638bf1061cfd56890070a916fa
[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, true, 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, _, payment_id) = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
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), payment_id });
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,  _, payment_id) = 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_id, 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                                 maybe_announced_channel: true,
2205                         }], blinded_tail: None },
2206                         Path { hops: vec![RouteHop {
2207                                 pubkey: nodes[1].node.get_our_node_id(),
2208                                 node_features: nodes[1].node.node_features(),
2209                                 short_channel_id: chan_2_id,
2210                                 channel_features: nodes[1].node.channel_features(),
2211                                 fee_msat: amt_msat / 2,
2212                                 cltv_expiry_delta: 100,
2213                                 maybe_announced_channel: true,
2214                         }], blinded_tail: None },
2215                 ],
2216                 route_params: Some(route_params.clone()),
2217         };
2218         let retry_1_route = Route {
2219                 paths: vec![
2220                         Path { hops: vec![RouteHop {
2221                                 pubkey: nodes[1].node.get_our_node_id(),
2222                                 node_features: nodes[1].node.node_features(),
2223                                 short_channel_id: chan_1_id,
2224                                 channel_features: nodes[1].node.channel_features(),
2225                                 fee_msat: amt_msat / 4,
2226                                 cltv_expiry_delta: 100,
2227                                 maybe_announced_channel: true,
2228                         }], blinded_tail: None },
2229                         Path { hops: vec![RouteHop {
2230                                 pubkey: nodes[1].node.get_our_node_id(),
2231                                 node_features: nodes[1].node.node_features(),
2232                                 short_channel_id: chan_3_id,
2233                                 channel_features: nodes[1].node.channel_features(),
2234                                 fee_msat: amt_msat / 4,
2235                                 cltv_expiry_delta: 100,
2236                                 maybe_announced_channel: true,
2237                         }], blinded_tail: None },
2238                 ],
2239                 route_params: Some(route_params.clone()),
2240         };
2241         let retry_2_route = Route {
2242                 paths: vec![
2243                         Path { hops: vec![RouteHop {
2244                                 pubkey: nodes[1].node.get_our_node_id(),
2245                                 node_features: nodes[1].node.node_features(),
2246                                 short_channel_id: chan_1_id,
2247                                 channel_features: nodes[1].node.channel_features(),
2248                                 fee_msat: amt_msat / 4,
2249                                 cltv_expiry_delta: 100,
2250                                 maybe_announced_channel: true,
2251                         }], blinded_tail: None },
2252                 ],
2253                 route_params: Some(route_params.clone()),
2254         };
2255         nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2256         let mut payment_params = route_params.payment_params.clone();
2257         payment_params.previously_failed_channels.push(chan_2_id);
2258         nodes[0].router.expect_find_route(
2259                 RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 2),
2260                 Ok(retry_1_route));
2261         let mut payment_params = route_params.payment_params.clone();
2262         payment_params.previously_failed_channels.push(chan_3_id);
2263         nodes[0].router.expect_find_route(
2264                 RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 4),
2265                 Ok(retry_2_route));
2266
2267         // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2268         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2269                 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2270         let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
2271         assert_eq!(closed_chan_events.len(), 4);
2272         match closed_chan_events[0] {
2273                 Event::ChannelClosed { .. } => {},
2274                 _ => panic!("Unexpected event"),
2275         }
2276         match closed_chan_events[1] {
2277                 Event::PaymentPathFailed { .. } => {},
2278                 _ => panic!("Unexpected event"),
2279         }
2280         match closed_chan_events[2] {
2281                 Event::ChannelClosed { .. } => {},
2282                 _ => panic!("Unexpected event"),
2283         }
2284         match closed_chan_events[3] {
2285                 Event::PaymentPathFailed { .. } => {},
2286                 _ => panic!("Unexpected event"),
2287         }
2288
2289         // Pass the first part of the payment along the path.
2290         check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
2291         let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2292
2293         // First message is the first update_add, remaining messages are broadcasting channel updates and
2294         // errors for the permfailed channels
2295         assert_eq!(msg_events.len(), 5);
2296         let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2297
2298         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2299         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2300         check_added_monitors!(nodes[1], 1);
2301         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2302
2303         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2304         check_added_monitors!(nodes[0], 1);
2305         let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2306
2307         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2308         check_added_monitors!(nodes[0], 1);
2309         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2310
2311         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2312         check_added_monitors!(nodes[1], 1);
2313
2314         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2315         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2316         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2317         check_added_monitors!(nodes[1], 1);
2318         let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2319
2320         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2321         check_added_monitors!(nodes[0], 1);
2322
2323         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2324         check_added_monitors!(nodes[0], 1);
2325         let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2326
2327         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2328         check_added_monitors!(nodes[1], 1);
2329
2330         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2331         nodes[1].node.process_pending_htlc_forwards();
2332         expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2333         nodes[1].node.claim_funds(payment_preimage);
2334         expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2335         let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2336         assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2337
2338         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2339         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
2340         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2341         check_added_monitors!(nodes[0], 1);
2342         let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2343
2344         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2345         check_added_monitors!(nodes[1], 4);
2346         let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2347
2348         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2349         check_added_monitors!(nodes[1], 1);
2350         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2351
2352         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2353         check_added_monitors!(nodes[0], 1);
2354         expect_payment_path_successful!(nodes[0]);
2355
2356         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2357         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2358         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2359         check_added_monitors!(nodes[0], 1);
2360         let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2361
2362         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2363         check_added_monitors!(nodes[1], 1);
2364
2365         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2366         check_added_monitors!(nodes[1], 1);
2367         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2368
2369         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2370         check_added_monitors!(nodes[0], 1);
2371         let events = nodes[0].node.get_and_clear_pending_events();
2372         assert_eq!(events.len(), 2);
2373         if let Event::PaymentPathSuccessful { .. } = events[0] {} else { panic!(); }
2374         if let Event::PaymentPathSuccessful { .. } = events[1] {} else { panic!(); }
2375 }
2376
2377 #[test]
2378 fn auto_retry_zero_attempts_send_error() {
2379         let chanmon_cfgs = create_chanmon_cfgs(2);
2380         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2381         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2382         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2383
2384         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2385         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2386
2387         // Marshall data to send the payment
2388         let amt_msat = 20_000;
2389         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2390         #[cfg(feature = "std")]
2391         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2392         #[cfg(not(feature = "std"))]
2393         let payment_expiry_secs = 60 * 60;
2394         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2395         invoice_features.set_variable_length_onion_required();
2396         invoice_features.set_payment_secret_required();
2397         invoice_features.set_basic_mpp_optional();
2398         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2399                 .with_expiry_time(payment_expiry_secs as u64)
2400                 .with_bolt11_features(invoice_features).unwrap();
2401         let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2402
2403         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2404         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2405                 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2406         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2407         let events = nodes[0].node.get_and_clear_pending_events();
2408         assert_eq!(events.len(), 3);
2409         if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2410         if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2411         if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2412         check_added_monitors!(nodes[0], 2);
2413 }
2414
2415 #[test]
2416 fn fails_paying_after_rejected_by_payee() {
2417         let chanmon_cfgs = create_chanmon_cfgs(2);
2418         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2419         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2420         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2421
2422         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2423
2424         // Marshall data to send the payment
2425         let amt_msat = 20_000;
2426         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2427         #[cfg(feature = "std")]
2428         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2429         #[cfg(not(feature = "std"))]
2430         let payment_expiry_secs = 60 * 60;
2431         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2432         invoice_features.set_variable_length_onion_required();
2433         invoice_features.set_payment_secret_required();
2434         invoice_features.set_basic_mpp_optional();
2435         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2436                 .with_expiry_time(payment_expiry_secs as u64)
2437                 .with_bolt11_features(invoice_features).unwrap();
2438         let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2439
2440         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2441                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2442         check_added_monitors!(nodes[0], 1);
2443         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2444         assert_eq!(events.len(), 1);
2445         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2446         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2447         check_added_monitors!(nodes[1], 0);
2448         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2449         expect_pending_htlcs_forwardable!(nodes[1]);
2450         expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2451
2452         nodes[1].node.fail_htlc_backwards(&payment_hash);
2453         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2454         pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2455 }
2456
2457 #[test]
2458 fn retry_multi_path_single_failed_payment() {
2459         // Tests that we can/will retry after a single path of an MPP payment failed immediately
2460         let chanmon_cfgs = create_chanmon_cfgs(2);
2461         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2462         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2463         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2464
2465         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2466         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2467
2468         let amt_msat = 100_010_000;
2469
2470         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2471         #[cfg(feature = "std")]
2472         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2473         #[cfg(not(feature = "std"))]
2474         let payment_expiry_secs = 60 * 60;
2475         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2476         invoice_features.set_variable_length_onion_required();
2477         invoice_features.set_payment_secret_required();
2478         invoice_features.set_basic_mpp_optional();
2479         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2480                 .with_expiry_time(payment_expiry_secs as u64)
2481                 .with_bolt11_features(invoice_features).unwrap();
2482         let route_params = RouteParameters::from_payment_params_and_value(
2483                 payment_params.clone(), amt_msat);
2484
2485         let chans = nodes[0].node.list_usable_channels();
2486         let mut route = Route {
2487                 paths: vec![
2488                         Path { hops: vec![RouteHop {
2489                                 pubkey: nodes[1].node.get_our_node_id(),
2490                                 node_features: nodes[1].node.node_features(),
2491                                 short_channel_id: chans[0].short_channel_id.unwrap(),
2492                                 channel_features: nodes[1].node.channel_features(),
2493                                 fee_msat: 10_000,
2494                                 cltv_expiry_delta: 100,
2495                                 maybe_announced_channel: true,
2496                         }], blinded_tail: None },
2497                         Path { hops: vec![RouteHop {
2498                                 pubkey: nodes[1].node.get_our_node_id(),
2499                                 node_features: nodes[1].node.node_features(),
2500                                 short_channel_id: chans[1].short_channel_id.unwrap(),
2501                                 channel_features: nodes[1].node.channel_features(),
2502                                 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2503                                 cltv_expiry_delta: 100,
2504                                 maybe_announced_channel: true,
2505                         }], blinded_tail: None },
2506                 ],
2507                 route_params: Some(route_params.clone()),
2508         };
2509         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2510         // On retry, split the payment across both channels.
2511         route.paths[0].hops[0].fee_msat = 50_000_001;
2512         route.paths[1].hops[0].fee_msat = 50_000_000;
2513         let mut pay_params = route.route_params.clone().unwrap().payment_params;
2514         pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2515         nodes[0].router.expect_find_route(
2516                 // Note that the second request here requests the amount we originally failed to send,
2517                 // not the amount remaining on the full payment, which should be changed.
2518                 RouteParameters::from_payment_params_and_value(pay_params, 100_000_001),
2519                 Ok(route.clone()));
2520
2521         {
2522                 let scorer = chanmon_cfgs[0].scorer.read().unwrap();
2523                 // The initial send attempt, 2 paths
2524                 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2525                 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2526                 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2527                 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2528                 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2529         }
2530
2531         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2532                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2533         let events = nodes[0].node.get_and_clear_pending_events();
2534         assert_eq!(events.len(), 1);
2535         match events[0] {
2536                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2537                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2538                         short_channel_id: Some(expected_scid), .. } =>
2539                 {
2540                         assert_eq!(payment_hash, ev_payment_hash);
2541                         assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2542                 },
2543                 _ => panic!("Unexpected event"),
2544         }
2545         let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2546         assert_eq!(htlc_msgs.len(), 2);
2547         check_added_monitors!(nodes[0], 2);
2548 }
2549
2550 #[test]
2551 fn immediate_retry_on_failure() {
2552         // Tests that we can/will retry immediately after a failure
2553         let chanmon_cfgs = create_chanmon_cfgs(2);
2554         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2555         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2556         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2557
2558         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2559         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2560
2561         let amt_msat = 100_000_001;
2562         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2563         #[cfg(feature = "std")]
2564         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2565         #[cfg(not(feature = "std"))]
2566         let payment_expiry_secs = 60 * 60;
2567         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2568         invoice_features.set_variable_length_onion_required();
2569         invoice_features.set_payment_secret_required();
2570         invoice_features.set_basic_mpp_optional();
2571         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2572                 .with_expiry_time(payment_expiry_secs as u64)
2573                 .with_bolt11_features(invoice_features).unwrap();
2574         let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2575
2576         let chans = nodes[0].node.list_usable_channels();
2577         let mut route = Route {
2578                 paths: vec![
2579                         Path { hops: vec![RouteHop {
2580                                 pubkey: nodes[1].node.get_our_node_id(),
2581                                 node_features: nodes[1].node.node_features(),
2582                                 short_channel_id: chans[0].short_channel_id.unwrap(),
2583                                 channel_features: nodes[1].node.channel_features(),
2584                                 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2585                                 cltv_expiry_delta: 100,
2586                                 maybe_announced_channel: true,
2587                         }], blinded_tail: None },
2588                 ],
2589                 route_params: Some(RouteParameters::from_payment_params_and_value(
2590                         PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV),
2591                         100_000_001)),
2592         };
2593         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2594         // On retry, split the payment across both channels.
2595         route.paths.push(route.paths[0].clone());
2596         route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2597         route.paths[0].hops[0].fee_msat = 50_000_000;
2598         route.paths[1].hops[0].fee_msat = 50_000_001;
2599         let mut pay_params = route_params.payment_params.clone();
2600         pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2601         nodes[0].router.expect_find_route(
2602                 RouteParameters::from_payment_params_and_value(pay_params, amt_msat),
2603                 Ok(route.clone()));
2604
2605         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2606                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2607         let events = nodes[0].node.get_and_clear_pending_events();
2608         assert_eq!(events.len(), 1);
2609         match events[0] {
2610                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2611                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2612                         short_channel_id: Some(expected_scid), .. } =>
2613                 {
2614                         assert_eq!(payment_hash, ev_payment_hash);
2615                         assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2616                 },
2617                 _ => panic!("Unexpected event"),
2618         }
2619         let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2620         assert_eq!(htlc_msgs.len(), 2);
2621         check_added_monitors!(nodes[0], 2);
2622 }
2623
2624 #[test]
2625 fn no_extra_retries_on_back_to_back_fail() {
2626         // In a previous release, we had a race where we may exceed the payment retry count if we
2627         // get two failures in a row with the second indicating that all paths had failed (this field,
2628         // `all_paths_failed`, has since been removed).
2629         // Generally, when we give up trying to retry a payment, we don't know for sure what the
2630         // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2631         // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2632         // pending which we will see later. Thus, when we previously removed the retry tracking map
2633         // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2634         // retry entry even though more events for the same payment were still pending. This led to
2635         // us retrying a payment again even though we'd already given up on it.
2636         //
2637         // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2638         // is used to remove the payment retry counter entries instead. This tests for the specific
2639         // excess-retry case while also testing `PaymentFailed` generation.
2640
2641         let chanmon_cfgs = create_chanmon_cfgs(3);
2642         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2643         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2644         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2645
2646         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2647         let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2648
2649         let amt_msat = 200_000_000;
2650         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2651         #[cfg(feature = "std")]
2652         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2653         #[cfg(not(feature = "std"))]
2654         let payment_expiry_secs = 60 * 60;
2655         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2656         invoice_features.set_variable_length_onion_required();
2657         invoice_features.set_payment_secret_required();
2658         invoice_features.set_basic_mpp_optional();
2659         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2660                 .with_expiry_time(payment_expiry_secs as u64)
2661                 .with_bolt11_features(invoice_features).unwrap();
2662         let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2663
2664         let mut route = Route {
2665                 paths: vec![
2666                         Path { hops: vec![RouteHop {
2667                                 pubkey: nodes[1].node.get_our_node_id(),
2668                                 node_features: nodes[1].node.node_features(),
2669                                 short_channel_id: chan_1_scid,
2670                                 channel_features: nodes[1].node.channel_features(),
2671                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2672                                 cltv_expiry_delta: 100,
2673                                 maybe_announced_channel: true,
2674                         }, RouteHop {
2675                                 pubkey: nodes[2].node.get_our_node_id(),
2676                                 node_features: nodes[2].node.node_features(),
2677                                 short_channel_id: chan_2_scid,
2678                                 channel_features: nodes[2].node.channel_features(),
2679                                 fee_msat: 100_000_000,
2680                                 cltv_expiry_delta: 100,
2681                                 maybe_announced_channel: true,
2682                         }], blinded_tail: None },
2683                         Path { hops: vec![RouteHop {
2684                                 pubkey: nodes[1].node.get_our_node_id(),
2685                                 node_features: nodes[1].node.node_features(),
2686                                 short_channel_id: chan_1_scid,
2687                                 channel_features: nodes[1].node.channel_features(),
2688                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2689                                 cltv_expiry_delta: 100,
2690                                 maybe_announced_channel: true,
2691                         }, RouteHop {
2692                                 pubkey: nodes[2].node.get_our_node_id(),
2693                                 node_features: nodes[2].node.node_features(),
2694                                 short_channel_id: chan_2_scid,
2695                                 channel_features: nodes[2].node.channel_features(),
2696                                 fee_msat: 100_000_000,
2697                                 cltv_expiry_delta: 100,
2698                                 maybe_announced_channel: true,
2699                         }], blinded_tail: None }
2700                 ],
2701                 route_params: Some(RouteParameters::from_payment_params_and_value(
2702                         PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV),
2703                         100_000_000)),
2704         };
2705         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2706         let mut second_payment_params = route_params.payment_params.clone();
2707         second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2708         // On retry, we'll only return one path
2709         route.paths.remove(1);
2710         route.paths[0].hops[1].fee_msat = amt_msat;
2711         nodes[0].router.expect_find_route(
2712                 RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat),
2713                 Ok(route.clone()));
2714
2715         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2716                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2717         let htlc_updates = SendEvent::from_node(&nodes[0]);
2718         check_added_monitors!(nodes[0], 1);
2719         assert_eq!(htlc_updates.msgs.len(), 1);
2720
2721         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2722         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2723         check_added_monitors!(nodes[1], 1);
2724         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2725
2726         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2727         check_added_monitors!(nodes[0], 1);
2728         let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2729
2730         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2731         check_added_monitors!(nodes[0], 1);
2732         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2733
2734         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2735         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2736         check_added_monitors!(nodes[1], 1);
2737         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2738
2739         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2740         check_added_monitors!(nodes[1], 1);
2741         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2742
2743         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2744         check_added_monitors!(nodes[0], 1);
2745
2746         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2747         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2748         check_added_monitors!(nodes[0], 1);
2749         let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2750
2751         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2752         check_added_monitors!(nodes[1], 1);
2753         let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2754
2755         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2756         check_added_monitors!(nodes[1], 1);
2757         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2758
2759         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2760         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2761         check_added_monitors!(nodes[0], 1);
2762
2763         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2764         check_added_monitors!(nodes[0], 1);
2765         let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2766
2767         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2768         check_added_monitors!(nodes[1], 1);
2769         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2770         check_added_monitors!(nodes[1], 1);
2771         let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2772
2773         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2774         check_added_monitors!(nodes[0], 1);
2775
2776         // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2777         // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2778         // with it set.
2779         //
2780         // Previously, we retried payments in an event consumer, which would retry each
2781         // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2782         // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2783         // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2784         // by adding the `PaymentFailed` event.
2785         //
2786         // Because we now retry payments as a batch, we simply return a single-path route in the
2787         // second, batched, request, have that fail, ensure the payment was abandoned.
2788         let mut events = nodes[0].node.get_and_clear_pending_events();
2789         assert_eq!(events.len(), 3);
2790         match events[0] {
2791                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2792                         assert_eq!(payment_hash, ev_payment_hash);
2793                         assert_eq!(payment_failed_permanently, false);
2794                 },
2795                 _ => panic!("Unexpected event"),
2796         }
2797         match events[1] {
2798                 Event::PendingHTLCsForwardable { .. } => {},
2799                 _ => panic!("Unexpected event"),
2800         }
2801         match events[2] {
2802                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2803                         assert_eq!(payment_hash, ev_payment_hash);
2804                         assert_eq!(payment_failed_permanently, false);
2805                 },
2806                 _ => panic!("Unexpected event"),
2807         }
2808
2809         nodes[0].node.process_pending_htlc_forwards();
2810         let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2811         check_added_monitors!(nodes[0], 1);
2812
2813         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2814         commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2815         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2816         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2817         commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2818
2819         let mut events = nodes[0].node.get_and_clear_pending_events();
2820         assert_eq!(events.len(), 2);
2821         match events[0] {
2822                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2823                         assert_eq!(payment_hash, ev_payment_hash);
2824                         assert_eq!(payment_failed_permanently, false);
2825                 },
2826                 _ => panic!("Unexpected event"),
2827         }
2828         match events[1] {
2829                 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2830                         assert_eq!(payment_hash, *ev_payment_hash);
2831                         assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2832                         assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2833                 },
2834                 _ => panic!("Unexpected event"),
2835         }
2836 }
2837
2838 #[test]
2839 fn test_simple_partial_retry() {
2840         // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2841         // full amount of the payment, rather than only the missing amount. Here we simply test for
2842         // this by sending a payment with two parts, failing one, and retrying the second. Note that
2843         // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2844         // request.
2845         let chanmon_cfgs = create_chanmon_cfgs(3);
2846         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2847         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2848         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2849
2850         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2851         let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2852
2853         let amt_msat = 200_000_000;
2854         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2855         #[cfg(feature = "std")]
2856         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2857         #[cfg(not(feature = "std"))]
2858         let payment_expiry_secs = 60 * 60;
2859         let mut invoice_features = Bolt11InvoiceFeatures::empty();
2860         invoice_features.set_variable_length_onion_required();
2861         invoice_features.set_payment_secret_required();
2862         invoice_features.set_basic_mpp_optional();
2863         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2864                 .with_expiry_time(payment_expiry_secs as u64)
2865                 .with_bolt11_features(invoice_features).unwrap();
2866         let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2867
2868         let mut route = Route {
2869                 paths: vec![
2870                         Path { hops: vec![RouteHop {
2871                                 pubkey: nodes[1].node.get_our_node_id(),
2872                                 node_features: nodes[1].node.node_features(),
2873                                 short_channel_id: chan_1_scid,
2874                                 channel_features: nodes[1].node.channel_features(),
2875                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2876                                 cltv_expiry_delta: 100,
2877                                 maybe_announced_channel: true,
2878                         }, RouteHop {
2879                                 pubkey: nodes[2].node.get_our_node_id(),
2880                                 node_features: nodes[2].node.node_features(),
2881                                 short_channel_id: chan_2_scid,
2882                                 channel_features: nodes[2].node.channel_features(),
2883                                 fee_msat: 100_000_000,
2884                                 cltv_expiry_delta: 100,
2885                                 maybe_announced_channel: true,
2886                         }], blinded_tail: None },
2887                         Path { hops: vec![RouteHop {
2888                                 pubkey: nodes[1].node.get_our_node_id(),
2889                                 node_features: nodes[1].node.node_features(),
2890                                 short_channel_id: chan_1_scid,
2891                                 channel_features: nodes[1].node.channel_features(),
2892                                 fee_msat: 100_000,
2893                                 cltv_expiry_delta: 100,
2894                                 maybe_announced_channel: true,
2895                         }, RouteHop {
2896                                 pubkey: nodes[2].node.get_our_node_id(),
2897                                 node_features: nodes[2].node.node_features(),
2898                                 short_channel_id: chan_2_scid,
2899                                 channel_features: nodes[2].node.channel_features(),
2900                                 fee_msat: 100_000_000,
2901                                 cltv_expiry_delta: 100,
2902                                 maybe_announced_channel: true,
2903                         }], blinded_tail: None }
2904                 ],
2905                 route_params: Some(RouteParameters::from_payment_params_and_value(
2906                         PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV),
2907                         100_000_000)),
2908         };
2909         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2910         let mut second_payment_params = route_params.payment_params.clone();
2911         second_payment_params.previously_failed_channels = vec![chan_2_scid];
2912         // On retry, we'll only be asked for one path (or 100k sats)
2913         route.paths.remove(0);
2914         nodes[0].router.expect_find_route(
2915                 RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat / 2),
2916                 Ok(route.clone()));
2917
2918         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2919                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2920         let htlc_updates = SendEvent::from_node(&nodes[0]);
2921         check_added_monitors!(nodes[0], 1);
2922         assert_eq!(htlc_updates.msgs.len(), 1);
2923
2924         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2925         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2926         check_added_monitors!(nodes[1], 1);
2927         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2928
2929         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2930         check_added_monitors!(nodes[0], 1);
2931         let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2932
2933         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2934         check_added_monitors!(nodes[0], 1);
2935         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2936
2937         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2938         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2939         check_added_monitors!(nodes[1], 1);
2940         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2941
2942         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2943         check_added_monitors!(nodes[1], 1);
2944         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2945
2946         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2947         check_added_monitors!(nodes[0], 1);
2948
2949         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2950         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2951         check_added_monitors!(nodes[0], 1);
2952         let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2953
2954         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2955         check_added_monitors!(nodes[1], 1);
2956
2957         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2958         check_added_monitors!(nodes[1], 1);
2959
2960         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2961
2962         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2963         check_added_monitors!(nodes[0], 1);
2964
2965         let mut events = nodes[0].node.get_and_clear_pending_events();
2966         assert_eq!(events.len(), 2);
2967         match events[0] {
2968                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2969                         assert_eq!(payment_hash, ev_payment_hash);
2970                         assert_eq!(payment_failed_permanently, false);
2971                 },
2972                 _ => panic!("Unexpected event"),
2973         }
2974         match events[1] {
2975                 Event::PendingHTLCsForwardable { .. } => {},
2976                 _ => panic!("Unexpected event"),
2977         }
2978
2979         nodes[0].node.process_pending_htlc_forwards();
2980         let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2981         check_added_monitors!(nodes[0], 1);
2982
2983         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2984         commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2985
2986         expect_pending_htlcs_forwardable!(nodes[1]);
2987         check_added_monitors!(nodes[1], 1);
2988
2989         let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2990         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2991         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2992         commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2993
2994         expect_pending_htlcs_forwardable!(nodes[2]);
2995         expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2996 }
2997
2998 #[test]
2999 #[cfg(feature = "std")]
3000 fn test_threaded_payment_retries() {
3001         // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
3002         // a single thread and would happily let multiple threads run retries at the same time. Because
3003         // retries are done by first calculating the amount we need to retry, then dropping the
3004         // relevant lock, then actually sending, we would happily let multiple threads retry the same
3005         // amount at the same time, overpaying our original HTLC!
3006         let chanmon_cfgs = create_chanmon_cfgs(4);
3007         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3008         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3009         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3010
3011         // There is one mitigating guardrail when retrying payments - we can never over-pay by more
3012         // than 10% of the original value. Thus, we want all our retries to be below that. In order to
3013         // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
3014         // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
3015         // our channel.
3016         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3017         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
3018         let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
3019         let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
3020
3021         let amt_msat = 100_000_000;
3022         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3023         #[cfg(feature = "std")]
3024         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3025         #[cfg(not(feature = "std"))]
3026         let payment_expiry_secs = 60 * 60;
3027         let mut invoice_features = Bolt11InvoiceFeatures::empty();
3028         invoice_features.set_variable_length_onion_required();
3029         invoice_features.set_payment_secret_required();
3030         invoice_features.set_basic_mpp_optional();
3031         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3032                 .with_expiry_time(payment_expiry_secs as u64)
3033                 .with_bolt11_features(invoice_features).unwrap();
3034         let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
3035
3036         let mut route = Route {
3037                 paths: vec![
3038                         Path { hops: vec![RouteHop {
3039                                 pubkey: nodes[1].node.get_our_node_id(),
3040                                 node_features: nodes[1].node.node_features(),
3041                                 short_channel_id: chan_1_scid,
3042                                 channel_features: nodes[1].node.channel_features(),
3043                                 fee_msat: 0,
3044                                 cltv_expiry_delta: 100,
3045                                 maybe_announced_channel: true,
3046                         }, RouteHop {
3047                                 pubkey: nodes[3].node.get_our_node_id(),
3048                                 node_features: nodes[2].node.node_features(),
3049                                 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3050                                 channel_features: nodes[2].node.channel_features(),
3051                                 fee_msat: amt_msat / 1000,
3052                                 cltv_expiry_delta: 100,
3053                                 maybe_announced_channel: true,
3054                         }], blinded_tail: None },
3055                         Path { hops: vec![RouteHop {
3056                                 pubkey: nodes[2].node.get_our_node_id(),
3057                                 node_features: nodes[2].node.node_features(),
3058                                 short_channel_id: chan_3_scid,
3059                                 channel_features: nodes[2].node.channel_features(),
3060                                 fee_msat: 100_000,
3061                                 cltv_expiry_delta: 100,
3062                                 maybe_announced_channel: true,
3063                         }, RouteHop {
3064                                 pubkey: nodes[3].node.get_our_node_id(),
3065                                 node_features: nodes[3].node.node_features(),
3066                                 short_channel_id: chan_4_scid,
3067                                 channel_features: nodes[3].node.channel_features(),
3068                                 fee_msat: amt_msat - amt_msat / 1000,
3069                                 cltv_expiry_delta: 100,
3070                                 maybe_announced_channel: true,
3071                         }], blinded_tail: None }
3072                 ],
3073                 route_params: Some(RouteParameters::from_payment_params_and_value(
3074                         PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV),
3075                         amt_msat - amt_msat / 1000)),
3076         };
3077         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3078
3079         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3080                 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3081         check_added_monitors!(nodes[0], 2);
3082         let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3083         assert_eq!(send_msg_events.len(), 2);
3084         send_msg_events.retain(|msg|
3085                 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3086                         // Drop the commitment update for nodes[2], we can just let that one sit pending
3087                         // forever.
3088                         *node_id == nodes[1].node.get_our_node_id()
3089                 } else { panic!(); }
3090         );
3091
3092         // from here on out, the retry `RouteParameters` amount will be amt/1000
3093         route_params.final_value_msat /= 1000;
3094         route.paths.pop();
3095
3096         let end_time = Instant::now() + Duration::from_secs(1);
3097         macro_rules! thread_body { () => { {
3098                 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3099                 let node_ref = NodePtr::from_node(&nodes[0]);
3100                 move || {
3101                         let node_a = unsafe { &*node_ref.0 };
3102                         while Instant::now() < end_time {
3103                                 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3104                                 // Ignore if we have any pending events, just always pretend we just got a
3105                                 // PendingHTLCsForwardable
3106                                 node_a.node.process_pending_htlc_forwards();
3107                         }
3108                 }
3109         } } }
3110         let mut threads = Vec::new();
3111         for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3112
3113         // Back in the main thread, poll pending messages and make sure that we never have more than
3114         // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3115         // there are HTLC messages shoved in while its running. This allows us to test that we never
3116         // generate an additional update_add_htlc until we've fully failed the first.
3117         let mut previously_failed_channels = Vec::new();
3118         loop {
3119                 assert_eq!(send_msg_events.len(), 1);
3120                 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3121                 assert_eq!(send_event.msgs.len(), 1);
3122
3123                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3124                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3125
3126                 // Note that we only push one route into `expect_find_route` at a time, because that's all
3127                 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3128                 // we should still ultimately fail for the same reason - because we're trying to send too
3129                 // many HTLCs at once.
3130                 let mut new_route_params = route_params.clone();
3131                 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3132                 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3133                 route.paths[0].hops[1].short_channel_id += 1;
3134                 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3135
3136                 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3137                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3138                 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3139                 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3140                 // This races with our other threads which may generate an add-HTLCs commitment update via
3141                 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3142                 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3143                 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3144                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3145
3146                 let cur_time = Instant::now();
3147                 if cur_time > end_time {
3148                         for thread in threads.drain(..) { thread.join().unwrap(); }
3149                 }
3150
3151                 // Make sure we have some events to handle when we go around...
3152                 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3153                 nodes[0].node.process_pending_htlc_forwards();
3154                 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3155                 check_added_monitors!(nodes[0], 2);
3156
3157                 if cur_time > end_time {
3158                         break;
3159                 }
3160         }
3161 }
3162
3163 fn do_no_missing_sent_on_reload(persist_manager_with_payment: bool, at_midpoint: bool) {
3164         // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3165         // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3166         // it was last persisted.
3167         let chanmon_cfgs = create_chanmon_cfgs(2);
3168         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3169         let (persister_a, persister_b, persister_c);
3170         let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3171         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3172         let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3173         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3174
3175         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3176
3177         let mut nodes_0_serialized = Vec::new();
3178         if !persist_manager_with_payment {
3179                 nodes_0_serialized = nodes[0].node.encode();
3180         }
3181
3182         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3183
3184         if persist_manager_with_payment {
3185                 nodes_0_serialized = nodes[0].node.encode();
3186         }
3187
3188         nodes[1].node.claim_funds(our_payment_preimage);
3189         check_added_monitors!(nodes[1], 1);
3190         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3191
3192         if at_midpoint {
3193                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3194                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3195                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3196                 check_added_monitors!(nodes[0], 1);
3197         } else {
3198                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3199                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
3200                 commitment_signed_dance!(nodes[0], nodes[1], htlc_fulfill_updates.commitment_signed, false);
3201                 // Ignore the PaymentSent event which is now pending on nodes[0] - if we were to handle it we'd
3202                 // be expected to ignore the eventual conflicting PaymentFailed, but by not looking at it we
3203                 // expect to get the PaymentSent again later.
3204                 check_added_monitors(&nodes[0], 0);
3205         }
3206
3207         // The ChannelMonitor should always be the latest version, as we're required to persist it
3208         // during the commitment signed handling.
3209         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3210         reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3211
3212         let events = nodes[0].node.get_and_clear_pending_events();
3213         assert_eq!(events.len(), 2);
3214         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3215         if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3216         // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3217         // the double-claim that would otherwise appear at the end of this test.
3218         nodes[0].node.timer_tick_occurred();
3219         let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3220         assert_eq!(as_broadcasted_txn.len(), 1);
3221
3222         // Ensure that, even after some time, if we restart we still include *something* in the current
3223         // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3224         // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3225         // A naive implementation of the fix here would wipe the pending payments set, causing a
3226         // failure event when we restart.
3227         for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3228
3229         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3230         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);
3231         let events = nodes[0].node.get_and_clear_pending_events();
3232         assert!(events.is_empty());
3233
3234         // Ensure that we don't generate any further events even after the channel-closing commitment
3235         // transaction is confirmed on-chain.
3236         confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3237         for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3238
3239         let events = nodes[0].node.get_and_clear_pending_events();
3240         assert!(events.is_empty());
3241
3242         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3243         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);
3244         let events = nodes[0].node.get_and_clear_pending_events();
3245         assert!(events.is_empty());
3246         check_added_monitors(&nodes[0], 1);
3247 }
3248
3249 #[test]
3250 fn no_missing_sent_on_midpoint_reload() {
3251         do_no_missing_sent_on_reload(false, true);
3252         do_no_missing_sent_on_reload(true, true);
3253 }
3254
3255 #[test]
3256 fn no_missing_sent_on_reload() {
3257         do_no_missing_sent_on_reload(false, false);
3258         do_no_missing_sent_on_reload(true, false);
3259 }
3260
3261 fn do_claim_from_closed_chan(fail_payment: bool) {
3262         // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3263         // received had been closed between when the HTLC was received and when we went to claim it.
3264         // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3265         // presumably the sender may retry later. Long ago it also reduced total code in the claim
3266         // pipeline.
3267         //
3268         // However, this doesn't make sense if you're trying to do an atomic swap or some other
3269         // protocol that requires atomicity with some other action - if your money got claimed
3270         // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3271         // is an over-optimization - there should be a very, very low likelihood that a channel closes
3272         // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3273         // Since we now have code to handle this anyway we should allow it.
3274
3275         // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3276         // CLTVs on the paths to different value resulting in a different claim deadline.
3277         let chanmon_cfgs = create_chanmon_cfgs(4);
3278         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3279         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3280         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3281
3282         create_announced_chan_between_nodes(&nodes, 0, 1);
3283         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3284         let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3285         create_announced_chan_between_nodes(&nodes, 2, 3);
3286
3287         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3288         let mut route_params = RouteParameters::from_payment_params_and_value(
3289                 PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3290                         .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
3291                 10_000_000);
3292         let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3293                 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3294         // Make sure the route is ordered as the B->D path before C->D
3295         route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3296                 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3297
3298         // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3299         // the HTLC is being relayed.
3300         route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3301         route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3302         let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3303
3304         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3305         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3306                 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3307         check_added_monitors(&nodes[0], 2);
3308         let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3309         send_msgs.sort_by(|a, _| {
3310                 let a_node_id =
3311                         if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3312                 let node_b_id = nodes[1].node.get_our_node_id();
3313                 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3314         });
3315
3316         assert_eq!(send_msgs.len(), 2);
3317         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3318                 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3319         let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3320                 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3321
3322         match receive_event.unwrap() {
3323                 Event::PaymentClaimable { claim_deadline, .. } => {
3324                         assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3325                 },
3326                 _ => panic!(),
3327         }
3328
3329         // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3330         // height.
3331         connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3332                 - if fail_payment { 0 } else { 2 });
3333         if fail_payment {
3334                 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3335                 // and expire both immediately, though, by connecting another 4 blocks.
3336                 let reason = HTLCDestination::FailedPayment { payment_hash };
3337                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3338                 connect_blocks(&nodes[3], 4);
3339                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3340                 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3341         } else {
3342                 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3343                 check_closed_event!(&nodes[1], 1, ClosureReason::HolderForceClosed, false,
3344                         [nodes[3].node.get_our_node_id()], 1000000);
3345                 check_closed_broadcast(&nodes[1], 1, true);
3346                 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3347                 assert_eq!(bs_tx.len(), 1);
3348
3349                 mine_transaction(&nodes[3], &bs_tx[0]);
3350                 check_added_monitors(&nodes[3], 1);
3351                 check_closed_broadcast(&nodes[3], 1, true);
3352                 check_closed_event!(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false,
3353                         [nodes[1].node.get_our_node_id()], 1000000);
3354
3355                 nodes[3].node.claim_funds(payment_preimage);
3356                 check_added_monitors(&nodes[3], 2);
3357                 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3358
3359                 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3360                 assert_eq!(ds_tx.len(), 1);
3361                 check_spends!(&ds_tx[0], &bs_tx[0]);
3362
3363                 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3364                 check_added_monitors(&nodes[1], 1);
3365                 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3366
3367                 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3368                 check_added_monitors(&nodes[1], 1);
3369                 assert_eq!(bs_claims.len(), 1);
3370                 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3371                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3372                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3373                 } else { panic!(); }
3374
3375                 expect_payment_sent!(nodes[0], payment_preimage);
3376
3377                 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3378                 assert_eq!(ds_claim_msgs.len(), 1);
3379                 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3380                         nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3381                         let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3382                         check_added_monitors(&nodes[2], 1);
3383                         commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3384                         expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3385                         cs_claim_msgs
3386                 } else { panic!(); };
3387
3388                 assert_eq!(cs_claim_msgs.len(), 1);
3389                 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3390                         nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3391                         commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3392                 } else { panic!(); }
3393
3394                 expect_payment_path_successful!(nodes[0]);
3395         }
3396 }
3397
3398 #[test]
3399 fn claim_from_closed_chan() {
3400         do_claim_from_closed_chan(true);
3401         do_claim_from_closed_chan(false);
3402 }
3403
3404 #[test]
3405 fn test_custom_tlvs_basic() {
3406         do_test_custom_tlvs(false, false, false);
3407         do_test_custom_tlvs(true, false, false);
3408 }
3409
3410 #[test]
3411 fn test_custom_tlvs_explicit_claim() {
3412         // Test that when receiving even custom TLVs the user must explicitly accept in case they
3413         // are unknown.
3414         do_test_custom_tlvs(false, true, false);
3415         do_test_custom_tlvs(false, true, true);
3416 }
3417
3418 fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) {
3419         let chanmon_cfgs = create_chanmon_cfgs(2);
3420         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3421         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None; 2]);
3422         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3423
3424         create_announced_chan_between_nodes(&nodes, 0, 1);
3425
3426         let amt_msat = 100_000;
3427         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat);
3428         let payment_id = PaymentId(our_payment_hash.0);
3429         let custom_tlvs = vec![
3430                 (if even_tlvs { 5482373482 } else { 5482373483 }, vec![1, 2, 3, 4]),
3431                 (5482373487, vec![0x42u8; 16]),
3432         ];
3433         let onion_fields = RecipientOnionFields {
3434                 payment_secret: if spontaneous { None } else { Some(our_payment_secret) },
3435                 payment_metadata: None,
3436                 custom_tlvs: custom_tlvs.clone()
3437         };
3438         if spontaneous {
3439                 nodes[0].node.send_spontaneous_payment(&route, Some(our_payment_preimage), onion_fields, payment_id).unwrap();
3440         } else {
3441                 nodes[0].node.send_payment_with_route(&route, our_payment_hash, onion_fields, payment_id).unwrap();
3442         }
3443         check_added_monitors(&nodes[0], 1);
3444
3445         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3446         let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
3447         let mut payment_event = SendEvent::from_event(ev);
3448
3449         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3450         check_added_monitors!(&nodes[1], 0);
3451         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3452         expect_pending_htlcs_forwardable!(nodes[1]);
3453
3454         let events = nodes[1].node.get_and_clear_pending_events();
3455         assert_eq!(events.len(), 1);
3456         match events[0] {
3457                 Event::PaymentClaimable { ref onion_fields, .. } => {
3458                         assert_eq!(onion_fields.clone().unwrap().custom_tlvs().clone(), custom_tlvs);
3459                 },
3460                 _ => panic!("Unexpected event"),
3461         }
3462
3463         match (known_tlvs, even_tlvs) {
3464                 (true, _) => {
3465                         nodes[1].node.claim_funds_with_known_custom_tlvs(our_payment_preimage);
3466                         let expected_total_fee_msat = pass_claimed_payment_along_route(&nodes[0], &[&[&nodes[1]]], &[0; 1], false, our_payment_preimage);
3467                         expect_payment_sent!(&nodes[0], our_payment_preimage, Some(expected_total_fee_msat));
3468                 },
3469                 (false, false) => {
3470                         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3471                 },
3472                 (false, true) => {
3473                         nodes[1].node.claim_funds(our_payment_preimage);
3474                         let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3475                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], expected_destinations);
3476                         pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, our_payment_hash, PaymentFailureReason::RecipientRejected);
3477                 }
3478         }
3479 }
3480
3481 #[test]
3482 fn test_retry_custom_tlvs() {
3483         // Test that custom TLVs are successfully sent on retries
3484         let chanmon_cfgs = create_chanmon_cfgs(3);
3485         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3486         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3487         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3488
3489         create_announced_chan_between_nodes(&nodes, 0, 1);
3490         let (chan_2_update, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 2, 1);
3491
3492         // Rebalance
3493         send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3494
3495         let amt_msat = 1_000_000;
3496         let (route, payment_hash, payment_preimage, payment_secret) =
3497                 get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
3498
3499         // Initiate the payment
3500         let payment_id = PaymentId(payment_hash.0);
3501         let mut route_params = route.route_params.clone().unwrap();
3502
3503         let custom_tlvs = vec![((1 << 16) + 1, vec![0x42u8; 16])];
3504         let onion_fields = RecipientOnionFields::secret_only(payment_secret);
3505         let onion_fields = onion_fields.with_custom_tlvs(custom_tlvs.clone()).unwrap();
3506
3507         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3508         nodes[0].node.send_payment(payment_hash, onion_fields,
3509                 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3510         check_added_monitors!(nodes[0], 1); // one monitor per path
3511
3512         // Add the HTLC along the first hop.
3513         let htlc_updates = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
3514         let msgs::CommitmentUpdate { update_add_htlcs, commitment_signed, .. } = htlc_updates;
3515         assert_eq!(update_add_htlcs.len(), 1);
3516         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_htlcs[0]);
3517         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
3518
3519         // Attempt to forward the payment and complete the path's failure.
3520         expect_pending_htlcs_forwardable!(&nodes[1]);
3521         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1],
3522                 vec![HTLCDestination::NextHopChannel {
3523                         node_id: Some(nodes[2].node.get_our_node_id()),
3524                         channel_id: chan_2_id
3525                 }]);
3526         check_added_monitors!(nodes[1], 1);
3527
3528         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3529         let msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } = htlc_updates;
3530         assert_eq!(update_fail_htlcs.len(), 1);
3531         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3532         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
3533
3534         let mut events = nodes[0].node.get_and_clear_pending_events();
3535         match events[1] {
3536                 Event::PendingHTLCsForwardable { .. } => {},
3537                 _ => panic!("Unexpected event")
3538         }
3539         events.remove(1);
3540         expect_payment_failed_conditions_event(events, payment_hash, false,
3541                 PaymentFailedConditions::new().mpp_parts_remain());
3542
3543         // Rebalance the channel so the retry of the payment can succeed.
3544         send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3545
3546         // Retry the payment and make sure it succeeds
3547         route_params.payment_params.previously_failed_channels.push(chan_2_update.contents.short_channel_id);
3548         nodes[0].router.expect_find_route(route_params, Ok(route));
3549         nodes[0].node.process_pending_htlc_forwards();
3550         check_added_monitors!(nodes[0], 1);
3551         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3552         assert_eq!(events.len(), 1);
3553         let payment_claimable = pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000,
3554                 payment_hash, Some(payment_secret), events.pop().unwrap(), true, None).unwrap();
3555         match payment_claimable {
3556                 Event::PaymentClaimable { onion_fields, .. } => {
3557                         assert_eq!(onion_fields.unwrap().custom_tlvs(), &custom_tlvs);
3558                 },
3559                 _ => panic!("Unexpected event"),
3560         };
3561         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
3562 }
3563
3564 #[test]
3565 fn test_custom_tlvs_consistency() {
3566         let even_type_1 = 1 << 16;
3567         let odd_type_1  = (1 << 16)+ 1;
3568         let even_type_2 = (1 << 16) + 2;
3569         let odd_type_2  = (1 << 16) + 3;
3570         let value_1 = || vec![1, 2, 3, 4];
3571         let differing_value_1 = || vec![1, 2, 3, 5];
3572         let value_2 = || vec![42u8; 16];
3573
3574         // Drop missing odd tlvs
3575         do_test_custom_tlvs_consistency(
3576                 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3577                 vec![(odd_type_1, value_1())],
3578                 Some(vec![(odd_type_1, value_1())]),
3579         );
3580         // Drop non-matching odd tlvs
3581         do_test_custom_tlvs_consistency(
3582                 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3583                 vec![(odd_type_1, differing_value_1()), (odd_type_2, value_2())],
3584                 Some(vec![(odd_type_2, value_2())]),
3585         );
3586         // Fail missing even tlvs
3587         do_test_custom_tlvs_consistency(
3588                 vec![(odd_type_1, value_1()), (even_type_2, value_2())],
3589                 vec![(odd_type_1, value_1())],
3590                 None,
3591         );
3592         // Fail non-matching even tlvs
3593         do_test_custom_tlvs_consistency(
3594                 vec![(even_type_1, value_1()), (odd_type_2, value_2())],
3595                 vec![(even_type_1, differing_value_1()), (odd_type_2, value_2())],
3596                 None,
3597         );
3598 }
3599
3600 fn do_test_custom_tlvs_consistency(first_tlvs: Vec<(u64, Vec<u8>)>, second_tlvs: Vec<(u64, Vec<u8>)>,
3601         expected_receive_tlvs: Option<Vec<(u64, Vec<u8>)>>) {
3602
3603         let chanmon_cfgs = create_chanmon_cfgs(4);
3604         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3605         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3606         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3607
3608         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
3609         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
3610         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
3611         let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
3612
3613         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3614                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
3615         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
3616         assert_eq!(route.paths.len(), 2);
3617         route.paths.sort_by(|path_a, _| {
3618                 // Sort the path so that the path through nodes[1] comes first
3619                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3620                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
3621         });
3622
3623         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
3624         let payment_id = PaymentId([42; 32]);
3625         let amt_msat = 15_000_000;
3626
3627         // Send first part
3628         let onion_fields = RecipientOnionFields {
3629                 payment_secret: Some(our_payment_secret),
3630                 payment_metadata: None,
3631                 custom_tlvs: first_tlvs
3632         };
3633         let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
3634                         onion_fields.clone(), payment_id, &route).unwrap();
3635         let cur_height = nodes[0].best_block_info().1;
3636         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
3637                 onion_fields.clone(), amt_msat, cur_height, payment_id,
3638                 &None, session_privs[0]).unwrap();
3639         check_added_monitors!(nodes[0], 1);
3640
3641         {
3642                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3643                 assert_eq!(events.len(), 1);
3644                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, our_payment_hash,
3645                         Some(our_payment_secret), events.pop().unwrap(), false, None);
3646         }
3647         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
3648
3649         // Send second part
3650         let onion_fields = RecipientOnionFields {
3651                 payment_secret: Some(our_payment_secret),
3652                 payment_metadata: None,
3653                 custom_tlvs: second_tlvs
3654         };
3655         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
3656                 onion_fields.clone(), amt_msat, cur_height, payment_id, &None, session_privs[1]).unwrap();
3657         check_added_monitors!(nodes[0], 1);
3658
3659         {
3660                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3661                 assert_eq!(events.len(), 1);
3662                 let payment_event = SendEvent::from_event(events.pop().unwrap());
3663
3664                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3665                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
3666
3667                 expect_pending_htlcs_forwardable!(nodes[2]);
3668                 check_added_monitors!(nodes[2], 1);
3669
3670                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
3671                 assert_eq!(events.len(), 1);
3672                 let payment_event = SendEvent::from_event(events.pop().unwrap());
3673
3674                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
3675                 check_added_monitors!(nodes[3], 0);
3676                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
3677         }
3678         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3679         nodes[3].node.process_pending_htlc_forwards();
3680
3681         if let Some(expected_tlvs) = expected_receive_tlvs {
3682                 // Claim and match expected
3683                 let events = nodes[3].node.get_and_clear_pending_events();
3684                 assert_eq!(events.len(), 1);
3685                 match events[0] {
3686                         Event::PaymentClaimable { ref onion_fields, .. } => {
3687                                 assert_eq!(onion_fields.clone().unwrap().custom_tlvs, expected_tlvs);
3688                         },
3689                         _ => panic!("Unexpected event"),
3690                 }
3691
3692                 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]],
3693                         false, our_payment_preimage);
3694                 expect_payment_sent(&nodes[0], our_payment_preimage, Some(Some(2000)), true, true);
3695         } else {
3696                 // Expect fail back
3697                 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3698                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], expected_destinations);
3699                 check_added_monitors!(nodes[3], 1);
3700
3701                 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
3702                 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
3703                 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
3704
3705                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![
3706                         HTLCDestination::NextHopChannel {
3707                                 node_id: Some(nodes[3].node.get_our_node_id()),
3708                                 channel_id: chan_2_3.2
3709                         }]);
3710                 check_added_monitors!(nodes[2], 1);
3711
3712                 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
3713                 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
3714                 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
3715
3716                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true,
3717                         PaymentFailedConditions::new().mpp_parts_remain());
3718         }
3719 }
3720
3721 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3722         // Check that a payment metadata received on one HTLC that doesn't match the one received on
3723         // another results in the HTLC being rejected.
3724         //
3725         // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3726         // first of which we'll deliver and the second of which we'll fail and then re-send with
3727         // modified payment metadata, which will in turn result in it being failed by the recipient.
3728         let chanmon_cfgs = create_chanmon_cfgs(4);
3729         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3730         let persister;
3731         let new_chain_monitor;
3732
3733         let mut config = test_default_channel_config();
3734         config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3735         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3736         let nodes_0_deserialized;
3737
3738         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3739
3740         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3741         let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3742         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3743         let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3744
3745         // Pay more than half of each channel's max, requiring MPP
3746         let amt_msat = 750_000_000;
3747         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3748         let payment_id = PaymentId(payment_hash.0);
3749         let payment_metadata = vec![44, 49, 52, 142];
3750
3751         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3752                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3753         let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
3754
3755         // Send the MPP payment, delivering the updated commitment state to nodes[1].
3756         nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3757                         payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata), custom_tlvs: vec![],
3758                 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3759         check_added_monitors!(nodes[0], 2);
3760
3761         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3762         assert_eq!(send_events.len(), 2);
3763         let first_send = SendEvent::from_event(send_events.pop().unwrap());
3764         let second_send = SendEvent::from_event(send_events.pop().unwrap());
3765
3766         let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3767                 (&first_send, &second_send)
3768         } else {
3769                 (&second_send, &first_send)
3770         };
3771         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3772         commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3773
3774         expect_pending_htlcs_forwardable!(nodes[1]);
3775         check_added_monitors(&nodes[1], 1);
3776         let b_forward_ev = SendEvent::from_node(&nodes[1]);
3777         nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3778         commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3779
3780         expect_pending_htlcs_forwardable!(nodes[3]);
3781
3782         // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3783         // will result in nodes[2] failing the HTLC back.
3784         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3785         nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3786
3787         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3788         commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3789
3790         let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3791         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3792         commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3793
3794         let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3795         assert_eq!(payment_fail_retryable_evs.len(), 2);
3796         if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3797         if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3798
3799         // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3800         // stored for our payment.
3801         if do_modify {
3802                 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3803         }
3804
3805         // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3806         // the payment state.
3807         if do_reload {
3808                 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3809                 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3810                 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3811                         persister, new_chain_monitor, nodes_0_deserialized);
3812                 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3813                 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
3814         }
3815         let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
3816         reconnect_args.send_channel_ready = (true, true);
3817         reconnect_nodes(reconnect_args);
3818
3819         // Create a new channel between C and D as A will refuse to retry on the existing one because
3820         // it just failed.
3821         let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3822
3823         // Now retry the failed HTLC.
3824         nodes[0].node.process_pending_htlc_forwards();
3825         check_added_monitors(&nodes[0], 1);
3826         let as_resend = SendEvent::from_node(&nodes[0]);
3827         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3828         commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3829
3830         expect_pending_htlcs_forwardable!(nodes[2]);
3831         check_added_monitors(&nodes[2], 1);
3832         let cs_forward = SendEvent::from_node(&nodes[2]);
3833         nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3834         commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3835
3836         // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3837         // the payment metadata was modified, failing only the one modified HTLC and retaining the
3838         // other.
3839         if do_modify {
3840                 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3841                 nodes[3].node.process_pending_htlc_forwards();
3842                 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3843                         &[HTLCDestination::FailedPayment {payment_hash}]);
3844                 nodes[3].node.process_pending_htlc_forwards();
3845
3846                 check_added_monitors(&nodes[3], 1);
3847                 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3848
3849                 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3850                 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3851                 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3852                         &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3853         } else {
3854                 expect_pending_htlcs_forwardable!(nodes[3]);
3855                 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3856                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3857         }
3858 }
3859
3860 #[test]
3861 fn test_payment_metadata_consistency() {
3862         do_test_payment_metadata_consistency(true, true);
3863         do_test_payment_metadata_consistency(true, false);
3864         do_test_payment_metadata_consistency(false, true);
3865         do_test_payment_metadata_consistency(false, false);
3866 }