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