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