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