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