1 // This file is Copyright its original authors, visible in version control
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
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.
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;
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;
22 use crate::ln::{msgs, ChannelId, PaymentSecret, PaymentPreimage};
23 use crate::ln::msgs::ChannelMessageHandler;
24 use crate::ln::outbound_payment::{IDEMPOTENCY_TIMEOUT_TICKS, Retry};
25 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
26 use crate::routing::router::{get_route, Path, PaymentParameters, Route, Router, RouteHint, RouteHintHop, RouteHop, RouteParameters, find_route};
27 use crate::routing::scoring::ChannelUsage;
28 use crate::util::config::UserConfig;
29 use crate::util::test_utils;
30 use crate::util::errors::APIError;
31 use crate::util::ser::Writeable;
32 use crate::util::string::UntrustedString;
34 use bitcoin::network::constants::Network;
36 use crate::prelude::*;
38 use crate::ln::functional_test_utils::*;
39 use crate::routing::gossip::NodeId;
40 #[cfg(feature = "std")]
42 crate::util::time::tests::SinceEpoch,
43 std::time::{SystemTime, Instant, Duration}
48 let chanmon_cfgs = create_chanmon_cfgs(4);
49 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
50 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
51 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
53 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
54 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
55 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
56 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
58 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
59 let path = route.paths[0].clone();
60 route.paths.push(path);
61 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
62 route.paths[0].hops[0].short_channel_id = chan_1_id;
63 route.paths[0].hops[1].short_channel_id = chan_3_id;
64 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
65 route.paths[1].hops[0].short_channel_id = chan_2_id;
66 route.paths[1].hops[1].short_channel_id = chan_4_id;
67 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
68 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
73 let chanmon_cfgs = create_chanmon_cfgs(4);
74 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
75 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
76 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
78 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
79 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
80 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
81 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
83 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
85 let amt_msat = 1_000_000;
86 let max_total_routing_fee_msat = 50_000;
87 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
88 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
89 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(
90 nodes[0], nodes[3], payment_params, amt_msat, Some(max_total_routing_fee_msat));
91 let path = route.paths[0].clone();
92 route.paths.push(path);
93 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
94 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
95 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
96 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
97 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
98 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
100 // Initiate the MPP payment.
101 let payment_id = PaymentId(payment_hash.0);
102 let mut route_params = route.route_params.clone().unwrap();
104 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
105 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
106 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
107 check_added_monitors!(nodes[0], 2); // one monitor per path
108 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
109 assert_eq!(events.len(), 2);
111 // Pass half of the payment along the success path.
112 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
113 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
115 // Add the HTLC along the first hop.
116 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
117 let send_event = SendEvent::from_event(fail_path_msgs_1);
118 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
119 commitment_signed_dance!(nodes[2], nodes[0], &send_event.commitment_msg, false);
121 // Attempt to forward the payment and complete the 2nd path's failure.
122 expect_pending_htlcs_forwardable!(&nodes[2]);
123 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 }]);
124 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
125 assert!(htlc_updates.update_add_htlcs.is_empty());
126 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
127 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
128 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
129 check_added_monitors!(nodes[2], 1);
130 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
131 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
132 let mut events = nodes[0].node.get_and_clear_pending_events();
134 Event::PendingHTLCsForwardable { .. } => {},
135 _ => panic!("Unexpected event")
138 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
140 // Rebalance the channel so the second half of the payment can succeed.
141 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
143 // Retry the second half of the payment and make sure it succeeds.
144 route.paths.remove(0);
145 route_params.final_value_msat = 1_000_000;
146 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
147 // Check the remaining max total routing fee for the second attempt is 50_000 - 1_000 msat fee
148 // used by the first path
149 route_params.max_total_routing_fee_msat = Some(max_total_routing_fee_msat - 1_000);
150 nodes[0].router.expect_find_route(route_params, Ok(route));
151 nodes[0].node.process_pending_htlc_forwards();
152 check_added_monitors!(nodes[0], 1);
153 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
154 assert_eq!(events.len(), 1);
155 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
156 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
160 fn mpp_retry_overpay() {
161 // We create an MPP scenario with two paths in which we need to overpay to reach
162 // htlc_minimum_msat. We then fail the overpaid path and check that on retry our
163 // max_total_routing_fee_msat only accounts for the path's fees, but not for the fees overpaid
164 // in the first attempt.
165 let chanmon_cfgs = create_chanmon_cfgs(4);
166 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
167 let mut user_config = test_default_channel_config();
168 user_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
169 let mut limited_config_1 = user_config.clone();
170 limited_config_1.channel_handshake_config.our_htlc_minimum_msat = 35_000_000;
171 let mut limited_config_2 = user_config.clone();
172 limited_config_2.channel_handshake_config.our_htlc_minimum_msat = 34_500_000;
173 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
174 &[Some(user_config), Some(limited_config_1), Some(limited_config_2), Some(user_config)]);
175 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
177 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 40_000, 0);
178 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 40_000, 0);
179 let (_chan_3_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 40_000, 0);
180 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes_with_value(&nodes, 3, 2, 40_000, 0);
182 let amt_msat = 70_000_000;
183 let max_total_routing_fee_msat = Some(1_000_000);
185 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
186 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
187 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(
188 nodes[0], nodes[3], payment_params, amt_msat, max_total_routing_fee_msat);
190 // Check we overpay on the second path which we're about to fail.
191 assert_eq!(chan_1_update.contents.fee_proportional_millionths, 0);
192 let overpaid_amount_1 = route.paths[0].fee_msat() as u32 - chan_1_update.contents.fee_base_msat;
193 assert_eq!(overpaid_amount_1, 0);
195 assert_eq!(chan_2_update.contents.fee_proportional_millionths, 0);
196 let overpaid_amount_2 = route.paths[1].fee_msat() as u32 - chan_2_update.contents.fee_base_msat;
198 let total_overpaid_amount = overpaid_amount_1 + overpaid_amount_2;
200 // Initiate the payment.
201 let payment_id = PaymentId(payment_hash.0);
202 let mut route_params = route.route_params.clone().unwrap();
204 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
205 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
206 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
207 check_added_monitors!(nodes[0], 2); // one monitor per path
208 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
209 assert_eq!(events.len(), 2);
211 // Pass half of the payment along the success path.
212 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
213 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, payment_hash,
214 Some(payment_secret), success_path_msgs, false, None);
216 // Add the HTLC along the first hop.
217 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
218 let send_event = SendEvent::from_event(fail_path_msgs_1);
219 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
220 commitment_signed_dance!(nodes[2], nodes[0], &send_event.commitment_msg, false);
222 // Attempt to forward the payment and complete the 2nd path's failure.
223 expect_pending_htlcs_forwardable!(&nodes[2]);
224 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[2],
225 vec![HTLCDestination::NextHopChannel {
226 node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_4_id
229 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
230 assert!(htlc_updates.update_add_htlcs.is_empty());
231 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
232 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
233 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
234 check_added_monitors!(nodes[2], 1);
235 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(),
236 &htlc_updates.update_fail_htlcs[0]);
237 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
238 let mut events = nodes[0].node.get_and_clear_pending_events();
240 Event::PendingHTLCsForwardable { .. } => {},
241 _ => panic!("Unexpected event")
244 expect_payment_failed_conditions_event(events, payment_hash, false,
245 PaymentFailedConditions::new().mpp_parts_remain());
247 // Rebalance the channel so the second half of the payment can succeed.
248 send_payment(&nodes[3], &vec!(&nodes[2])[..], 38_000_000);
250 // Retry the second half of the payment and make sure it succeeds.
251 let first_path_value = route.paths[0].final_value_msat();
252 assert_eq!(first_path_value, 36_000_000);
254 route.paths.remove(0);
255 route_params.final_value_msat -= first_path_value;
256 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
258 // Check the remaining max total routing fee for the second attempt accounts only for 1_000 msat
259 // base fee, but not for overpaid value of the first try.
260 route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 1000);
261 nodes[0].router.expect_find_route(route_params, Ok(route));
262 nodes[0].node.process_pending_htlc_forwards();
264 check_added_monitors!(nodes[0], 1);
265 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
266 assert_eq!(events.len(), 1);
267 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], amt_msat, payment_hash,
268 Some(payment_secret), events.pop().unwrap(), true, None);
270 // Can't use claim_payment_along_route as it doesn't support overpayment, so we break out the
271 // individual steps here.
272 let extra_fees = vec![0, total_overpaid_amount];
273 let expected_total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
274 &nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], &extra_fees[..], false,
276 expect_payment_sent!(&nodes[0], payment_preimage, Some(expected_total_fee_msat));
279 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
280 let chanmon_cfgs = create_chanmon_cfgs(4);
281 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
282 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
283 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
285 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
286 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
287 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
288 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
290 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
291 let path = route.paths[0].clone();
292 route.paths.push(path);
293 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
294 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
295 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
296 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
297 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
298 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
300 // Initiate the MPP payment.
301 nodes[0].node.send_payment_with_route(&route, payment_hash,
302 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
303 check_added_monitors!(nodes[0], 2); // one monitor per path
304 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
305 assert_eq!(events.len(), 2);
307 // Pass half of the payment along the first path.
308 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
309 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
311 if send_partial_mpp {
312 // Time out the partial MPP
313 for _ in 0..MPP_TIMEOUT_TICKS {
314 nodes[3].node.timer_tick_occurred();
317 // Failed HTLC from node 3 -> 1
318 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
319 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
320 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
321 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
322 check_added_monitors!(nodes[3], 1);
323 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
325 // Failed HTLC from node 1 -> 0
326 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 }]);
327 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
328 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
329 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
330 check_added_monitors!(nodes[1], 1);
331 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
333 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
335 // Pass half of the payment along the second path.
336 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
337 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
339 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
340 for _ in 0..MPP_TIMEOUT_TICKS {
341 nodes[3].node.timer_tick_occurred();
344 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
349 fn mpp_receive_timeout() {
350 do_mpp_receive_timeout(true);
351 do_mpp_receive_timeout(false);
355 fn test_keysend_payments() {
356 do_test_keysend_payments(false, false);
357 do_test_keysend_payments(false, true);
358 do_test_keysend_payments(true, false);
359 do_test_keysend_payments(true, true);
362 fn do_test_keysend_payments(public_node: bool, with_retry: bool) {
363 let chanmon_cfgs = create_chanmon_cfgs(2);
364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
366 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
369 create_announced_chan_between_nodes(&nodes, 0, 1);
371 create_chan_between_nodes(&nodes[0], &nodes[1]);
373 let payer_pubkey = nodes[0].node.get_our_node_id();
374 let payee_pubkey = nodes[1].node.get_our_node_id();
375 let route_params = RouteParameters::from_payment_params_and_value(
376 PaymentParameters::for_keysend(payee_pubkey, 40, false), 10000);
378 let network_graph = nodes[0].network_graph.clone();
379 let channels = nodes[0].node.list_usable_channels();
380 let first_hops = channels.iter().collect::<Vec<_>>();
381 let first_hops = if public_node { None } else { Some(first_hops.as_slice()) };
383 let scorer = test_utils::TestScorer::new();
384 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
385 let route = find_route(
386 &payer_pubkey, &route_params, &network_graph, first_hops,
387 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
391 let test_preimage = PaymentPreimage([42; 32]);
393 nodes[0].node.send_spontaneous_payment_with_retry(Some(test_preimage),
394 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0),
395 route_params, Retry::Attempts(1)).unwrap()
397 nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
398 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap()
401 check_added_monitors!(nodes[0], 1);
402 let send_event = SendEvent::from_node(&nodes[0]);
403 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
404 do_commitment_signed_dance(&nodes[1], &nodes[0], &send_event.commitment_msg, false, false);
405 expect_pending_htlcs_forwardable!(nodes[1]);
406 // Previously, a refactor caused us to stop including the payment preimage in the onion which
407 // is sent as a part of keysend payments. Thus, to be extra careful here, we scope the preimage
408 // above to demonstrate that we have no way to get the preimage at this point except by
409 // extracting it from the onion nodes[1] received.
410 let event = nodes[1].node.get_and_clear_pending_events();
411 assert_eq!(event.len(), 1);
412 if let Event::PaymentClaimable { purpose: PaymentPurpose::SpontaneousPayment(preimage), .. } = event[0] {
413 claim_payment(&nodes[0], &[&nodes[1]], preimage);
418 fn test_mpp_keysend() {
419 let mut mpp_keysend_config = test_default_channel_config();
420 mpp_keysend_config.accept_mpp_keysend = true;
421 let chanmon_cfgs = create_chanmon_cfgs(4);
422 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
423 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
424 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
426 create_announced_chan_between_nodes(&nodes, 0, 1);
427 create_announced_chan_between_nodes(&nodes, 0, 2);
428 create_announced_chan_between_nodes(&nodes, 1, 3);
429 create_announced_chan_between_nodes(&nodes, 2, 3);
430 let network_graph = nodes[0].network_graph.clone();
432 let payer_pubkey = nodes[0].node.get_our_node_id();
433 let payee_pubkey = nodes[3].node.get_our_node_id();
434 let recv_value = 15_000_000;
435 let route_params = RouteParameters::from_payment_params_and_value(
436 PaymentParameters::for_keysend(payee_pubkey, 40, true), recv_value);
437 let scorer = test_utils::TestScorer::new();
438 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
439 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger,
440 &scorer, &Default::default(), &random_seed_bytes).unwrap();
442 let payment_preimage = PaymentPreimage([42; 32]);
443 let payment_secret = PaymentSecret(payment_preimage.0);
444 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
445 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_preimage.0)).unwrap();
446 check_added_monitors!(nodes[0], 2);
448 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
449 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
450 assert_eq!(events.len(), 2);
452 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
453 pass_along_path(&nodes[0], expected_route[0], recv_value, payment_hash.clone(),
454 Some(payment_secret), ev.clone(), false, Some(payment_preimage));
456 let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
457 pass_along_path(&nodes[0], expected_route[1], recv_value, payment_hash.clone(),
458 Some(payment_secret), ev.clone(), true, Some(payment_preimage));
459 claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
463 fn test_reject_mpp_keysend_htlc() {
464 // This test enforces that we reject MPP keysend HTLCs if our config states we don't support
465 // MPP keysend. When receiving a payment, if we don't support MPP keysend we'll reject the
466 // payment if it's keysend and has a payment secret, never reaching our payment validation
467 // logic. To check that we enforce rejecting MPP keysends in our payment logic, here we send
468 // keysend payments without payment secrets, then modify them by adding payment secrets in the
469 // final node in between receiving the HTLCs and actually processing them.
470 let mut reject_mpp_keysend_cfg = test_default_channel_config();
471 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
473 let chanmon_cfgs = create_chanmon_cfgs(4);
474 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
475 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(reject_mpp_keysend_cfg)]);
476 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
477 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
478 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
479 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
480 let (update_a, _, chan_4_channel_id, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
481 let chan_4_id = update_a.contents.short_channel_id;
483 let (mut route, payment_hash, payment_preimage, _) = get_route_and_payment_hash!(nodes[0], nodes[3], amount);
485 // Pay along nodes[1]
486 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
487 route.paths[0].hops[0].short_channel_id = chan_1_id;
488 route.paths[0].hops[1].short_channel_id = chan_3_id;
490 let payment_id_0 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
491 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_0).unwrap();
492 check_added_monitors!(nodes[0], 1);
494 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
495 let update_add_0 = update_0.update_add_htlcs[0].clone();
496 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
497 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
498 expect_pending_htlcs_forwardable!(nodes[1]);
500 check_added_monitors!(&nodes[1], 1);
501 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[3].node.get_our_node_id());
502 let update_add_1 = update_1.update_add_htlcs[0].clone();
503 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
504 commitment_signed_dance!(nodes[3], nodes[1], update_1.commitment_signed, false, true);
506 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
507 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
508 for f in pending_forwards.iter_mut() {
510 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
511 match forward_info.routing {
512 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
513 *payment_data = Some(msgs::FinalOnionHopData {
514 payment_secret: PaymentSecret([42; 32]),
515 total_msat: amount * 2,
518 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
525 expect_pending_htlcs_forwardable!(nodes[3]);
527 // Pay along nodes[2]
528 route.paths[0].hops[0].pubkey = nodes[2].node.get_our_node_id();
529 route.paths[0].hops[0].short_channel_id = chan_2_id;
530 route.paths[0].hops[1].short_channel_id = chan_4_id;
532 let payment_id_1 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
533 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
534 check_added_monitors!(nodes[0], 1);
536 let update_2 = get_htlc_update_msgs!(nodes[0], nodes[2].node.get_our_node_id());
537 let update_add_2 = update_2.update_add_htlcs[0].clone();
538 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_2);
539 commitment_signed_dance!(nodes[2], nodes[0], &update_2.commitment_signed, false, true);
540 expect_pending_htlcs_forwardable!(nodes[2]);
542 check_added_monitors!(&nodes[2], 1);
543 let update_3 = get_htlc_update_msgs!(nodes[2], nodes[3].node.get_our_node_id());
544 let update_add_3 = update_3.update_add_htlcs[0].clone();
545 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &update_add_3);
546 commitment_signed_dance!(nodes[3], nodes[2], update_3.commitment_signed, false, true);
548 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
549 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
550 for f in pending_forwards.iter_mut() {
552 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
553 match forward_info.routing {
554 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
555 *payment_data = Some(msgs::FinalOnionHopData {
556 payment_secret: PaymentSecret([42; 32]),
557 total_msat: amount * 2,
560 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
567 expect_pending_htlcs_forwardable!(nodes[3]);
568 check_added_monitors!(nodes[3], 1);
570 // Fail back along nodes[2]
571 let update_fail_0 = get_htlc_update_msgs!(&nodes[3], &nodes[2].node.get_our_node_id());
572 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &update_fail_0.update_fail_htlcs[0]);
573 commitment_signed_dance!(nodes[2], nodes[3], update_fail_0.commitment_signed, false);
574 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 }]);
575 check_added_monitors!(nodes[2], 1);
577 let update_fail_1 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
578 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_1.update_fail_htlcs[0]);
579 commitment_signed_dance!(nodes[0], nodes[2], update_fail_1.commitment_signed, false);
581 expect_payment_failed_conditions(&nodes[0], payment_hash, true, PaymentFailedConditions::new());
582 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
587 fn no_pending_leak_on_initial_send_failure() {
588 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
589 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
590 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
591 // pending payment forever and never time it out.
592 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
593 // try, and then check that no pending payment is being tracked.
594 let chanmon_cfgs = create_chanmon_cfgs(2);
595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
599 create_announced_chan_between_nodes(&nodes, 0, 1);
601 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
603 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
604 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
606 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
607 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
608 ), true, APIError::ChannelUnavailable { ref err },
609 assert_eq!(err, "Peer for first hop currently disconnected"));
611 assert!(!nodes[0].node.has_pending_payments());
614 fn do_retry_with_no_persist(confirm_before_reload: bool) {
615 // If we send a pending payment and `send_payment` returns success, we should always either
616 // return a payment failure event or a payment success event, and on failure the payment should
619 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
620 // always persisted asynchronously), the ChannelManager has to reload some payment data from
621 // ChannelMonitor(s) in some cases. This tests that reloading.
623 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
624 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
625 // which has separate codepaths for "commitment transaction already confirmed" and not.
626 let chanmon_cfgs = create_chanmon_cfgs(3);
627 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
629 let new_chain_monitor;
630 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
631 let nodes_0_deserialized;
632 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
634 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
635 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
637 // Serialize the ChannelManager prior to sending payments
638 let nodes_0_serialized = nodes[0].node.encode();
640 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
642 let amt_msat = 1_000_000;
643 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
644 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
645 let route_params = route.route_params.unwrap().clone();
646 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
647 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
648 check_added_monitors!(nodes[0], 1);
650 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
651 assert_eq!(events.len(), 1);
652 let payment_event = SendEvent::from_event(events.pop().unwrap());
653 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
655 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
656 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
657 // which would prevent retry.
658 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
659 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
661 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
662 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
663 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
664 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
666 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
668 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
669 if confirm_before_reload {
670 mine_transaction(&nodes[0], &as_commitment_tx);
671 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
674 // The ChannelMonitor should always be the latest version, as we're required to persist it
675 // during the `commitment_signed_dance!()`.
676 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
677 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
679 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
680 // force-close the channel.
681 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
682 assert!(nodes[0].node.list_channels().is_empty());
683 assert!(nodes[0].node.has_pending_payments());
684 nodes[0].node.timer_tick_occurred();
685 if !confirm_before_reload {
686 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
687 assert_eq!(as_broadcasted_txn.len(), 1);
688 assert_eq!(as_broadcasted_txn[0].txid(), as_commitment_tx.txid());
690 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
692 check_added_monitors!(nodes[0], 1);
694 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
695 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
696 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
698 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
700 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
701 // error, as the channel has hit the chain.
702 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
703 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
705 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
706 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
707 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
708 assert_eq!(as_err.len(), 1);
710 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
711 assert_eq!(node_id, nodes[1].node.get_our_node_id());
712 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
713 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 {}",
714 &nodes[1].node.get_our_node_id())) }, [nodes[0].node.get_our_node_id()], 100000);
715 check_added_monitors!(nodes[1], 1);
716 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
718 _ => panic!("Unexpected event"),
720 check_closed_broadcast!(nodes[1], false);
722 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
723 // we close in a moment.
724 nodes[2].node.claim_funds(payment_preimage_1);
725 check_added_monitors!(nodes[2], 1);
726 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
728 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
729 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
730 check_added_monitors!(nodes[1], 1);
731 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
732 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, true, false);
734 if confirm_before_reload {
735 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
736 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
739 // Create a new channel on which to retry the payment before we fail the payment via the
740 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
741 // connecting several blocks while creating the channel (implying time has passed).
742 create_announced_chan_between_nodes(&nodes, 0, 1);
743 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
745 mine_transaction(&nodes[1], &as_commitment_tx);
746 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
747 assert_eq!(bs_htlc_claim_txn.len(), 1);
748 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
750 if !confirm_before_reload {
751 mine_transaction(&nodes[0], &as_commitment_tx);
753 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
754 expect_payment_sent(&nodes[0], payment_preimage_1, None, true, false);
755 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
756 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
757 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
758 assert_eq!(txn.len(), 2);
759 (txn.remove(0), txn.remove(0))
761 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
762 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
763 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
764 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
766 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
768 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
769 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
771 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
772 // reloaded) via a route over the new channel, which work without issue and eventually be
773 // received and claimed at the recipient just like any other payment.
774 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
776 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
777 // and not the original fee. We also update node[1]'s relevant config as
778 // do_claim_payment_along_route expects us to never overpay.
780 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
781 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
782 .unwrap().lock().unwrap();
783 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
784 let mut new_config = channel.context().config();
785 new_config.forwarding_fee_base_msat += 100_000;
786 channel.context_mut().update_config(&new_config);
787 new_route.paths[0].hops[0].fee_msat += 100_000;
790 // Force expiration of the channel's previous config.
791 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
792 nodes[1].node.timer_tick_occurred();
795 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
796 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
797 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
798 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
799 check_added_monitors!(nodes[0], 1);
800 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
801 assert_eq!(events.len(), 1);
802 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
803 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
804 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
808 fn retry_with_no_persist() {
809 do_retry_with_no_persist(true);
810 do_retry_with_no_persist(false);
813 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
814 // Test that an off-chain completed payment is not retryable on restart. This was previously
815 // broken for dust payments, but we test for both dust and non-dust payments.
817 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
819 let chanmon_cfgs = create_chanmon_cfgs(3);
820 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
822 let mut manually_accept_config = test_default_channel_config();
823 manually_accept_config.manually_accept_inbound_channels = true;
826 let first_new_chain_monitor;
827 let second_persister;
828 let second_new_chain_monitor;
830 let third_new_chain_monitor;
832 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
833 let first_nodes_0_deserialized;
834 let second_nodes_0_deserialized;
835 let third_nodes_0_deserialized;
837 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
839 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
840 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
841 confirm_transaction(&nodes[0], &funding_tx);
842 confirm_transaction(&nodes[1], &funding_tx);
843 // Ignore the announcement_signatures messages
844 nodes[0].node.get_and_clear_pending_msg_events();
845 nodes[1].node.get_and_clear_pending_msg_events();
846 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
848 // Serialize the ChannelManager prior to sending payments
849 let mut nodes_0_serialized = nodes[0].node.encode();
851 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
852 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 });
854 // The ChannelMonitor should always be the latest version, as we're required to persist it
855 // during the `commitment_signed_dance!()`.
856 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
858 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);
859 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
861 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
862 // force-close the channel.
863 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
864 nodes[0].node.timer_tick_occurred();
865 assert!(nodes[0].node.list_channels().is_empty());
866 assert!(nodes[0].node.has_pending_payments());
867 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
868 check_added_monitors!(nodes[0], 1);
870 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
871 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
873 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
875 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
876 // error, as the channel has hit the chain.
877 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
878 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
880 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
881 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
882 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
883 assert_eq!(as_err.len(), 1);
884 let bs_commitment_tx;
886 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
887 assert_eq!(node_id, nodes[1].node.get_our_node_id());
888 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
889 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())) }
890 , [nodes[0].node.get_our_node_id()], 100000);
891 check_added_monitors!(nodes[1], 1);
892 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
894 _ => panic!("Unexpected event"),
896 check_closed_broadcast!(nodes[1], false);
898 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
899 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
900 // incoming HTLCs with the same payment hash later.
901 nodes[2].node.fail_htlc_backwards(&payment_hash);
902 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
903 check_added_monitors!(nodes[2], 1);
905 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
906 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
907 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
908 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
909 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
911 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
912 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
913 // after the commitment transaction, so always connect the commitment transaction.
914 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
915 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
917 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
918 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
919 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
920 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
921 assert_eq!(as_htlc_timeout.len(), 1);
923 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
924 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
925 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
926 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
929 // Create a new channel on which to retry the payment before we fail the payment via the
930 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
931 // connecting several blocks while creating the channel (implying time has passed).
932 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
933 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
934 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
936 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
937 // confirming, we will fail as it's considered still-pending...
938 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
939 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
940 Err(PaymentSendFailure::DuplicatePayment) => {},
941 _ => panic!("Unexpected error")
943 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
945 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
946 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
947 // (which should also still work).
948 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
949 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
950 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
952 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
953 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
954 nodes_0_serialized = nodes[0].node.encode();
956 // After the payment failed, we're free to send it again.
957 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
958 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
959 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
961 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);
962 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
964 nodes[0].node.test_process_background_events();
965 check_added_monitors(&nodes[0], 1);
967 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
968 reconnect_args.send_channel_ready = (true, true);
969 reconnect_nodes(reconnect_args);
971 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
972 // the payment is not (spuriously) listed as still pending.
973 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
974 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
975 check_added_monitors!(nodes[0], 1);
976 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
977 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
979 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
980 Err(PaymentSendFailure::DuplicatePayment) => {},
981 _ => panic!("Unexpected error")
983 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
985 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
986 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
987 nodes_0_serialized = nodes[0].node.encode();
989 // Check that after reload we can send the payment again (though we shouldn't, since it was
990 // claimed previously).
991 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);
992 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
994 nodes[0].node.test_process_background_events();
995 check_added_monitors(&nodes[0], 1);
997 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
999 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
1000 Err(PaymentSendFailure::DuplicatePayment) => {},
1001 _ => panic!("Unexpected error")
1003 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1007 fn test_completed_payment_not_retryable_on_reload() {
1008 do_test_completed_payment_not_retryable_on_reload(true);
1009 do_test_completed_payment_not_retryable_on_reload(false);
1013 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
1014 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
1015 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
1016 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
1017 // the ChannelMonitor tells it to.
1019 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
1020 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
1021 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
1022 let chanmon_cfgs = create_chanmon_cfgs(2);
1023 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1025 let new_chain_monitor;
1026 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1027 let nodes_0_deserialized;
1028 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1030 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
1032 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
1034 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
1035 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
1036 check_closed_broadcast!(nodes[0], true);
1037 check_added_monitors!(nodes[0], 1);
1038 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
1040 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1041 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
1043 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
1044 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
1045 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1046 assert_eq!(node_txn.len(), 3);
1047 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
1048 check_spends!(node_txn[1], funding_tx);
1049 check_spends!(node_txn[2], node_txn[1]);
1050 let timeout_txn = vec![node_txn[2].clone()];
1052 nodes[1].node.claim_funds(payment_preimage);
1053 check_added_monitors!(nodes[1], 1);
1054 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
1056 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[1].clone()]));
1057 check_closed_broadcast!(nodes[1], true);
1058 check_added_monitors!(nodes[1], 1);
1059 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
1060 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1061 assert_eq!(claim_txn.len(), 1);
1062 check_spends!(claim_txn[0], node_txn[1]);
1064 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[1].clone()]));
1066 if confirm_commitment_tx {
1067 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
1070 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] });
1072 if payment_timeout {
1073 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
1074 connect_block(&nodes[0], &claim_block);
1075 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
1078 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
1079 // returning InProgress. This should cause the claim event to never make its way to the
1081 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
1082 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
1084 if payment_timeout {
1085 connect_blocks(&nodes[0], 1);
1087 connect_block(&nodes[0], &claim_block);
1090 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
1091 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
1092 .get_mut(&funding_txo).unwrap().drain().collect();
1093 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
1094 // If we're testing connection idempotency we may get substantially more.
1095 assert!(mon_updates.len() >= 1);
1096 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
1097 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1099 // If we persist the ChannelManager here, we should get the PaymentSent event after
1101 let mut chan_manager_serialized = Vec::new();
1102 if !persist_manager_post_event {
1103 chan_manager_serialized = nodes[0].node.encode();
1106 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
1107 // payment sent event.
1108 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1109 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1110 for update in mon_updates {
1111 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
1113 if payment_timeout {
1114 expect_payment_failed!(nodes[0], payment_hash, false);
1116 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1119 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
1121 if persist_manager_post_event {
1122 chan_manager_serialized = nodes[0].node.encode();
1125 // Now reload nodes[0]...
1126 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
1128 if persist_manager_post_event {
1129 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1130 } else if payment_timeout {
1131 expect_payment_failed!(nodes[0], payment_hash, false);
1133 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1136 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
1137 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
1138 // payment events should kick in, leaving us with no pending events here.
1139 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
1140 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
1141 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1142 check_added_monitors(&nodes[0], 1);
1146 fn test_dup_htlc_onchain_fails_on_reload() {
1147 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
1148 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
1149 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
1150 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
1151 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
1152 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
1156 fn test_fulfill_restart_failure() {
1157 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
1158 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
1159 // again, or fail it, giving us free money.
1161 // Of course probably they won't fail it and give us free money, but because we have code to
1162 // handle it, we should test the logic for it anyway. We do that here.
1163 let chanmon_cfgs = create_chanmon_cfgs(2);
1164 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1166 let new_chain_monitor;
1167 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1168 let nodes_1_deserialized;
1169 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1171 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1172 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
1174 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
1175 // pre-fulfill, which we do by serializing it here.
1176 let chan_manager_serialized = nodes[1].node.encode();
1177 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1179 nodes[1].node.claim_funds(payment_preimage);
1180 check_added_monitors!(nodes[1], 1);
1181 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1183 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1184 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1185 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
1187 // Now reload nodes[1]...
1188 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1190 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1191 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1193 nodes[1].node.fail_htlc_backwards(&payment_hash);
1194 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1195 check_added_monitors!(nodes[1], 1);
1196 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1197 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1198 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1199 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1200 // it had already considered the payment fulfilled, and now they just got free money.
1201 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1205 fn get_ldk_payment_preimage() {
1206 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1207 let chanmon_cfgs = create_chanmon_cfgs(2);
1208 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1209 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1210 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1211 create_announced_chan_between_nodes(&nodes, 0, 1);
1213 let amt_msat = 60_000;
1214 let expiry_secs = 60 * 60;
1215 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1217 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1218 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
1219 let scorer = test_utils::TestScorer::new();
1220 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1221 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1222 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
1223 let route = get_route( &nodes[0].node.get_our_node_id(), &route_params,
1224 &nodes[0].network_graph.read_only(),
1225 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()), nodes[0].logger,
1226 &scorer, &Default::default(), &random_seed_bytes).unwrap();
1227 nodes[0].node.send_payment_with_route(&route, payment_hash,
1228 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1229 check_added_monitors!(nodes[0], 1);
1231 // Make sure to use `get_payment_preimage`
1232 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1233 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1234 assert_eq!(events.len(), 1);
1235 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1236 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1240 fn sent_probe_is_probe_of_sending_node() {
1241 let chanmon_cfgs = create_chanmon_cfgs(3);
1242 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1243 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1244 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1246 create_announced_chan_between_nodes(&nodes, 0, 1);
1247 create_announced_chan_between_nodes(&nodes, 1, 2);
1249 // First check we refuse to build a single-hop probe
1250 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1251 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1253 // Then build an actual two-hop probing path
1254 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1256 match nodes[0].node.send_probe(route.paths[0].clone()) {
1257 Ok((payment_hash, payment_id)) => {
1258 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1259 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1260 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1265 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1266 check_added_monitors!(nodes[0], 1);
1270 fn successful_probe_yields_event() {
1271 let chanmon_cfgs = create_chanmon_cfgs(3);
1272 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1273 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1274 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1276 create_announced_chan_between_nodes(&nodes, 0, 1);
1277 create_announced_chan_between_nodes(&nodes, 1, 2);
1279 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1281 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1283 // node[0] -- update_add_htlcs -> node[1]
1284 check_added_monitors!(nodes[0], 1);
1285 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1286 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1287 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1288 check_added_monitors!(nodes[1], 0);
1289 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1290 expect_pending_htlcs_forwardable!(nodes[1]);
1292 // node[1] -- update_add_htlcs -> node[2]
1293 check_added_monitors!(nodes[1], 1);
1294 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1295 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1296 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1297 check_added_monitors!(nodes[2], 0);
1298 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
1300 // node[1] <- update_fail_htlcs -- node[2]
1301 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1302 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1303 check_added_monitors!(nodes[1], 0);
1304 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1306 // node[0] <- update_fail_htlcs -- node[1]
1307 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1308 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1309 check_added_monitors!(nodes[0], 0);
1310 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1312 let mut events = nodes[0].node.get_and_clear_pending_events();
1313 assert_eq!(events.len(), 1);
1314 match events.drain(..).next().unwrap() {
1315 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1316 assert_eq!(payment_id, ev_pid);
1317 assert_eq!(payment_hash, ev_ph);
1321 assert!(!nodes[0].node.has_pending_payments());
1325 fn failed_probe_yields_event() {
1326 let chanmon_cfgs = create_chanmon_cfgs(3);
1327 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1328 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1329 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1331 create_announced_chan_between_nodes(&nodes, 0, 1);
1332 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1334 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1336 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 9_998_000);
1338 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1340 // node[0] -- update_add_htlcs -> node[1]
1341 check_added_monitors!(nodes[0], 1);
1342 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1343 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1344 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1345 check_added_monitors!(nodes[1], 0);
1346 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1347 expect_pending_htlcs_forwardable!(nodes[1]);
1349 // node[0] <- update_fail_htlcs -- node[1]
1350 check_added_monitors!(nodes[1], 1);
1351 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1352 // Skip the PendingHTLCsForwardable event
1353 let _events = nodes[1].node.get_and_clear_pending_events();
1354 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1355 check_added_monitors!(nodes[0], 0);
1356 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1358 let mut events = nodes[0].node.get_and_clear_pending_events();
1359 assert_eq!(events.len(), 1);
1360 match events.drain(..).next().unwrap() {
1361 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1362 assert_eq!(payment_id, ev_pid);
1363 assert_eq!(payment_hash, ev_ph);
1367 assert!(!nodes[0].node.has_pending_payments());
1371 fn onchain_failed_probe_yields_event() {
1372 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1374 let chanmon_cfgs = create_chanmon_cfgs(3);
1375 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1376 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1377 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1379 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1380 create_announced_chan_between_nodes(&nodes, 1, 2);
1382 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1384 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1385 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 1_000);
1386 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1388 // node[0] -- update_add_htlcs -> node[1]
1389 check_added_monitors!(nodes[0], 1);
1390 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1391 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1392 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1393 check_added_monitors!(nodes[1], 0);
1394 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1395 expect_pending_htlcs_forwardable!(nodes[1]);
1397 check_added_monitors!(nodes[1], 1);
1398 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1400 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1401 // Node A, which after 6 confirmations should result in a probe failure event.
1402 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1403 confirm_transaction(&nodes[0], &bs_txn[0]);
1404 check_closed_broadcast!(&nodes[0], true);
1405 check_added_monitors!(nodes[0], 1);
1407 let mut events = nodes[0].node.get_and_clear_pending_events();
1408 assert_eq!(events.len(), 2);
1409 let mut found_probe_failed = false;
1410 for event in events.drain(..) {
1412 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1413 assert_eq!(payment_id, ev_pid);
1414 assert_eq!(payment_hash, ev_ph);
1415 found_probe_failed = true;
1417 Event::ChannelClosed { .. } => {},
1421 assert!(found_probe_failed);
1422 assert!(!nodes[0].node.has_pending_payments());
1426 fn preflight_probes_yield_event_and_skip() {
1427 let chanmon_cfgs = create_chanmon_cfgs(5);
1428 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1430 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1431 let mut no_htlc_limit_config = test_default_channel_config();
1432 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1434 let user_configs = std::iter::repeat(no_htlc_limit_config).take(5).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1435 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &user_configs);
1436 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1438 // Setup channel topology:
1439 // (30k:0)- N2 -(1M:0)
1441 // N0 -(100k:0)-> N1 N4
1443 // (70k:0)- N3 -(1M:0)
1445 let first_chan_update = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0).0;
1446 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 30_000, 0);
1447 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 70_000, 0);
1448 create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 1_000_000, 0);
1449 create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0);
1451 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1452 invoice_features.set_basic_mpp_optional();
1454 let mut payment_params = PaymentParameters::from_node_id(nodes[4].node.get_our_node_id(), TEST_FINAL_CLTV)
1455 .with_bolt11_features(invoice_features).unwrap();
1457 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 80_000_000);
1458 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1460 // We check that only one probe was sent, the other one was skipped due to limited liquidity.
1461 assert_eq!(res.len(), 1);
1462 let log_msg = format!("Skipped sending payment probe to avoid putting channel {} under the liquidity limit.",
1463 first_chan_update.contents.short_channel_id);
1464 node_cfgs[0].logger.assert_log_contains("lightning::ln::channelmanager", &log_msg, 1);
1466 let (payment_hash, payment_id) = res.first().unwrap();
1468 // node[0] -- update_add_htlcs -> node[1]
1469 check_added_monitors!(nodes[0], 1);
1470 let probe_event = SendEvent::from_node(&nodes[0]);
1471 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1472 check_added_monitors!(nodes[1], 0);
1473 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1474 expect_pending_htlcs_forwardable!(nodes[1]);
1476 // node[1] -- update_add_htlcs -> node[2]
1477 check_added_monitors!(nodes[1], 1);
1478 let probe_event = SendEvent::from_node(&nodes[1]);
1479 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1480 check_added_monitors!(nodes[2], 0);
1481 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, false);
1482 expect_pending_htlcs_forwardable!(nodes[2]);
1484 // node[2] -- update_add_htlcs -> node[4]
1485 check_added_monitors!(nodes[2], 1);
1486 let probe_event = SendEvent::from_node(&nodes[2]);
1487 nodes[4].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &probe_event.msgs[0]);
1488 check_added_monitors!(nodes[4], 0);
1489 commitment_signed_dance!(nodes[4], nodes[2], probe_event.commitment_msg, true, true);
1491 // node[2] <- update_fail_htlcs -- node[4]
1492 let updates = get_htlc_update_msgs!(nodes[4], nodes[2].node.get_our_node_id());
1493 nodes[2].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1494 check_added_monitors!(nodes[2], 0);
1495 commitment_signed_dance!(nodes[2], nodes[4], updates.commitment_signed, true);
1497 // node[1] <- update_fail_htlcs -- node[2]
1498 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1499 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1500 check_added_monitors!(nodes[1], 0);
1501 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1503 // node[0] <- update_fail_htlcs -- node[1]
1504 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1505 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1506 check_added_monitors!(nodes[0], 0);
1507 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1509 let mut events = nodes[0].node.get_and_clear_pending_events();
1510 assert_eq!(events.len(), 1);
1511 match events.drain(..).next().unwrap() {
1512 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1513 assert_eq!(*payment_id, ev_pid);
1514 assert_eq!(*payment_hash, ev_ph);
1518 assert!(!nodes[0].node.has_pending_payments());
1522 fn claimed_send_payment_idempotent() {
1523 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1524 let chanmon_cfgs = create_chanmon_cfgs(2);
1525 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1526 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1527 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1529 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1531 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1532 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1534 macro_rules! check_send_rejected {
1536 // If we try to resend a new payment with a different payment_hash but with the same
1537 // payment_id, it should be rejected.
1538 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1539 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1541 Err(PaymentSendFailure::DuplicatePayment) => {},
1542 _ => panic!("Unexpected send result: {:?}", send_result),
1545 // Further, if we try to send a spontaneous payment with the same payment_id it should
1546 // also be rejected.
1547 let send_result = nodes[0].node.send_spontaneous_payment(
1548 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1550 Err(PaymentSendFailure::DuplicatePayment) => {},
1551 _ => panic!("Unexpected send result: {:?}", send_result),
1556 check_send_rejected!();
1558 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1559 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1560 // we must remain just as idempotent as we were before.
1561 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1563 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1564 nodes[0].node.timer_tick_occurred();
1567 check_send_rejected!();
1569 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1570 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1571 // the payment complete. However, they could have called `send_payment` while the event was
1572 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1573 // after the event is handled a duplicate payment should sitll be rejected.
1574 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1575 check_send_rejected!();
1577 // If relatively little time has passed, a duplicate payment should still fail.
1578 nodes[0].node.timer_tick_occurred();
1579 check_send_rejected!();
1581 // However, after some time has passed (at least more than the one timer tick above), a
1582 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1583 // references to the old payment data.
1584 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1585 nodes[0].node.timer_tick_occurred();
1588 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1589 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1590 check_added_monitors!(nodes[0], 1);
1591 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1592 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1596 fn abandoned_send_payment_idempotent() {
1597 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1599 let chanmon_cfgs = create_chanmon_cfgs(2);
1600 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1601 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1602 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1604 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1606 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1607 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1609 macro_rules! check_send_rejected {
1611 // If we try to resend a new payment with a different payment_hash but with the same
1612 // payment_id, it should be rejected.
1613 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1614 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1616 Err(PaymentSendFailure::DuplicatePayment) => {},
1617 _ => panic!("Unexpected send result: {:?}", send_result),
1620 // Further, if we try to send a spontaneous payment with the same payment_id it should
1621 // also be rejected.
1622 let send_result = nodes[0].node.send_spontaneous_payment(
1623 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1625 Err(PaymentSendFailure::DuplicatePayment) => {},
1626 _ => panic!("Unexpected send result: {:?}", send_result),
1631 check_send_rejected!();
1633 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1634 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1636 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1638 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1639 nodes[0].node.timer_tick_occurred();
1641 check_send_rejected!();
1643 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1645 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1646 // failed payment back.
1647 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1648 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1649 check_added_monitors!(nodes[0], 1);
1650 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1651 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1654 #[derive(PartialEq)]
1655 enum InterceptTest {
1662 fn test_trivial_inflight_htlc_tracking(){
1663 // In this test, we test three scenarios:
1664 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1665 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1666 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1667 let chanmon_cfgs = create_chanmon_cfgs(3);
1668 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1669 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1670 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1672 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1673 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1675 // Send and claim the payment. Inflight HTLCs should be empty.
1676 let (_, payment_hash, _, payment_id) = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1677 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1679 let mut node_0_per_peer_lock;
1680 let mut node_0_peer_state_lock;
1681 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1683 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1684 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1685 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1686 channel_1.context().get_short_channel_id().unwrap()
1688 assert_eq!(chan_1_used_liquidity, None);
1691 let mut node_1_per_peer_lock;
1692 let mut node_1_peer_state_lock;
1693 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1695 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1696 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1697 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1698 channel_2.context().get_short_channel_id().unwrap()
1701 assert_eq!(chan_2_used_liquidity, None);
1703 let pending_payments = nodes[0].node.list_recent_payments();
1704 assert_eq!(pending_payments.len(), 1);
1705 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash), payment_id });
1707 // Remove fulfilled payment
1708 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1709 nodes[0].node.timer_tick_occurred();
1712 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1713 let (payment_preimage, payment_hash, _, payment_id) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1714 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1716 let mut node_0_per_peer_lock;
1717 let mut node_0_peer_state_lock;
1718 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1720 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1721 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1722 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1723 channel_1.context().get_short_channel_id().unwrap()
1725 // First hop accounts for expected 1000 msat fee
1726 assert_eq!(chan_1_used_liquidity, Some(501000));
1729 let mut node_1_per_peer_lock;
1730 let mut node_1_peer_state_lock;
1731 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1733 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1734 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1735 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1736 channel_2.context().get_short_channel_id().unwrap()
1739 assert_eq!(chan_2_used_liquidity, Some(500000));
1741 let pending_payments = nodes[0].node.list_recent_payments();
1742 assert_eq!(pending_payments.len(), 1);
1743 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_id, payment_hash, total_msat: 500000 });
1745 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1746 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1748 // Remove fulfilled payment
1749 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1750 nodes[0].node.timer_tick_occurred();
1753 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1755 let mut node_0_per_peer_lock;
1756 let mut node_0_peer_state_lock;
1757 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1759 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1760 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1761 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1762 channel_1.context().get_short_channel_id().unwrap()
1764 assert_eq!(chan_1_used_liquidity, None);
1767 let mut node_1_per_peer_lock;
1768 let mut node_1_peer_state_lock;
1769 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1771 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1772 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1773 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1774 channel_2.context().get_short_channel_id().unwrap()
1776 assert_eq!(chan_2_used_liquidity, None);
1779 let pending_payments = nodes[0].node.list_recent_payments();
1780 assert_eq!(pending_payments.len(), 0);
1784 fn test_holding_cell_inflight_htlcs() {
1785 let chanmon_cfgs = create_chanmon_cfgs(2);
1786 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1787 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1788 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1789 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1791 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1792 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1794 // Queue up two payments - one will be delivered right away, one immediately goes into the
1795 // holding cell as nodes[0] is AwaitingRAA.
1797 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1798 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1799 check_added_monitors!(nodes[0], 1);
1800 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1801 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1802 check_added_monitors!(nodes[0], 0);
1805 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1808 let mut node_0_per_peer_lock;
1809 let mut node_0_peer_state_lock;
1810 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1812 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1813 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1814 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1815 channel.context().get_short_channel_id().unwrap()
1818 assert_eq!(used_liquidity, Some(2000000));
1821 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1822 nodes[0].node.get_and_clear_pending_msg_events();
1826 fn intercepted_payment() {
1827 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1828 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1829 // payment or (b) fail the payment.
1830 do_test_intercepted_payment(InterceptTest::Forward);
1831 do_test_intercepted_payment(InterceptTest::Fail);
1832 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1833 do_test_intercepted_payment(InterceptTest::Timeout);
1836 fn do_test_intercepted_payment(test: InterceptTest) {
1837 let chanmon_cfgs = create_chanmon_cfgs(3);
1838 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1840 let mut zero_conf_chan_config = test_default_channel_config();
1841 zero_conf_chan_config.manually_accept_inbound_channels = true;
1842 let mut intercept_forwards_config = test_default_channel_config();
1843 intercept_forwards_config.accept_intercept_htlcs = true;
1844 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1846 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1847 let scorer = test_utils::TestScorer::new();
1848 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1850 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1852 let amt_msat = 100_000;
1853 let intercept_scid = nodes[1].node.get_intercept_scid();
1854 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1855 .with_route_hints(vec![
1856 RouteHint(vec![RouteHintHop {
1857 src_node_id: nodes[1].node.get_our_node_id(),
1858 short_channel_id: intercept_scid,
1861 proportional_millionths: 0,
1863 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1864 htlc_minimum_msat: None,
1865 htlc_maximum_msat: None,
1868 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1869 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat,);
1870 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params,
1871 &nodes[0].network_graph.read_only(), None, nodes[0].logger, &scorer, &Default::default(),
1872 &random_seed_bytes).unwrap();
1874 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1875 nodes[0].node.send_payment_with_route(&route, payment_hash,
1876 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1877 let payment_event = {
1879 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1880 assert_eq!(added_monitors.len(), 1);
1881 added_monitors.clear();
1883 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1884 assert_eq!(events.len(), 1);
1885 SendEvent::from_event(events.remove(0))
1887 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1888 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1890 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1891 let events = nodes[1].node.get_and_clear_pending_events();
1892 assert_eq!(events.len(), 1);
1893 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1894 crate::events::Event::HTLCIntercepted {
1895 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1897 assert_eq!(pmt_hash, payment_hash);
1898 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1899 assert_eq!(short_channel_id, intercept_scid);
1900 (intercept_id, expected_outbound_amount_msat)
1905 // Check for unknown channel id error.
1906 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();
1907 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable {
1908 err: format!("Channel with id {} not found for the passed counterparty node_id {}.",
1909 log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1911 if test == InterceptTest::Fail {
1912 // Ensure we can fail the intercepted payment back.
1913 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1914 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1915 nodes[1].node.process_pending_htlc_forwards();
1916 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1917 check_added_monitors!(&nodes[1], 1);
1918 assert!(update_fail.update_fail_htlcs.len() == 1);
1919 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1920 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1921 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1923 // Ensure the payment fails with the expected error.
1924 let fail_conditions = PaymentFailedConditions::new()
1925 .blamed_scid(intercept_scid)
1926 .blamed_chan_closed(true)
1927 .expected_htlc_error_data(0x4000 | 10, &[]);
1928 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1929 } else if test == InterceptTest::Forward {
1930 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1931 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1932 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();
1933 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1934 err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
1935 temp_chan_id, nodes[2].node.get_our_node_id()) });
1936 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1938 // Open the just-in-time channel so the payment can then be forwarded.
1939 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1941 // Finally, forward the intercepted payment through and claim it.
1942 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1943 expect_pending_htlcs_forwardable!(nodes[1]);
1945 let payment_event = {
1947 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1948 assert_eq!(added_monitors.len(), 1);
1949 added_monitors.clear();
1951 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1952 assert_eq!(events.len(), 1);
1953 SendEvent::from_event(events.remove(0))
1955 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1956 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1957 expect_pending_htlcs_forwardable!(nodes[2]);
1959 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1960 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1961 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1962 let events = nodes[0].node.get_and_clear_pending_events();
1963 assert_eq!(events.len(), 2);
1965 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1966 assert_eq!(payment_preimage, *ev_preimage);
1967 assert_eq!(payment_hash, *ev_hash);
1968 assert_eq!(fee_paid_msat, &Some(1000));
1970 _ => panic!("Unexpected event")
1973 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1974 assert_eq!(hash, Some(payment_hash));
1976 _ => panic!("Unexpected event")
1978 check_added_monitors(&nodes[0], 1);
1979 } else if test == InterceptTest::Timeout {
1980 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
1981 connect_block(&nodes[0], &block);
1982 connect_block(&nodes[1], &block);
1983 for _ in 0..TEST_FINAL_CLTV {
1984 block.header.prev_blockhash = block.block_hash();
1985 connect_block(&nodes[0], &block);
1986 connect_block(&nodes[1], &block);
1988 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1989 check_added_monitors!(nodes[1], 1);
1990 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1991 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1992 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1993 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1994 assert!(htlc_timeout_updates.update_fee.is_none());
1996 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1997 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1998 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
2000 // Check for unknown intercept id error.
2001 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
2002 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();
2003 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2004 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
2005 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2010 fn accept_underpaying_htlcs_config() {
2011 do_accept_underpaying_htlcs_config(1);
2012 do_accept_underpaying_htlcs_config(2);
2013 do_accept_underpaying_htlcs_config(3);
2016 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
2017 let chanmon_cfgs = create_chanmon_cfgs(3);
2018 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2019 let mut intercept_forwards_config = test_default_channel_config();
2020 intercept_forwards_config.accept_intercept_htlcs = true;
2021 let mut underpay_config = test_default_channel_config();
2022 underpay_config.channel_config.accept_underpaying_htlcs = true;
2023 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
2024 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2026 let mut chan_ids = Vec::new();
2027 for _ in 0..num_mpp_parts {
2028 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000, 0);
2029 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 2_000_000, 0).0.channel_id;
2030 chan_ids.push(channel_id);
2033 // Send the initial payment.
2034 let amt_msat = 900_000;
2035 let skimmed_fee_msat = 20;
2036 let mut route_hints = Vec::new();
2037 for _ in 0..num_mpp_parts {
2038 route_hints.push(RouteHint(vec![RouteHintHop {
2039 src_node_id: nodes[1].node.get_our_node_id(),
2040 short_channel_id: nodes[1].node.get_intercept_scid(),
2043 proportional_millionths: 0,
2045 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
2046 htlc_minimum_msat: None,
2047 htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
2050 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2051 .with_route_hints(route_hints).unwrap()
2052 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
2053 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2054 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
2055 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2056 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2057 check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
2058 let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
2059 assert_eq!(events.len(), num_mpp_parts);
2061 // Forward the intercepted payments.
2062 for (idx, ev) in events.into_iter().enumerate() {
2063 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
2064 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
2066 let events = nodes[1].node.get_and_clear_pending_events();
2067 assert_eq!(events.len(), 1);
2068 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
2069 crate::events::Event::HTLCIntercepted {
2070 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
2072 assert_eq!(pmt_hash, payment_hash);
2073 (intercept_id, expected_outbound_amount_msat)
2077 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
2078 nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
2079 expect_pending_htlcs_forwardable!(nodes[1]);
2080 let payment_event = {
2082 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2083 assert_eq!(added_monitors.len(), 1);
2084 added_monitors.clear();
2086 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2087 assert_eq!(events.len(), 1);
2088 SendEvent::from_event(events.remove(0))
2090 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
2091 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
2092 if idx == num_mpp_parts - 1 {
2093 expect_pending_htlcs_forwardable!(nodes[2]);
2097 // Claim the payment and check that the skimmed fee is as expected.
2098 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
2099 let events = nodes[2].node.get_and_clear_pending_events();
2100 assert_eq!(events.len(), 1);
2102 crate::events::Event::PaymentClaimable {
2103 ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
2105 assert_eq!(payment_hash, payment_hash);
2106 assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
2107 assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
2108 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2110 crate::events::PaymentPurpose::InvoicePayment { payment_preimage: ev_payment_preimage,
2111 payment_secret: ev_payment_secret, .. } =>
2113 assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
2114 assert_eq!(payment_secret, *ev_payment_secret);
2119 _ => panic!("Unexpected event"),
2121 let mut expected_paths_vecs = Vec::new();
2122 let mut expected_paths = Vec::new();
2123 for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
2124 for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
2125 let total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
2126 &nodes[0], &expected_paths[..], &vec![skimmed_fee_msat as u32; num_mpp_parts][..], false,
2128 // The sender doesn't know that the penultimate hop took an extra fee.
2129 expect_payment_sent(&nodes[0], payment_preimage,
2130 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true, true);
2133 #[derive(PartialEq)]
2144 fn automatic_retries() {
2145 do_automatic_retries(AutoRetry::Success);
2146 do_automatic_retries(AutoRetry::Spontaneous);
2147 do_automatic_retries(AutoRetry::FailAttempts);
2148 do_automatic_retries(AutoRetry::FailTimeout);
2149 do_automatic_retries(AutoRetry::FailOnRestart);
2150 do_automatic_retries(AutoRetry::FailOnRetry);
2152 fn do_automatic_retries(test: AutoRetry) {
2153 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
2155 let chanmon_cfgs = create_chanmon_cfgs(3);
2156 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2158 let new_chain_monitor;
2160 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2161 let node_0_deserialized;
2163 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2164 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2165 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2167 // Marshall data to send the payment
2168 #[cfg(feature = "std")]
2169 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2170 #[cfg(not(feature = "std"))]
2171 let payment_expiry_secs = 60 * 60;
2172 let amt_msat = 1000;
2173 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2174 invoice_features.set_variable_length_onion_required();
2175 invoice_features.set_payment_secret_required();
2176 invoice_features.set_basic_mpp_optional();
2177 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2178 .with_expiry_time(payment_expiry_secs as u64)
2179 .with_bolt11_features(invoice_features).unwrap();
2180 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2181 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
2183 macro_rules! pass_failed_attempt_with_retry_along_path {
2184 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
2185 // Send a payment attempt that fails due to lack of liquidity on the second hop
2186 check_added_monitors!(nodes[0], 1);
2187 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2188 let mut update_add = update_0.update_add_htlcs[0].clone();
2189 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
2190 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
2191 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2192 nodes[1].node.process_pending_htlc_forwards();
2193 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
2194 vec![HTLCDestination::NextHopChannel {
2195 node_id: Some(nodes[2].node.get_our_node_id()),
2196 channel_id: $failing_channel_id,
2198 nodes[1].node.process_pending_htlc_forwards();
2199 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2200 check_added_monitors!(&nodes[1], 1);
2201 assert!(update_1.update_fail_htlcs.len() == 1);
2202 let fail_msg = update_1.update_fail_htlcs[0].clone();
2203 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
2204 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
2206 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
2207 let mut events = nodes[0].node.get_and_clear_pending_events();
2208 assert_eq!(events.len(), 2);
2210 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2211 assert_eq!(payment_hash, ev_payment_hash);
2212 assert_eq!(payment_failed_permanently, false);
2214 _ => panic!("Unexpected event"),
2216 if $expect_pending_htlcs_forwardable {
2218 Event::PendingHTLCsForwardable { .. } => {},
2219 _ => panic!("Unexpected event"),
2223 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
2224 assert_eq!(payment_hash, ev_payment_hash);
2226 _ => panic!("Unexpected event"),
2232 if test == AutoRetry::Success {
2233 // Test that we can succeed on the first retry.
2234 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2235 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2236 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2238 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2239 // attempt, since the initial second hop channel will be excluded from pathfinding
2240 create_announced_chan_between_nodes(&nodes, 1, 2);
2242 // We retry payments in `process_pending_htlc_forwards`
2243 nodes[0].node.process_pending_htlc_forwards();
2244 check_added_monitors!(nodes[0], 1);
2245 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2246 assert_eq!(msg_events.len(), 1);
2247 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
2248 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2249 } else if test == AutoRetry::Spontaneous {
2250 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
2251 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
2252 Retry::Attempts(1)).unwrap();
2253 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2255 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2256 // attempt, since the initial second hop channel will be excluded from pathfinding
2257 create_announced_chan_between_nodes(&nodes, 1, 2);
2259 // We retry payments in `process_pending_htlc_forwards`
2260 nodes[0].node.process_pending_htlc_forwards();
2261 check_added_monitors!(nodes[0], 1);
2262 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2263 assert_eq!(msg_events.len(), 1);
2264 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2265 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2266 } else if test == AutoRetry::FailAttempts {
2267 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2268 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2269 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2270 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2272 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2273 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2274 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2276 // We retry payments in `process_pending_htlc_forwards`
2277 nodes[0].node.process_pending_htlc_forwards();
2278 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2280 // Ensure we won't retry a second time.
2281 nodes[0].node.process_pending_htlc_forwards();
2282 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2283 assert_eq!(msg_events.len(), 0);
2284 } else if test == AutoRetry::FailTimeout {
2285 #[cfg(not(feature = "no-std"))] {
2286 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2287 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2288 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2289 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2291 // Advance the time so the second attempt fails due to timeout.
2292 SinceEpoch::advance(Duration::from_secs(61));
2294 // Make sure we don't retry again.
2295 nodes[0].node.process_pending_htlc_forwards();
2296 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2297 assert_eq!(msg_events.len(), 0);
2299 let mut events = nodes[0].node.get_and_clear_pending_events();
2300 assert_eq!(events.len(), 1);
2302 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2303 assert_eq!(payment_hash, *ev_payment_hash);
2304 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2305 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2307 _ => panic!("Unexpected event"),
2310 } else if test == AutoRetry::FailOnRestart {
2311 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2312 // attempts remaining prior to restart.
2313 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2314 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2315 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2317 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2318 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2319 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2321 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2322 nodes[0].node.process_pending_htlc_forwards();
2323 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2325 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2326 let node_encoded = nodes[0].node.encode();
2327 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2328 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2330 let mut events = nodes[0].node.get_and_clear_pending_events();
2331 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2332 // Make sure we don't retry again.
2333 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2334 assert_eq!(msg_events.len(), 0);
2336 let mut events = nodes[0].node.get_and_clear_pending_events();
2337 assert_eq!(events.len(), 1);
2339 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2340 assert_eq!(payment_hash, *ev_payment_hash);
2341 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2342 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2344 _ => panic!("Unexpected event"),
2346 } else if test == AutoRetry::FailOnRetry {
2347 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2348 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2349 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2351 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2352 // fail to find a route.
2353 nodes[0].node.process_pending_htlc_forwards();
2354 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2355 assert_eq!(msg_events.len(), 0);
2357 let mut events = nodes[0].node.get_and_clear_pending_events();
2358 assert_eq!(events.len(), 1);
2360 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2361 assert_eq!(payment_hash, *ev_payment_hash);
2362 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2363 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2365 _ => panic!("Unexpected event"),
2371 fn auto_retry_partial_failure() {
2372 // Test that we'll retry appropriately on send partial failure and retry partial failure.
2373 let chanmon_cfgs = create_chanmon_cfgs(2);
2374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2376 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2378 // Open three channels, the first has plenty of liquidity, the second and third have ~no
2379 // available liquidity, causing any outbound payments routed over it to fail immediately.
2380 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2381 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;
2382 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;
2384 // Marshall data to send the payment
2385 let amt_msat = 10_000_000;
2386 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2387 #[cfg(feature = "std")]
2388 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2389 #[cfg(not(feature = "std"))]
2390 let payment_expiry_secs = 60 * 60;
2391 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2392 invoice_features.set_variable_length_onion_required();
2393 invoice_features.set_payment_secret_required();
2394 invoice_features.set_basic_mpp_optional();
2395 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2396 .with_expiry_time(payment_expiry_secs as u64)
2397 .with_bolt11_features(invoice_features).unwrap();
2398 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2399 route_params.max_total_routing_fee_msat = None;
2401 // Configure the initial send, retry1 and retry2's paths.
2402 let send_route = Route {
2404 Path { hops: vec![RouteHop {
2405 pubkey: nodes[1].node.get_our_node_id(),
2406 node_features: nodes[1].node.node_features(),
2407 short_channel_id: chan_1_id,
2408 channel_features: nodes[1].node.channel_features(),
2409 fee_msat: amt_msat / 2,
2410 cltv_expiry_delta: 100,
2411 maybe_announced_channel: true,
2412 }], blinded_tail: None },
2413 Path { hops: vec![RouteHop {
2414 pubkey: nodes[1].node.get_our_node_id(),
2415 node_features: nodes[1].node.node_features(),
2416 short_channel_id: chan_2_id,
2417 channel_features: nodes[1].node.channel_features(),
2418 fee_msat: amt_msat / 2,
2419 cltv_expiry_delta: 100,
2420 maybe_announced_channel: true,
2421 }], blinded_tail: None },
2423 route_params: Some(route_params.clone()),
2425 let retry_1_route = Route {
2427 Path { hops: vec![RouteHop {
2428 pubkey: nodes[1].node.get_our_node_id(),
2429 node_features: nodes[1].node.node_features(),
2430 short_channel_id: chan_1_id,
2431 channel_features: nodes[1].node.channel_features(),
2432 fee_msat: amt_msat / 4,
2433 cltv_expiry_delta: 100,
2434 maybe_announced_channel: true,
2435 }], blinded_tail: None },
2436 Path { hops: vec![RouteHop {
2437 pubkey: nodes[1].node.get_our_node_id(),
2438 node_features: nodes[1].node.node_features(),
2439 short_channel_id: chan_3_id,
2440 channel_features: nodes[1].node.channel_features(),
2441 fee_msat: amt_msat / 4,
2442 cltv_expiry_delta: 100,
2443 maybe_announced_channel: true,
2444 }], blinded_tail: None },
2446 route_params: Some(route_params.clone()),
2448 let retry_2_route = Route {
2450 Path { hops: vec![RouteHop {
2451 pubkey: nodes[1].node.get_our_node_id(),
2452 node_features: nodes[1].node.node_features(),
2453 short_channel_id: chan_1_id,
2454 channel_features: nodes[1].node.channel_features(),
2455 fee_msat: amt_msat / 4,
2456 cltv_expiry_delta: 100,
2457 maybe_announced_channel: true,
2458 }], blinded_tail: None },
2460 route_params: Some(route_params.clone()),
2462 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2463 let mut payment_params = route_params.payment_params.clone();
2464 payment_params.previously_failed_channels.push(chan_2_id);
2466 let mut retry_1_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 2);
2467 retry_1_params.max_total_routing_fee_msat = None;
2468 nodes[0].router.expect_find_route(retry_1_params, Ok(retry_1_route));
2470 let mut payment_params = route_params.payment_params.clone();
2471 payment_params.previously_failed_channels.push(chan_3_id);
2472 let mut retry_2_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 4);
2473 retry_2_params.max_total_routing_fee_msat = None;
2474 nodes[0].router.expect_find_route(retry_2_params, Ok(retry_2_route));
2476 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2477 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2478 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2479 let payment_failed_events = nodes[0].node.get_and_clear_pending_events();
2480 assert_eq!(payment_failed_events.len(), 2);
2481 match payment_failed_events[0] {
2482 Event::PaymentPathFailed { .. } => {},
2483 _ => panic!("Unexpected event"),
2485 match payment_failed_events[1] {
2486 Event::PaymentPathFailed { .. } => {},
2487 _ => panic!("Unexpected event"),
2490 // Pass the first part of the payment along the path.
2491 check_added_monitors!(nodes[0], 1); // only one HTLC actually made it out
2492 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2494 // Only one HTLC/channel update actually made it out
2495 assert_eq!(msg_events.len(), 1);
2496 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2498 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2499 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2500 check_added_monitors!(nodes[1], 1);
2501 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2503 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2504 check_added_monitors!(nodes[0], 1);
2505 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2507 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2508 check_added_monitors!(nodes[0], 1);
2509 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2511 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2512 check_added_monitors!(nodes[1], 1);
2514 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2515 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2516 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2517 check_added_monitors!(nodes[1], 1);
2518 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2520 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2521 check_added_monitors!(nodes[0], 1);
2523 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2524 check_added_monitors!(nodes[0], 1);
2525 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2527 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2528 check_added_monitors!(nodes[1], 1);
2530 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2531 nodes[1].node.process_pending_htlc_forwards();
2532 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2533 nodes[1].node.claim_funds(payment_preimage);
2534 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2535 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2536 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2538 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2539 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
2540 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2541 check_added_monitors!(nodes[0], 1);
2542 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2544 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2545 check_added_monitors!(nodes[1], 4);
2546 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2548 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2549 check_added_monitors!(nodes[1], 1);
2550 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2552 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2553 check_added_monitors!(nodes[0], 1);
2554 expect_payment_path_successful!(nodes[0]);
2556 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2557 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2558 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2559 check_added_monitors!(nodes[0], 1);
2560 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2562 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2563 check_added_monitors!(nodes[1], 1);
2565 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2566 check_added_monitors!(nodes[1], 1);
2567 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2569 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2570 check_added_monitors!(nodes[0], 1);
2571 let events = nodes[0].node.get_and_clear_pending_events();
2572 assert_eq!(events.len(), 2);
2573 if let Event::PaymentPathSuccessful { .. } = events[0] {} else { panic!(); }
2574 if let Event::PaymentPathSuccessful { .. } = events[1] {} else { panic!(); }
2578 fn auto_retry_zero_attempts_send_error() {
2579 let chanmon_cfgs = create_chanmon_cfgs(2);
2580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2582 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2584 // Open a single channel that does not have sufficient liquidity for the payment we want to
2586 let chan_id = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 989_000_000).0.contents.short_channel_id;
2588 // Marshall data to send the payment
2589 let amt_msat = 10_000_000;
2590 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(amt_msat), None);
2591 #[cfg(feature = "std")]
2592 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2593 #[cfg(not(feature = "std"))]
2594 let payment_expiry_secs = 60 * 60;
2595 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2596 invoice_features.set_variable_length_onion_required();
2597 invoice_features.set_payment_secret_required();
2598 invoice_features.set_basic_mpp_optional();
2599 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2600 .with_expiry_time(payment_expiry_secs as u64)
2601 .with_bolt11_features(invoice_features).unwrap();
2602 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2604 // Override the route search to return a route, rather than failing at the route-finding step.
2605 let send_route = Route {
2607 Path { hops: vec![RouteHop {
2608 pubkey: nodes[1].node.get_our_node_id(),
2609 node_features: nodes[1].node.node_features(),
2610 short_channel_id: chan_id,
2611 channel_features: nodes[1].node.channel_features(),
2613 cltv_expiry_delta: 100,
2614 maybe_announced_channel: true,
2615 }], blinded_tail: None },
2617 route_params: Some(route_params.clone()),
2619 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2621 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2622 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2623 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2624 let events = nodes[0].node.get_and_clear_pending_events();
2625 assert_eq!(events.len(), 2);
2626 if let Event::PaymentPathFailed { .. } = events[0] { } else { panic!(); }
2627 if let Event::PaymentFailed { .. } = events[1] { } else { panic!(); }
2628 check_added_monitors!(nodes[0], 0);
2632 fn fails_paying_after_rejected_by_payee() {
2633 let chanmon_cfgs = create_chanmon_cfgs(2);
2634 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2635 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2636 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2638 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2640 // Marshall data to send the payment
2641 let amt_msat = 20_000;
2642 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2643 #[cfg(feature = "std")]
2644 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2645 #[cfg(not(feature = "std"))]
2646 let payment_expiry_secs = 60 * 60;
2647 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2648 invoice_features.set_variable_length_onion_required();
2649 invoice_features.set_payment_secret_required();
2650 invoice_features.set_basic_mpp_optional();
2651 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2652 .with_expiry_time(payment_expiry_secs as u64)
2653 .with_bolt11_features(invoice_features).unwrap();
2654 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2656 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2657 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2658 check_added_monitors!(nodes[0], 1);
2659 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2660 assert_eq!(events.len(), 1);
2661 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2662 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2663 check_added_monitors!(nodes[1], 0);
2664 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2665 expect_pending_htlcs_forwardable!(nodes[1]);
2666 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2668 nodes[1].node.fail_htlc_backwards(&payment_hash);
2669 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2670 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2674 fn retry_multi_path_single_failed_payment() {
2675 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2676 let chanmon_cfgs = create_chanmon_cfgs(2);
2677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2679 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2681 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2682 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2684 let amt_msat = 100_010_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 mut route_params = RouteParameters::from_payment_params_and_value(
2699 payment_params.clone(), amt_msat);
2700 route_params.max_total_routing_fee_msat = None;
2702 let chans = nodes[0].node.list_usable_channels();
2703 let mut route = Route {
2705 Path { hops: vec![RouteHop {
2706 pubkey: nodes[1].node.get_our_node_id(),
2707 node_features: nodes[1].node.node_features(),
2708 short_channel_id: chans[0].short_channel_id.unwrap(),
2709 channel_features: nodes[1].node.channel_features(),
2711 cltv_expiry_delta: 100,
2712 maybe_announced_channel: true,
2713 }], blinded_tail: None },
2714 Path { hops: vec![RouteHop {
2715 pubkey: nodes[1].node.get_our_node_id(),
2716 node_features: nodes[1].node.node_features(),
2717 short_channel_id: chans[1].short_channel_id.unwrap(),
2718 channel_features: nodes[1].node.channel_features(),
2719 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2720 cltv_expiry_delta: 100,
2721 maybe_announced_channel: true,
2722 }], blinded_tail: None },
2724 route_params: Some(route_params.clone()),
2726 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2727 // On retry, split the payment across both channels.
2728 route.paths[0].hops[0].fee_msat = 50_000_001;
2729 route.paths[1].hops[0].fee_msat = 50_000_000;
2730 let mut pay_params = route.route_params.clone().unwrap().payment_params;
2731 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2733 // Note that the second request here requests the amount we originally failed to send,
2734 // not the amount remaining on the full payment, which should be changed.
2735 let mut retry_params = RouteParameters::from_payment_params_and_value(pay_params, 100_000_001);
2736 retry_params.max_total_routing_fee_msat = None;
2737 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2740 let scorer = chanmon_cfgs[0].scorer.read().unwrap();
2741 // The initial send attempt, 2 paths
2742 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2743 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2744 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2745 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2746 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2749 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2750 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2751 let events = nodes[0].node.get_and_clear_pending_events();
2752 assert_eq!(events.len(), 1);
2754 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2755 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2756 short_channel_id: Some(expected_scid), .. } =>
2758 assert_eq!(payment_hash, ev_payment_hash);
2759 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2761 _ => panic!("Unexpected event"),
2763 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2764 assert_eq!(htlc_msgs.len(), 2);
2765 check_added_monitors!(nodes[0], 2);
2769 fn immediate_retry_on_failure() {
2770 // Tests that we can/will retry immediately after a failure
2771 let chanmon_cfgs = create_chanmon_cfgs(2);
2772 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2773 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2774 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2776 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2777 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2779 let amt_msat = 100_000_001;
2780 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2781 #[cfg(feature = "std")]
2782 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2783 #[cfg(not(feature = "std"))]
2784 let payment_expiry_secs = 60 * 60;
2785 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2786 invoice_features.set_variable_length_onion_required();
2787 invoice_features.set_payment_secret_required();
2788 invoice_features.set_basic_mpp_optional();
2789 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2790 .with_expiry_time(payment_expiry_secs as u64)
2791 .with_bolt11_features(invoice_features).unwrap();
2792 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2794 let chans = nodes[0].node.list_usable_channels();
2795 let mut route = Route {
2797 Path { hops: vec![RouteHop {
2798 pubkey: nodes[1].node.get_our_node_id(),
2799 node_features: nodes[1].node.node_features(),
2800 short_channel_id: chans[0].short_channel_id.unwrap(),
2801 channel_features: nodes[1].node.channel_features(),
2802 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2803 cltv_expiry_delta: 100,
2804 maybe_announced_channel: true,
2805 }], blinded_tail: None },
2807 route_params: Some(RouteParameters::from_payment_params_and_value(
2808 PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV),
2811 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2812 // On retry, split the payment across both channels.
2813 route.paths.push(route.paths[0].clone());
2814 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2815 route.paths[0].hops[0].fee_msat = 50_000_000;
2816 route.paths[1].hops[0].fee_msat = 50_000_001;
2817 let mut pay_params = route_params.payment_params.clone();
2818 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2819 nodes[0].router.expect_find_route(
2820 RouteParameters::from_payment_params_and_value(pay_params, amt_msat),
2823 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2824 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2825 let events = nodes[0].node.get_and_clear_pending_events();
2826 assert_eq!(events.len(), 1);
2828 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2829 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2830 short_channel_id: Some(expected_scid), .. } =>
2832 assert_eq!(payment_hash, ev_payment_hash);
2833 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2835 _ => panic!("Unexpected event"),
2837 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2838 assert_eq!(htlc_msgs.len(), 2);
2839 check_added_monitors!(nodes[0], 2);
2843 fn no_extra_retries_on_back_to_back_fail() {
2844 // In a previous release, we had a race where we may exceed the payment retry count if we
2845 // get two failures in a row with the second indicating that all paths had failed (this field,
2846 // `all_paths_failed`, has since been removed).
2847 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2848 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2849 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2850 // pending which we will see later. Thus, when we previously removed the retry tracking map
2851 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2852 // retry entry even though more events for the same payment were still pending. This led to
2853 // us retrying a payment again even though we'd already given up on it.
2855 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2856 // is used to remove the payment retry counter entries instead. This tests for the specific
2857 // excess-retry case while also testing `PaymentFailed` generation.
2859 let chanmon_cfgs = create_chanmon_cfgs(3);
2860 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2861 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2862 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2864 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2865 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2867 let amt_msat = 200_000_000;
2868 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2869 #[cfg(feature = "std")]
2870 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2871 #[cfg(not(feature = "std"))]
2872 let payment_expiry_secs = 60 * 60;
2873 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2874 invoice_features.set_variable_length_onion_required();
2875 invoice_features.set_payment_secret_required();
2876 invoice_features.set_basic_mpp_optional();
2877 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2878 .with_expiry_time(payment_expiry_secs as u64)
2879 .with_bolt11_features(invoice_features).unwrap();
2880 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2881 route_params.max_total_routing_fee_msat = None;
2883 let mut route = Route {
2885 Path { hops: vec![RouteHop {
2886 pubkey: nodes[1].node.get_our_node_id(),
2887 node_features: nodes[1].node.node_features(),
2888 short_channel_id: chan_1_scid,
2889 channel_features: nodes[1].node.channel_features(),
2890 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2891 cltv_expiry_delta: 100,
2892 maybe_announced_channel: true,
2894 pubkey: nodes[2].node.get_our_node_id(),
2895 node_features: nodes[2].node.node_features(),
2896 short_channel_id: chan_2_scid,
2897 channel_features: nodes[2].node.channel_features(),
2898 fee_msat: 100_000_000,
2899 cltv_expiry_delta: 100,
2900 maybe_announced_channel: true,
2901 }], blinded_tail: None },
2902 Path { hops: vec![RouteHop {
2903 pubkey: nodes[1].node.get_our_node_id(),
2904 node_features: nodes[1].node.node_features(),
2905 short_channel_id: chan_1_scid,
2906 channel_features: nodes[1].node.channel_features(),
2907 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2908 cltv_expiry_delta: 100,
2909 maybe_announced_channel: true,
2911 pubkey: nodes[2].node.get_our_node_id(),
2912 node_features: nodes[2].node.node_features(),
2913 short_channel_id: chan_2_scid,
2914 channel_features: nodes[2].node.channel_features(),
2915 fee_msat: 100_000_000,
2916 cltv_expiry_delta: 100,
2917 maybe_announced_channel: true,
2918 }], blinded_tail: None }
2920 route_params: Some(RouteParameters::from_payment_params_and_value(
2921 PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV),
2924 route.route_params.as_mut().unwrap().max_total_routing_fee_msat = None;
2925 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2926 let mut second_payment_params = route_params.payment_params.clone();
2927 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2928 // On retry, we'll only return one path
2929 route.paths.remove(1);
2930 route.paths[0].hops[1].fee_msat = amt_msat;
2931 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat);
2932 retry_params.max_total_routing_fee_msat = None;
2933 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2935 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2936 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2937 let htlc_updates = SendEvent::from_node(&nodes[0]);
2938 check_added_monitors!(nodes[0], 1);
2939 assert_eq!(htlc_updates.msgs.len(), 1);
2941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2942 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2943 check_added_monitors!(nodes[1], 1);
2944 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2946 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2947 check_added_monitors!(nodes[0], 1);
2948 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2950 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2951 check_added_monitors!(nodes[0], 1);
2952 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2954 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2955 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2956 check_added_monitors!(nodes[1], 1);
2957 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2959 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2960 check_added_monitors!(nodes[1], 1);
2961 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2963 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2964 check_added_monitors!(nodes[0], 1);
2966 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2967 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2968 check_added_monitors!(nodes[0], 1);
2969 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2971 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2972 check_added_monitors!(nodes[1], 1);
2973 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2975 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2976 check_added_monitors!(nodes[1], 1);
2977 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2979 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2980 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2981 check_added_monitors!(nodes[0], 1);
2983 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2984 check_added_monitors!(nodes[0], 1);
2985 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2987 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2988 check_added_monitors!(nodes[1], 1);
2989 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2990 check_added_monitors!(nodes[1], 1);
2991 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2993 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2994 check_added_monitors!(nodes[0], 1);
2996 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2997 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
3000 // Previously, we retried payments in an event consumer, which would retry each
3001 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
3002 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
3003 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
3004 // by adding the `PaymentFailed` event.
3006 // Because we now retry payments as a batch, we simply return a single-path route in the
3007 // second, batched, request, have that fail, ensure the payment was abandoned.
3008 let mut events = nodes[0].node.get_and_clear_pending_events();
3009 assert_eq!(events.len(), 3);
3011 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3012 assert_eq!(payment_hash, ev_payment_hash);
3013 assert_eq!(payment_failed_permanently, false);
3015 _ => panic!("Unexpected event"),
3018 Event::PendingHTLCsForwardable { .. } => {},
3019 _ => panic!("Unexpected event"),
3022 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3023 assert_eq!(payment_hash, ev_payment_hash);
3024 assert_eq!(payment_failed_permanently, false);
3026 _ => panic!("Unexpected event"),
3029 nodes[0].node.process_pending_htlc_forwards();
3030 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3031 check_added_monitors!(nodes[0], 1);
3033 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3034 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3035 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3036 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3037 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
3039 let mut events = nodes[0].node.get_and_clear_pending_events();
3040 assert_eq!(events.len(), 2);
3042 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3043 assert_eq!(payment_hash, ev_payment_hash);
3044 assert_eq!(payment_failed_permanently, false);
3046 _ => panic!("Unexpected event"),
3049 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
3050 assert_eq!(payment_hash, *ev_payment_hash);
3051 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
3052 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
3054 _ => panic!("Unexpected event"),
3059 fn test_simple_partial_retry() {
3060 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
3061 // full amount of the payment, rather than only the missing amount. Here we simply test for
3062 // this by sending a payment with two parts, failing one, and retrying the second. Note that
3063 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
3065 let chanmon_cfgs = create_chanmon_cfgs(3);
3066 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3067 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3068 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3070 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3071 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
3073 let amt_msat = 200_000_000;
3074 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3075 #[cfg(feature = "std")]
3076 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3077 #[cfg(not(feature = "std"))]
3078 let payment_expiry_secs = 60 * 60;
3079 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3080 invoice_features.set_variable_length_onion_required();
3081 invoice_features.set_payment_secret_required();
3082 invoice_features.set_basic_mpp_optional();
3083 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3084 .with_expiry_time(payment_expiry_secs as u64)
3085 .with_bolt11_features(invoice_features).unwrap();
3086 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
3087 route_params.max_total_routing_fee_msat = None;
3089 let mut route = Route {
3091 Path { hops: vec![RouteHop {
3092 pubkey: nodes[1].node.get_our_node_id(),
3093 node_features: nodes[1].node.node_features(),
3094 short_channel_id: chan_1_scid,
3095 channel_features: nodes[1].node.channel_features(),
3096 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
3097 cltv_expiry_delta: 100,
3098 maybe_announced_channel: true,
3100 pubkey: nodes[2].node.get_our_node_id(),
3101 node_features: nodes[2].node.node_features(),
3102 short_channel_id: chan_2_scid,
3103 channel_features: nodes[2].node.channel_features(),
3104 fee_msat: 100_000_000,
3105 cltv_expiry_delta: 100,
3106 maybe_announced_channel: true,
3107 }], blinded_tail: None },
3108 Path { hops: vec![RouteHop {
3109 pubkey: nodes[1].node.get_our_node_id(),
3110 node_features: nodes[1].node.node_features(),
3111 short_channel_id: chan_1_scid,
3112 channel_features: nodes[1].node.channel_features(),
3114 cltv_expiry_delta: 100,
3115 maybe_announced_channel: true,
3117 pubkey: nodes[2].node.get_our_node_id(),
3118 node_features: nodes[2].node.node_features(),
3119 short_channel_id: chan_2_scid,
3120 channel_features: nodes[2].node.channel_features(),
3121 fee_msat: 100_000_000,
3122 cltv_expiry_delta: 100,
3123 maybe_announced_channel: true,
3124 }], blinded_tail: None }
3126 route_params: Some(RouteParameters::from_payment_params_and_value(
3127 PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV),
3130 route.route_params.as_mut().unwrap().max_total_routing_fee_msat = None;
3131 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3132 let mut second_payment_params = route_params.payment_params.clone();
3133 second_payment_params.previously_failed_channels = vec![chan_2_scid];
3134 // On retry, we'll only be asked for one path (or 100k sats)
3135 route.paths.remove(0);
3136 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat / 2);
3137 retry_params.max_total_routing_fee_msat = None;
3138 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
3140 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3141 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
3142 let htlc_updates = SendEvent::from_node(&nodes[0]);
3143 check_added_monitors!(nodes[0], 1);
3144 assert_eq!(htlc_updates.msgs.len(), 1);
3146 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
3147 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
3148 check_added_monitors!(nodes[1], 1);
3149 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3151 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
3152 check_added_monitors!(nodes[0], 1);
3153 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
3155 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
3156 check_added_monitors!(nodes[0], 1);
3157 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3159 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
3160 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
3161 check_added_monitors!(nodes[1], 1);
3162 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3164 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
3165 check_added_monitors!(nodes[1], 1);
3166 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3168 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
3169 check_added_monitors!(nodes[0], 1);
3171 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3172 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
3173 check_added_monitors!(nodes[0], 1);
3174 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3176 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
3177 check_added_monitors!(nodes[1], 1);
3179 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
3180 check_added_monitors!(nodes[1], 1);
3182 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3184 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
3185 check_added_monitors!(nodes[0], 1);
3187 let mut events = nodes[0].node.get_and_clear_pending_events();
3188 assert_eq!(events.len(), 2);
3190 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3191 assert_eq!(payment_hash, ev_payment_hash);
3192 assert_eq!(payment_failed_permanently, false);
3194 _ => panic!("Unexpected event"),
3197 Event::PendingHTLCsForwardable { .. } => {},
3198 _ => panic!("Unexpected event"),
3201 nodes[0].node.process_pending_htlc_forwards();
3202 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3203 check_added_monitors!(nodes[0], 1);
3205 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3206 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3208 expect_pending_htlcs_forwardable!(nodes[1]);
3209 check_added_monitors!(nodes[1], 1);
3211 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3212 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
3213 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
3214 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
3216 expect_pending_htlcs_forwardable!(nodes[2]);
3217 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
3221 #[cfg(feature = "std")]
3222 fn test_threaded_payment_retries() {
3223 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
3224 // a single thread and would happily let multiple threads run retries at the same time. Because
3225 // retries are done by first calculating the amount we need to retry, then dropping the
3226 // relevant lock, then actually sending, we would happily let multiple threads retry the same
3227 // amount at the same time, overpaying our original HTLC!
3228 let chanmon_cfgs = create_chanmon_cfgs(4);
3229 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3230 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3231 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3233 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
3234 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
3235 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
3236 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
3238 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3239 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
3240 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
3241 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
3243 let amt_msat = 100_000_000;
3244 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3245 #[cfg(feature = "std")]
3246 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3247 #[cfg(not(feature = "std"))]
3248 let payment_expiry_secs = 60 * 60;
3249 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3250 invoice_features.set_variable_length_onion_required();
3251 invoice_features.set_payment_secret_required();
3252 invoice_features.set_basic_mpp_optional();
3253 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3254 .with_expiry_time(payment_expiry_secs as u64)
3255 .with_bolt11_features(invoice_features).unwrap();
3256 let mut route_params = RouteParameters {
3257 payment_params, final_value_msat: amt_msat, max_total_routing_fee_msat: Some(500_000),
3260 let mut route = Route {
3262 Path { hops: vec![RouteHop {
3263 pubkey: nodes[1].node.get_our_node_id(),
3264 node_features: nodes[1].node.node_features(),
3265 short_channel_id: chan_1_scid,
3266 channel_features: nodes[1].node.channel_features(),
3268 cltv_expiry_delta: 100,
3269 maybe_announced_channel: true,
3271 pubkey: nodes[3].node.get_our_node_id(),
3272 node_features: nodes[2].node.node_features(),
3273 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3274 channel_features: nodes[2].node.channel_features(),
3275 fee_msat: amt_msat / 1000,
3276 cltv_expiry_delta: 100,
3277 maybe_announced_channel: true,
3278 }], blinded_tail: None },
3279 Path { hops: vec![RouteHop {
3280 pubkey: nodes[2].node.get_our_node_id(),
3281 node_features: nodes[2].node.node_features(),
3282 short_channel_id: chan_3_scid,
3283 channel_features: nodes[2].node.channel_features(),
3285 cltv_expiry_delta: 100,
3286 maybe_announced_channel: true,
3288 pubkey: nodes[3].node.get_our_node_id(),
3289 node_features: nodes[3].node.node_features(),
3290 short_channel_id: chan_4_scid,
3291 channel_features: nodes[3].node.channel_features(),
3292 fee_msat: amt_msat - amt_msat / 1000,
3293 cltv_expiry_delta: 100,
3294 maybe_announced_channel: true,
3295 }], blinded_tail: None }
3297 route_params: Some(RouteParameters {
3298 payment_params: PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV),
3299 final_value_msat: amt_msat - amt_msat / 1000,
3300 max_total_routing_fee_msat: Some(500_000),
3303 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3305 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3306 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3307 check_added_monitors!(nodes[0], 2);
3308 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3309 assert_eq!(send_msg_events.len(), 2);
3310 send_msg_events.retain(|msg|
3311 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3312 // Drop the commitment update for nodes[2], we can just let that one sit pending
3314 *node_id == nodes[1].node.get_our_node_id()
3315 } else { panic!(); }
3318 // from here on out, the retry `RouteParameters` amount will be amt/1000
3319 route_params.final_value_msat /= 1000;
3322 let end_time = Instant::now() + Duration::from_secs(1);
3323 macro_rules! thread_body { () => { {
3324 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3325 let node_ref = NodePtr::from_node(&nodes[0]);
3327 let node_a = unsafe { &*node_ref.0 };
3328 while Instant::now() < end_time {
3329 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3330 // Ignore if we have any pending events, just always pretend we just got a
3331 // PendingHTLCsForwardable
3332 node_a.node.process_pending_htlc_forwards();
3336 let mut threads = Vec::new();
3337 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3339 // Back in the main thread, poll pending messages and make sure that we never have more than
3340 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3341 // there are HTLC messages shoved in while its running. This allows us to test that we never
3342 // generate an additional update_add_htlc until we've fully failed the first.
3343 let mut previously_failed_channels = Vec::new();
3345 assert_eq!(send_msg_events.len(), 1);
3346 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3347 assert_eq!(send_event.msgs.len(), 1);
3349 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3350 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3352 // Note that we only push one route into `expect_find_route` at a time, because that's all
3353 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3354 // we should still ultimately fail for the same reason - because we're trying to send too
3355 // many HTLCs at once.
3356 let mut new_route_params = route_params.clone();
3357 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3358 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3359 new_route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 100_000);
3360 route.paths[0].hops[1].short_channel_id += 1;
3361 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3363 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3364 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3365 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3366 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3367 // This races with our other threads which may generate an add-HTLCs commitment update via
3368 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3369 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3370 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3371 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3373 let cur_time = Instant::now();
3374 if cur_time > end_time {
3375 for thread in threads.drain(..) { thread.join().unwrap(); }
3378 // Make sure we have some events to handle when we go around...
3379 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3380 nodes[0].node.process_pending_htlc_forwards();
3381 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3382 check_added_monitors!(nodes[0], 2);
3384 if cur_time > end_time {
3390 fn do_no_missing_sent_on_reload(persist_manager_with_payment: bool, at_midpoint: bool) {
3391 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3392 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3393 // it was last persisted.
3394 let chanmon_cfgs = create_chanmon_cfgs(2);
3395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3396 let (persister_a, persister_b, persister_c);
3397 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3398 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3399 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3400 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3402 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3404 let mut nodes_0_serialized = Vec::new();
3405 if !persist_manager_with_payment {
3406 nodes_0_serialized = nodes[0].node.encode();
3409 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3411 if persist_manager_with_payment {
3412 nodes_0_serialized = nodes[0].node.encode();
3415 nodes[1].node.claim_funds(our_payment_preimage);
3416 check_added_monitors!(nodes[1], 1);
3417 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3420 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3421 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3422 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3423 check_added_monitors!(nodes[0], 1);
3425 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3426 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
3427 commitment_signed_dance!(nodes[0], nodes[1], htlc_fulfill_updates.commitment_signed, false);
3428 // Ignore the PaymentSent event which is now pending on nodes[0] - if we were to handle it we'd
3429 // be expected to ignore the eventual conflicting PaymentFailed, but by not looking at it we
3430 // expect to get the PaymentSent again later.
3431 check_added_monitors(&nodes[0], 0);
3434 // The ChannelMonitor should always be the latest version, as we're required to persist it
3435 // during the commitment signed handling.
3436 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3437 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3439 let events = nodes[0].node.get_and_clear_pending_events();
3440 assert_eq!(events.len(), 2);
3441 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3442 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3443 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3444 // the double-claim that would otherwise appear at the end of this test.
3445 nodes[0].node.timer_tick_occurred();
3446 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3447 assert_eq!(as_broadcasted_txn.len(), 1);
3449 // Ensure that, even after some time, if we restart we still include *something* in the current
3450 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3451 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3452 // A naive implementation of the fix here would wipe the pending payments set, causing a
3453 // failure event when we restart.
3454 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3456 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3457 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);
3458 let events = nodes[0].node.get_and_clear_pending_events();
3459 assert!(events.is_empty());
3461 // Ensure that we don't generate any further events even after the channel-closing commitment
3462 // transaction is confirmed on-chain.
3463 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3464 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3466 let events = nodes[0].node.get_and_clear_pending_events();
3467 assert!(events.is_empty());
3469 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3470 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);
3471 let events = nodes[0].node.get_and_clear_pending_events();
3472 assert!(events.is_empty());
3473 check_added_monitors(&nodes[0], 1);
3477 fn no_missing_sent_on_midpoint_reload() {
3478 do_no_missing_sent_on_reload(false, true);
3479 do_no_missing_sent_on_reload(true, true);
3483 fn no_missing_sent_on_reload() {
3484 do_no_missing_sent_on_reload(false, false);
3485 do_no_missing_sent_on_reload(true, false);
3488 fn do_claim_from_closed_chan(fail_payment: bool) {
3489 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3490 // received had been closed between when the HTLC was received and when we went to claim it.
3491 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3492 // presumably the sender may retry later. Long ago it also reduced total code in the claim
3495 // However, this doesn't make sense if you're trying to do an atomic swap or some other
3496 // protocol that requires atomicity with some other action - if your money got claimed
3497 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3498 // is an over-optimization - there should be a very, very low likelihood that a channel closes
3499 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3500 // Since we now have code to handle this anyway we should allow it.
3502 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3503 // CLTVs on the paths to different value resulting in a different claim deadline.
3504 let chanmon_cfgs = create_chanmon_cfgs(4);
3505 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3506 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3507 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3509 create_announced_chan_between_nodes(&nodes, 0, 1);
3510 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3511 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3512 create_announced_chan_between_nodes(&nodes, 2, 3);
3514 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3515 let mut route_params = RouteParameters::from_payment_params_and_value(
3516 PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3517 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
3519 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3520 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3521 // Make sure the route is ordered as the B->D path before C->D
3522 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3523 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3525 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3526 // the HTLC is being relayed.
3527 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3528 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3529 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3531 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3532 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3533 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3534 check_added_monitors(&nodes[0], 2);
3535 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3536 send_msgs.sort_by(|a, _| {
3538 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3539 let node_b_id = nodes[1].node.get_our_node_id();
3540 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3543 assert_eq!(send_msgs.len(), 2);
3544 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3545 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3546 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3547 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3549 match receive_event.unwrap() {
3550 Event::PaymentClaimable { claim_deadline, .. } => {
3551 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3556 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3558 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3559 - if fail_payment { 0 } else { 2 });
3561 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3562 // and expire both immediately, though, by connecting another 4 blocks.
3563 let reason = HTLCDestination::FailedPayment { payment_hash };
3564 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3565 connect_blocks(&nodes[3], 4);
3566 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3567 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3569 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3570 check_closed_event!(&nodes[1], 1, ClosureReason::HolderForceClosed, false,
3571 [nodes[3].node.get_our_node_id()], 1000000);
3572 check_closed_broadcast(&nodes[1], 1, true);
3573 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3574 assert_eq!(bs_tx.len(), 1);
3576 mine_transaction(&nodes[3], &bs_tx[0]);
3577 check_added_monitors(&nodes[3], 1);
3578 check_closed_broadcast(&nodes[3], 1, true);
3579 check_closed_event!(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false,
3580 [nodes[1].node.get_our_node_id()], 1000000);
3582 nodes[3].node.claim_funds(payment_preimage);
3583 check_added_monitors(&nodes[3], 2);
3584 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3586 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3587 assert_eq!(ds_tx.len(), 1);
3588 check_spends!(&ds_tx[0], &bs_tx[0]);
3590 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3591 check_added_monitors(&nodes[1], 1);
3592 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3594 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3595 check_added_monitors(&nodes[1], 1);
3596 assert_eq!(bs_claims.len(), 1);
3597 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3598 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3599 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3600 } else { panic!(); }
3602 expect_payment_sent!(nodes[0], payment_preimage);
3604 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3605 assert_eq!(ds_claim_msgs.len(), 1);
3606 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3607 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3608 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3609 check_added_monitors(&nodes[2], 1);
3610 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3611 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3613 } else { panic!(); };
3615 assert_eq!(cs_claim_msgs.len(), 1);
3616 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3617 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3618 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3619 } else { panic!(); }
3621 expect_payment_path_successful!(nodes[0]);
3626 fn claim_from_closed_chan() {
3627 do_claim_from_closed_chan(true);
3628 do_claim_from_closed_chan(false);
3632 fn test_custom_tlvs_basic() {
3633 do_test_custom_tlvs(false, false, false);
3634 do_test_custom_tlvs(true, false, false);
3638 fn test_custom_tlvs_explicit_claim() {
3639 // Test that when receiving even custom TLVs the user must explicitly accept in case they
3641 do_test_custom_tlvs(false, true, false);
3642 do_test_custom_tlvs(false, true, true);
3645 fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) {
3646 let chanmon_cfgs = create_chanmon_cfgs(2);
3647 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3648 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None; 2]);
3649 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3651 create_announced_chan_between_nodes(&nodes, 0, 1);
3653 let amt_msat = 100_000;
3654 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat);
3655 let payment_id = PaymentId(our_payment_hash.0);
3656 let custom_tlvs = vec![
3657 (if even_tlvs { 5482373482 } else { 5482373483 }, vec![1, 2, 3, 4]),
3658 (5482373487, vec![0x42u8; 16]),
3660 let onion_fields = RecipientOnionFields {
3661 payment_secret: if spontaneous { None } else { Some(our_payment_secret) },
3662 payment_metadata: None,
3663 custom_tlvs: custom_tlvs.clone()
3666 nodes[0].node.send_spontaneous_payment(&route, Some(our_payment_preimage), onion_fields, payment_id).unwrap();
3668 nodes[0].node.send_payment_with_route(&route, our_payment_hash, onion_fields, payment_id).unwrap();
3670 check_added_monitors(&nodes[0], 1);
3672 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3673 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
3674 let mut payment_event = SendEvent::from_event(ev);
3676 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3677 check_added_monitors!(&nodes[1], 0);
3678 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3679 expect_pending_htlcs_forwardable!(nodes[1]);
3681 let events = nodes[1].node.get_and_clear_pending_events();
3682 assert_eq!(events.len(), 1);
3684 Event::PaymentClaimable { ref onion_fields, .. } => {
3685 assert_eq!(onion_fields.clone().unwrap().custom_tlvs().clone(), custom_tlvs);
3687 _ => panic!("Unexpected event"),
3690 match (known_tlvs, even_tlvs) {
3692 nodes[1].node.claim_funds_with_known_custom_tlvs(our_payment_preimage);
3693 let expected_total_fee_msat = pass_claimed_payment_along_route(&nodes[0], &[&[&nodes[1]]], &[0; 1], false, our_payment_preimage);
3694 expect_payment_sent!(&nodes[0], our_payment_preimage, Some(expected_total_fee_msat));
3697 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3700 nodes[1].node.claim_funds(our_payment_preimage);
3701 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3702 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], expected_destinations);
3703 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, our_payment_hash, PaymentFailureReason::RecipientRejected);
3709 fn test_retry_custom_tlvs() {
3710 // Test that custom TLVs are successfully sent on retries
3711 let chanmon_cfgs = create_chanmon_cfgs(3);
3712 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3713 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3714 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3716 create_announced_chan_between_nodes(&nodes, 0, 1);
3717 let (chan_2_update, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 2, 1);
3720 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3722 let amt_msat = 1_000_000;
3723 let (route, payment_hash, payment_preimage, payment_secret) =
3724 get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
3726 // Initiate the payment
3727 let payment_id = PaymentId(payment_hash.0);
3728 let mut route_params = route.route_params.clone().unwrap();
3730 let custom_tlvs = vec![((1 << 16) + 1, vec![0x42u8; 16])];
3731 let onion_fields = RecipientOnionFields::secret_only(payment_secret);
3732 let onion_fields = onion_fields.with_custom_tlvs(custom_tlvs.clone()).unwrap();
3734 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3735 nodes[0].node.send_payment(payment_hash, onion_fields,
3736 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3737 check_added_monitors!(nodes[0], 1); // one monitor per path
3739 // Add the HTLC along the first hop.
3740 let htlc_updates = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
3741 let msgs::CommitmentUpdate { update_add_htlcs, commitment_signed, .. } = htlc_updates;
3742 assert_eq!(update_add_htlcs.len(), 1);
3743 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_htlcs[0]);
3744 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
3746 // Attempt to forward the payment and complete the path's failure.
3747 expect_pending_htlcs_forwardable!(&nodes[1]);
3748 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1],
3749 vec![HTLCDestination::NextHopChannel {
3750 node_id: Some(nodes[2].node.get_our_node_id()),
3751 channel_id: chan_2_id
3753 check_added_monitors!(nodes[1], 1);
3755 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3756 let msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } = htlc_updates;
3757 assert_eq!(update_fail_htlcs.len(), 1);
3758 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3759 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
3761 let mut events = nodes[0].node.get_and_clear_pending_events();
3763 Event::PendingHTLCsForwardable { .. } => {},
3764 _ => panic!("Unexpected event")
3767 expect_payment_failed_conditions_event(events, payment_hash, false,
3768 PaymentFailedConditions::new().mpp_parts_remain());
3770 // Rebalance the channel so the retry of the payment can succeed.
3771 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3773 // Retry the payment and make sure it succeeds
3774 route_params.payment_params.previously_failed_channels.push(chan_2_update.contents.short_channel_id);
3775 nodes[0].router.expect_find_route(route_params, Ok(route));
3776 nodes[0].node.process_pending_htlc_forwards();
3777 check_added_monitors!(nodes[0], 1);
3778 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3779 assert_eq!(events.len(), 1);
3780 let payment_claimable = pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000,
3781 payment_hash, Some(payment_secret), events.pop().unwrap(), true, None).unwrap();
3782 match payment_claimable {
3783 Event::PaymentClaimable { onion_fields, .. } => {
3784 assert_eq!(onion_fields.unwrap().custom_tlvs(), &custom_tlvs);
3786 _ => panic!("Unexpected event"),
3788 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
3792 fn test_custom_tlvs_consistency() {
3793 let even_type_1 = 1 << 16;
3794 let odd_type_1 = (1 << 16)+ 1;
3795 let even_type_2 = (1 << 16) + 2;
3796 let odd_type_2 = (1 << 16) + 3;
3797 let value_1 = || vec![1, 2, 3, 4];
3798 let differing_value_1 = || vec![1, 2, 3, 5];
3799 let value_2 = || vec![42u8; 16];
3801 // Drop missing odd tlvs
3802 do_test_custom_tlvs_consistency(
3803 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3804 vec![(odd_type_1, value_1())],
3805 Some(vec![(odd_type_1, value_1())]),
3807 // Drop non-matching odd tlvs
3808 do_test_custom_tlvs_consistency(
3809 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3810 vec![(odd_type_1, differing_value_1()), (odd_type_2, value_2())],
3811 Some(vec![(odd_type_2, value_2())]),
3813 // Fail missing even tlvs
3814 do_test_custom_tlvs_consistency(
3815 vec![(odd_type_1, value_1()), (even_type_2, value_2())],
3816 vec![(odd_type_1, value_1())],
3819 // Fail non-matching even tlvs
3820 do_test_custom_tlvs_consistency(
3821 vec![(even_type_1, value_1()), (odd_type_2, value_2())],
3822 vec![(even_type_1, differing_value_1()), (odd_type_2, value_2())],
3827 fn do_test_custom_tlvs_consistency(first_tlvs: Vec<(u64, Vec<u8>)>, second_tlvs: Vec<(u64, Vec<u8>)>,
3828 expected_receive_tlvs: Option<Vec<(u64, Vec<u8>)>>) {
3830 let chanmon_cfgs = create_chanmon_cfgs(4);
3831 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3832 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3833 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3835 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
3836 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
3837 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
3838 let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
3840 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3841 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
3842 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
3843 assert_eq!(route.paths.len(), 2);
3844 route.paths.sort_by(|path_a, _| {
3845 // Sort the path so that the path through nodes[1] comes first
3846 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3847 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
3850 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
3851 let payment_id = PaymentId([42; 32]);
3852 let amt_msat = 15_000_000;
3855 let onion_fields = RecipientOnionFields {
3856 payment_secret: Some(our_payment_secret),
3857 payment_metadata: None,
3858 custom_tlvs: first_tlvs
3860 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
3861 onion_fields.clone(), payment_id, &route).unwrap();
3862 let cur_height = nodes[0].best_block_info().1;
3863 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
3864 onion_fields.clone(), amt_msat, cur_height, payment_id,
3865 &None, session_privs[0]).unwrap();
3866 check_added_monitors!(nodes[0], 1);
3869 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3870 assert_eq!(events.len(), 1);
3871 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, our_payment_hash,
3872 Some(our_payment_secret), events.pop().unwrap(), false, None);
3874 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
3877 let onion_fields = RecipientOnionFields {
3878 payment_secret: Some(our_payment_secret),
3879 payment_metadata: None,
3880 custom_tlvs: second_tlvs
3882 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
3883 onion_fields.clone(), amt_msat, cur_height, payment_id, &None, session_privs[1]).unwrap();
3884 check_added_monitors!(nodes[0], 1);
3887 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3888 assert_eq!(events.len(), 1);
3889 let payment_event = SendEvent::from_event(events.pop().unwrap());
3891 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3892 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
3894 expect_pending_htlcs_forwardable!(nodes[2]);
3895 check_added_monitors!(nodes[2], 1);
3897 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
3898 assert_eq!(events.len(), 1);
3899 let payment_event = SendEvent::from_event(events.pop().unwrap());
3901 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
3902 check_added_monitors!(nodes[3], 0);
3903 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
3905 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3906 nodes[3].node.process_pending_htlc_forwards();
3908 if let Some(expected_tlvs) = expected_receive_tlvs {
3909 // Claim and match expected
3910 let events = nodes[3].node.get_and_clear_pending_events();
3911 assert_eq!(events.len(), 1);
3913 Event::PaymentClaimable { ref onion_fields, .. } => {
3914 assert_eq!(onion_fields.clone().unwrap().custom_tlvs, expected_tlvs);
3916 _ => panic!("Unexpected event"),
3919 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]],
3920 false, our_payment_preimage);
3921 expect_payment_sent(&nodes[0], our_payment_preimage, Some(Some(2000)), true, true);
3924 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3925 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], expected_destinations);
3926 check_added_monitors!(nodes[3], 1);
3928 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
3929 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
3930 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
3932 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![
3933 HTLCDestination::NextHopChannel {
3934 node_id: Some(nodes[3].node.get_our_node_id()),
3935 channel_id: chan_2_3.2
3937 check_added_monitors!(nodes[2], 1);
3939 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
3940 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
3941 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
3943 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true,
3944 PaymentFailedConditions::new().mpp_parts_remain());
3948 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3949 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3950 // another results in the HTLC being rejected.
3952 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3953 // first of which we'll deliver and the second of which we'll fail and then re-send with
3954 // modified payment metadata, which will in turn result in it being failed by the recipient.
3955 let chanmon_cfgs = create_chanmon_cfgs(4);
3956 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3958 let new_chain_monitor;
3960 let mut config = test_default_channel_config();
3961 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3962 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3963 let nodes_0_deserialized;
3965 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3967 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3968 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3969 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3970 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3972 // Pay more than half of each channel's max, requiring MPP
3973 let amt_msat = 750_000_000;
3974 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3975 let payment_id = PaymentId(payment_hash.0);
3976 let payment_metadata = vec![44, 49, 52, 142];
3978 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3979 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3980 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
3982 // Send the MPP payment, delivering the updated commitment state to nodes[1].
3983 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3984 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata), custom_tlvs: vec![],
3985 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3986 check_added_monitors!(nodes[0], 2);
3988 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3989 assert_eq!(send_events.len(), 2);
3990 let first_send = SendEvent::from_event(send_events.pop().unwrap());
3991 let second_send = SendEvent::from_event(send_events.pop().unwrap());
3993 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3994 (&first_send, &second_send)
3996 (&second_send, &first_send)
3998 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3999 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
4001 expect_pending_htlcs_forwardable!(nodes[1]);
4002 check_added_monitors(&nodes[1], 1);
4003 let b_forward_ev = SendEvent::from_node(&nodes[1]);
4004 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
4005 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
4007 expect_pending_htlcs_forwardable!(nodes[3]);
4009 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
4010 // will result in nodes[2] failing the HTLC back.
4011 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4012 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
4014 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
4015 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
4017 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
4018 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
4019 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
4021 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
4022 assert_eq!(payment_fail_retryable_evs.len(), 2);
4023 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
4024 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
4026 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
4027 // stored for our payment.
4029 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
4032 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
4033 // the payment state.
4035 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
4036 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
4037 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
4038 persister, new_chain_monitor, nodes_0_deserialized);
4039 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4040 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
4042 let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
4043 reconnect_args.send_channel_ready = (true, true);
4044 reconnect_nodes(reconnect_args);
4046 // Create a new channel between C and D as A will refuse to retry on the existing one because
4048 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
4050 // Now retry the failed HTLC.
4051 nodes[0].node.process_pending_htlc_forwards();
4052 check_added_monitors(&nodes[0], 1);
4053 let as_resend = SendEvent::from_node(&nodes[0]);
4054 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
4055 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
4057 expect_pending_htlcs_forwardable!(nodes[2]);
4058 check_added_monitors(&nodes[2], 1);
4059 let cs_forward = SendEvent::from_node(&nodes[2]);
4060 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
4061 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
4063 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
4064 // the payment metadata was modified, failing only the one modified HTLC and retaining the
4067 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
4068 nodes[3].node.process_pending_htlc_forwards();
4069 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
4070 &[HTLCDestination::FailedPayment {payment_hash}]);
4071 nodes[3].node.process_pending_htlc_forwards();
4073 check_added_monitors(&nodes[3], 1);
4074 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
4076 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
4077 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
4078 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
4079 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
4081 expect_pending_htlcs_forwardable!(nodes[3]);
4082 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
4083 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
4088 fn test_payment_metadata_consistency() {
4089 do_test_payment_metadata_consistency(true, true);
4090 do_test_payment_metadata_consistency(true, false);
4091 do_test_payment_metadata_consistency(false, true);
4092 do_test_payment_metadata_consistency(false, false);