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