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