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