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