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