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