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