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