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