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