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.route_params.as_mut().map(|p| p.final_value_msat -= first_path_value);
257 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
259 // Check the remaining max total routing fee for the second attempt accounts only for 1_000 msat
260 // base fee, but not for overpaid value of the first try.
261 route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 1000);
262 nodes[0].router.expect_find_route(route_params, Ok(route));
263 nodes[0].node.process_pending_htlc_forwards();
265 check_added_monitors!(nodes[0], 1);
266 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
267 assert_eq!(events.len(), 1);
268 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], amt_msat, payment_hash,
269 Some(payment_secret), events.pop().unwrap(), true, None);
271 // Can't use claim_payment_along_route as it doesn't support overpayment, so we break out the
272 // individual steps here.
273 let extra_fees = vec![0, total_overpaid_amount];
274 let expected_total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
275 &nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], &extra_fees[..], false,
277 expect_payment_sent!(&nodes[0], payment_preimage, Some(expected_total_fee_msat));
280 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
281 let chanmon_cfgs = create_chanmon_cfgs(4);
282 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
283 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
284 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
286 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
287 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
288 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
289 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
291 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
292 let path = route.paths[0].clone();
293 route.paths.push(path);
294 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
295 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
296 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
297 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
298 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
299 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
301 // Initiate the MPP payment.
302 nodes[0].node.send_payment_with_route(&route, payment_hash,
303 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
304 check_added_monitors!(nodes[0], 2); // one monitor per path
305 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
306 assert_eq!(events.len(), 2);
308 // Pass half of the payment along the first path.
309 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
310 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
312 if send_partial_mpp {
313 // Time out the partial MPP
314 for _ in 0..MPP_TIMEOUT_TICKS {
315 nodes[3].node.timer_tick_occurred();
318 // Failed HTLC from node 3 -> 1
319 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
320 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
321 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
322 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
323 check_added_monitors!(nodes[3], 1);
324 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
326 // Failed HTLC from node 1 -> 0
327 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 }]);
328 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
329 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
330 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
331 check_added_monitors!(nodes[1], 1);
332 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
334 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
336 // Pass half of the payment along the second path.
337 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
338 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
340 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
341 for _ in 0..MPP_TIMEOUT_TICKS {
342 nodes[3].node.timer_tick_occurred();
345 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
350 fn mpp_receive_timeout() {
351 do_mpp_receive_timeout(true);
352 do_mpp_receive_timeout(false);
356 fn test_keysend_payments() {
357 do_test_keysend_payments(false, false);
358 do_test_keysend_payments(false, true);
359 do_test_keysend_payments(true, false);
360 do_test_keysend_payments(true, true);
363 fn do_test_keysend_payments(public_node: bool, with_retry: bool) {
364 let chanmon_cfgs = create_chanmon_cfgs(2);
365 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
366 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
367 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
370 create_announced_chan_between_nodes(&nodes, 0, 1);
372 create_chan_between_nodes(&nodes[0], &nodes[1]);
374 let payer_pubkey = nodes[0].node.get_our_node_id();
375 let payee_pubkey = nodes[1].node.get_our_node_id();
376 let route_params = RouteParameters::from_payment_params_and_value(
377 PaymentParameters::for_keysend(payee_pubkey, 40, false), 10000);
379 let network_graph = nodes[0].network_graph.clone();
380 let channels = nodes[0].node.list_usable_channels();
381 let first_hops = channels.iter().collect::<Vec<_>>();
382 let first_hops = if public_node { None } else { Some(first_hops.as_slice()) };
384 let scorer = test_utils::TestScorer::new();
385 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
386 let route = find_route(
387 &payer_pubkey, &route_params, &network_graph, first_hops,
388 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
392 let test_preimage = PaymentPreimage([42; 32]);
394 nodes[0].node.send_spontaneous_payment_with_retry(Some(test_preimage),
395 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0),
396 route_params, Retry::Attempts(1)).unwrap()
398 nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
399 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap()
402 check_added_monitors!(nodes[0], 1);
403 let send_event = SendEvent::from_node(&nodes[0]);
404 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
405 do_commitment_signed_dance(&nodes[1], &nodes[0], &send_event.commitment_msg, false, false);
406 expect_pending_htlcs_forwardable!(nodes[1]);
407 // Previously, a refactor caused us to stop including the payment preimage in the onion which
408 // is sent as a part of keysend payments. Thus, to be extra careful here, we scope the preimage
409 // above to demonstrate that we have no way to get the preimage at this point except by
410 // extracting it from the onion nodes[1] received.
411 let event = nodes[1].node.get_and_clear_pending_events();
412 assert_eq!(event.len(), 1);
413 if let Event::PaymentClaimable { purpose: PaymentPurpose::SpontaneousPayment(preimage), .. } = event[0] {
414 claim_payment(&nodes[0], &[&nodes[1]], preimage);
419 fn test_mpp_keysend() {
420 let mut mpp_keysend_config = test_default_channel_config();
421 mpp_keysend_config.accept_mpp_keysend = true;
422 let chanmon_cfgs = create_chanmon_cfgs(4);
423 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
424 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
425 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
427 create_announced_chan_between_nodes(&nodes, 0, 1);
428 create_announced_chan_between_nodes(&nodes, 0, 2);
429 create_announced_chan_between_nodes(&nodes, 1, 3);
430 create_announced_chan_between_nodes(&nodes, 2, 3);
431 let network_graph = nodes[0].network_graph.clone();
433 let payer_pubkey = nodes[0].node.get_our_node_id();
434 let payee_pubkey = nodes[3].node.get_our_node_id();
435 let recv_value = 15_000_000;
436 let route_params = RouteParameters::from_payment_params_and_value(
437 PaymentParameters::for_keysend(payee_pubkey, 40, true), recv_value);
438 let scorer = test_utils::TestScorer::new();
439 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
440 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger,
441 &scorer, &Default::default(), &random_seed_bytes).unwrap();
443 let payment_preimage = PaymentPreimage([42; 32]);
444 let payment_secret = PaymentSecret(payment_preimage.0);
445 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
446 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_preimage.0)).unwrap();
447 check_added_monitors!(nodes[0], 2);
449 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
450 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
451 assert_eq!(events.len(), 2);
453 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
454 pass_along_path(&nodes[0], expected_route[0], recv_value, payment_hash.clone(),
455 Some(payment_secret), ev.clone(), false, Some(payment_preimage));
457 let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
458 pass_along_path(&nodes[0], expected_route[1], recv_value, payment_hash.clone(),
459 Some(payment_secret), ev.clone(), true, Some(payment_preimage));
460 claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
464 fn test_reject_mpp_keysend_htlc() {
465 // This test enforces that we reject MPP keysend HTLCs if our config states we don't support
466 // MPP keysend. When receiving a payment, if we don't support MPP keysend we'll reject the
467 // payment if it's keysend and has a payment secret, never reaching our payment validation
468 // logic. To check that we enforce rejecting MPP keysends in our payment logic, here we send
469 // keysend payments without payment secrets, then modify them by adding payment secrets in the
470 // final node in between receiving the HTLCs and actually processing them.
471 let mut reject_mpp_keysend_cfg = test_default_channel_config();
472 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
474 let chanmon_cfgs = create_chanmon_cfgs(4);
475 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
476 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(reject_mpp_keysend_cfg)]);
477 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
478 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
479 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
480 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
481 let (update_a, _, chan_4_channel_id, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
482 let chan_4_id = update_a.contents.short_channel_id;
484 let (mut route, payment_hash, payment_preimage, _) = get_route_and_payment_hash!(nodes[0], nodes[3], amount);
486 // Pay along nodes[1]
487 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
488 route.paths[0].hops[0].short_channel_id = chan_1_id;
489 route.paths[0].hops[1].short_channel_id = chan_3_id;
491 let payment_id_0 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
492 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_0).unwrap();
493 check_added_monitors!(nodes[0], 1);
495 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
496 let update_add_0 = update_0.update_add_htlcs[0].clone();
497 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
498 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
499 expect_pending_htlcs_forwardable!(nodes[1]);
501 check_added_monitors!(&nodes[1], 1);
502 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[3].node.get_our_node_id());
503 let update_add_1 = update_1.update_add_htlcs[0].clone();
504 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
505 commitment_signed_dance!(nodes[3], nodes[1], update_1.commitment_signed, false, true);
507 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
508 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
509 for f in pending_forwards.iter_mut() {
511 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
512 match forward_info.routing {
513 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
514 *payment_data = Some(msgs::FinalOnionHopData {
515 payment_secret: PaymentSecret([42; 32]),
516 total_msat: amount * 2,
519 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
526 expect_pending_htlcs_forwardable!(nodes[3]);
528 // Pay along nodes[2]
529 route.paths[0].hops[0].pubkey = nodes[2].node.get_our_node_id();
530 route.paths[0].hops[0].short_channel_id = chan_2_id;
531 route.paths[0].hops[1].short_channel_id = chan_4_id;
533 let payment_id_1 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
534 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
535 check_added_monitors!(nodes[0], 1);
537 let update_2 = get_htlc_update_msgs!(nodes[0], nodes[2].node.get_our_node_id());
538 let update_add_2 = update_2.update_add_htlcs[0].clone();
539 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_2);
540 commitment_signed_dance!(nodes[2], nodes[0], &update_2.commitment_signed, false, true);
541 expect_pending_htlcs_forwardable!(nodes[2]);
543 check_added_monitors!(&nodes[2], 1);
544 let update_3 = get_htlc_update_msgs!(nodes[2], nodes[3].node.get_our_node_id());
545 let update_add_3 = update_3.update_add_htlcs[0].clone();
546 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &update_add_3);
547 commitment_signed_dance!(nodes[3], nodes[2], update_3.commitment_signed, false, true);
549 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
550 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
551 for f in pending_forwards.iter_mut() {
553 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
554 match forward_info.routing {
555 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
556 *payment_data = Some(msgs::FinalOnionHopData {
557 payment_secret: PaymentSecret([42; 32]),
558 total_msat: amount * 2,
561 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
568 expect_pending_htlcs_forwardable!(nodes[3]);
569 check_added_monitors!(nodes[3], 1);
571 // Fail back along nodes[2]
572 let update_fail_0 = get_htlc_update_msgs!(&nodes[3], &nodes[2].node.get_our_node_id());
573 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &update_fail_0.update_fail_htlcs[0]);
574 commitment_signed_dance!(nodes[2], nodes[3], update_fail_0.commitment_signed, false);
575 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 }]);
576 check_added_monitors!(nodes[2], 1);
578 let update_fail_1 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
579 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_1.update_fail_htlcs[0]);
580 commitment_signed_dance!(nodes[0], nodes[2], update_fail_1.commitment_signed, false);
582 expect_payment_failed_conditions(&nodes[0], payment_hash, true, PaymentFailedConditions::new());
583 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
588 fn no_pending_leak_on_initial_send_failure() {
589 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
590 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
591 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
592 // pending payment forever and never time it out.
593 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
594 // try, and then check that no pending payment is being tracked.
595 let chanmon_cfgs = create_chanmon_cfgs(2);
596 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
597 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
598 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
600 create_announced_chan_between_nodes(&nodes, 0, 1);
602 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
604 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
605 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
607 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
608 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
609 ), true, APIError::ChannelUnavailable { ref err },
610 assert_eq!(err, "Peer for first hop currently disconnected"));
612 assert!(!nodes[0].node.has_pending_payments());
615 fn do_retry_with_no_persist(confirm_before_reload: bool) {
616 // If we send a pending payment and `send_payment` returns success, we should always either
617 // return a payment failure event or a payment success event, and on failure the payment should
620 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
621 // always persisted asynchronously), the ChannelManager has to reload some payment data from
622 // ChannelMonitor(s) in some cases. This tests that reloading.
624 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
625 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
626 // which has separate codepaths for "commitment transaction already confirmed" and not.
627 let chanmon_cfgs = create_chanmon_cfgs(3);
628 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
630 let new_chain_monitor;
631 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
632 let nodes_0_deserialized;
633 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
635 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
636 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
638 // Serialize the ChannelManager prior to sending payments
639 let nodes_0_serialized = nodes[0].node.encode();
641 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
643 let amt_msat = 1_000_000;
644 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
645 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
646 let route_params = route.route_params.unwrap().clone();
647 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
648 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
649 check_added_monitors!(nodes[0], 1);
651 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
652 assert_eq!(events.len(), 1);
653 let payment_event = SendEvent::from_event(events.pop().unwrap());
654 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
656 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
657 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
658 // which would prevent retry.
659 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
660 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
662 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
663 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
664 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
665 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
667 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
669 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
670 if confirm_before_reload {
671 mine_transaction(&nodes[0], &as_commitment_tx);
672 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
675 // The ChannelMonitor should always be the latest version, as we're required to persist it
676 // during the `commitment_signed_dance!()`.
677 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
678 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
680 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
681 // force-close the channel.
682 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
683 assert!(nodes[0].node.list_channels().is_empty());
684 assert!(nodes[0].node.has_pending_payments());
685 nodes[0].node.timer_tick_occurred();
686 if !confirm_before_reload {
687 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
688 assert_eq!(as_broadcasted_txn.len(), 1);
689 assert_eq!(as_broadcasted_txn[0].txid(), as_commitment_tx.txid());
691 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
693 check_added_monitors!(nodes[0], 1);
695 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
696 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
697 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
699 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
701 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
702 // error, as the channel has hit the chain.
703 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
704 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
706 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
707 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
708 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
709 assert_eq!(as_err.len(), 1);
711 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
712 assert_eq!(node_id, nodes[1].node.get_our_node_id());
713 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
714 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 {}",
715 &nodes[1].node.get_our_node_id())) }, [nodes[0].node.get_our_node_id()], 100000);
716 check_added_monitors!(nodes[1], 1);
717 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
719 _ => panic!("Unexpected event"),
721 check_closed_broadcast!(nodes[1], false);
723 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
724 // we close in a moment.
725 nodes[2].node.claim_funds(payment_preimage_1);
726 check_added_monitors!(nodes[2], 1);
727 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
729 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
730 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
731 check_added_monitors!(nodes[1], 1);
732 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
733 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, true, false);
735 if confirm_before_reload {
736 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
737 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
740 // Create a new channel on which to retry the payment before we fail the payment via the
741 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
742 // connecting several blocks while creating the channel (implying time has passed).
743 create_announced_chan_between_nodes(&nodes, 0, 1);
744 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
746 mine_transaction(&nodes[1], &as_commitment_tx);
747 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
748 assert_eq!(bs_htlc_claim_txn.len(), 1);
749 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
751 if !confirm_before_reload {
752 mine_transaction(&nodes[0], &as_commitment_tx);
754 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
755 expect_payment_sent(&nodes[0], payment_preimage_1, None, true, false);
756 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
757 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
758 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
759 assert_eq!(txn.len(), 2);
760 (txn.remove(0), txn.remove(0))
762 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
763 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
764 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
765 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
767 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
769 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
770 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
772 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
773 // reloaded) via a route over the new channel, which work without issue and eventually be
774 // received and claimed at the recipient just like any other payment.
775 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
777 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
778 // and not the original fee. We also update node[1]'s relevant config as
779 // do_claim_payment_along_route expects us to never overpay.
781 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
782 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
783 .unwrap().lock().unwrap();
784 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
785 let mut new_config = channel.context().config();
786 new_config.forwarding_fee_base_msat += 100_000;
787 channel.context_mut().update_config(&new_config);
788 new_route.paths[0].hops[0].fee_msat += 100_000;
791 // Force expiration of the channel's previous config.
792 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
793 nodes[1].node.timer_tick_occurred();
796 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
797 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
798 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
799 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
800 check_added_monitors!(nodes[0], 1);
801 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
802 assert_eq!(events.len(), 1);
803 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
804 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
805 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
809 fn retry_with_no_persist() {
810 do_retry_with_no_persist(true);
811 do_retry_with_no_persist(false);
814 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
815 // Test that an off-chain completed payment is not retryable on restart. This was previously
816 // broken for dust payments, but we test for both dust and non-dust payments.
818 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
820 let chanmon_cfgs = create_chanmon_cfgs(3);
821 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
823 let mut manually_accept_config = test_default_channel_config();
824 manually_accept_config.manually_accept_inbound_channels = true;
827 let first_new_chain_monitor;
828 let second_persister;
829 let second_new_chain_monitor;
831 let third_new_chain_monitor;
833 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
834 let first_nodes_0_deserialized;
835 let second_nodes_0_deserialized;
836 let third_nodes_0_deserialized;
838 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
840 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
841 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
842 confirm_transaction(&nodes[0], &funding_tx);
843 confirm_transaction(&nodes[1], &funding_tx);
844 // Ignore the announcement_signatures messages
845 nodes[0].node.get_and_clear_pending_msg_events();
846 nodes[1].node.get_and_clear_pending_msg_events();
847 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
849 // Serialize the ChannelManager prior to sending payments
850 let mut nodes_0_serialized = nodes[0].node.encode();
852 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
853 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 });
855 // The ChannelMonitor should always be the latest version, as we're required to persist it
856 // during the `commitment_signed_dance!()`.
857 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
859 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);
860 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
862 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
863 // force-close the channel.
864 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
865 nodes[0].node.timer_tick_occurred();
866 assert!(nodes[0].node.list_channels().is_empty());
867 assert!(nodes[0].node.has_pending_payments());
868 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
869 check_added_monitors!(nodes[0], 1);
871 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
872 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
874 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
876 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
877 // error, as the channel has hit the chain.
878 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
879 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
881 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
882 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
883 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
884 assert_eq!(as_err.len(), 1);
885 let bs_commitment_tx;
887 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
888 assert_eq!(node_id, nodes[1].node.get_our_node_id());
889 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
890 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())) }
891 , [nodes[0].node.get_our_node_id()], 100000);
892 check_added_monitors!(nodes[1], 1);
893 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
895 _ => panic!("Unexpected event"),
897 check_closed_broadcast!(nodes[1], false);
899 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
900 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
901 // incoming HTLCs with the same payment hash later.
902 nodes[2].node.fail_htlc_backwards(&payment_hash);
903 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
904 check_added_monitors!(nodes[2], 1);
906 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
907 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
908 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
909 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
910 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
912 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
913 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
914 // after the commitment transaction, so always connect the commitment transaction.
915 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
916 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
918 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
919 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
920 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
921 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
922 assert_eq!(as_htlc_timeout.len(), 1);
924 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
925 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
926 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
927 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
930 // Create a new channel on which to retry the payment before we fail the payment via the
931 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
932 // connecting several blocks while creating the channel (implying time has passed).
933 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
934 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
935 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
937 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
938 // confirming, we will fail as it's considered still-pending...
939 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
940 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
941 Err(PaymentSendFailure::DuplicatePayment) => {},
942 _ => panic!("Unexpected error")
944 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
946 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
947 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
948 // (which should also still work).
949 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
950 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
951 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
953 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
954 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
955 nodes_0_serialized = nodes[0].node.encode();
957 // After the payment failed, we're free to send it again.
958 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
959 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
960 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
962 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);
963 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
965 nodes[0].node.test_process_background_events();
966 check_added_monitors(&nodes[0], 1);
968 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
969 reconnect_args.send_channel_ready = (true, true);
970 reconnect_nodes(reconnect_args);
972 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
973 // the payment is not (spuriously) listed as still pending.
974 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
975 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
976 check_added_monitors!(nodes[0], 1);
977 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
978 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
980 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
981 Err(PaymentSendFailure::DuplicatePayment) => {},
982 _ => panic!("Unexpected error")
984 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
986 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
987 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
988 nodes_0_serialized = nodes[0].node.encode();
990 // Check that after reload we can send the payment again (though we shouldn't, since it was
991 // claimed previously).
992 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);
993 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
995 nodes[0].node.test_process_background_events();
996 check_added_monitors(&nodes[0], 1);
998 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1000 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
1001 Err(PaymentSendFailure::DuplicatePayment) => {},
1002 _ => panic!("Unexpected error")
1004 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1008 fn test_completed_payment_not_retryable_on_reload() {
1009 do_test_completed_payment_not_retryable_on_reload(true);
1010 do_test_completed_payment_not_retryable_on_reload(false);
1014 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
1015 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
1016 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
1017 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
1018 // the ChannelMonitor tells it to.
1020 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
1021 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
1022 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
1023 let chanmon_cfgs = create_chanmon_cfgs(2);
1024 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1026 let new_chain_monitor;
1027 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1028 let nodes_0_deserialized;
1029 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1031 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
1033 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
1035 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
1036 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
1037 check_closed_broadcast!(nodes[0], true);
1038 check_added_monitors!(nodes[0], 1);
1039 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
1041 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1042 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
1044 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
1045 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
1046 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1047 assert_eq!(node_txn.len(), 3);
1048 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
1049 check_spends!(node_txn[1], funding_tx);
1050 check_spends!(node_txn[2], node_txn[1]);
1051 let timeout_txn = vec![node_txn[2].clone()];
1053 nodes[1].node.claim_funds(payment_preimage);
1054 check_added_monitors!(nodes[1], 1);
1055 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
1057 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[1].clone()]));
1058 check_closed_broadcast!(nodes[1], true);
1059 check_added_monitors!(nodes[1], 1);
1060 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
1061 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1062 assert_eq!(claim_txn.len(), 1);
1063 check_spends!(claim_txn[0], node_txn[1]);
1065 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[1].clone()]));
1067 if confirm_commitment_tx {
1068 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
1071 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] });
1073 if payment_timeout {
1074 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
1075 connect_block(&nodes[0], &claim_block);
1076 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
1079 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
1080 // returning InProgress. This should cause the claim event to never make its way to the
1082 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
1083 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
1085 if payment_timeout {
1086 connect_blocks(&nodes[0], 1);
1088 connect_block(&nodes[0], &claim_block);
1091 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
1092 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
1093 .get_mut(&funding_txo).unwrap().drain().collect();
1094 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
1095 // If we're testing connection idempotency we may get substantially more.
1096 assert!(mon_updates.len() >= 1);
1097 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
1098 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1100 // If we persist the ChannelManager here, we should get the PaymentSent event after
1102 let mut chan_manager_serialized = Vec::new();
1103 if !persist_manager_post_event {
1104 chan_manager_serialized = nodes[0].node.encode();
1107 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
1108 // payment sent event.
1109 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1110 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1111 for update in mon_updates {
1112 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
1114 if payment_timeout {
1115 expect_payment_failed!(nodes[0], payment_hash, false);
1117 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1120 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
1122 if persist_manager_post_event {
1123 chan_manager_serialized = nodes[0].node.encode();
1126 // Now reload nodes[0]...
1127 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
1129 if persist_manager_post_event {
1130 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1131 } else if payment_timeout {
1132 expect_payment_failed!(nodes[0], payment_hash, false);
1134 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1137 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
1138 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
1139 // payment events should kick in, leaving us with no pending events here.
1140 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
1141 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
1142 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1143 check_added_monitors(&nodes[0], 1);
1147 fn test_dup_htlc_onchain_fails_on_reload() {
1148 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
1149 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
1150 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
1151 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
1152 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
1153 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
1157 fn test_fulfill_restart_failure() {
1158 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
1159 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
1160 // again, or fail it, giving us free money.
1162 // Of course probably they won't fail it and give us free money, but because we have code to
1163 // handle it, we should test the logic for it anyway. We do that here.
1164 let chanmon_cfgs = create_chanmon_cfgs(2);
1165 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1167 let new_chain_monitor;
1168 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1169 let nodes_1_deserialized;
1170 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1172 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1173 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
1175 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
1176 // pre-fulfill, which we do by serializing it here.
1177 let chan_manager_serialized = nodes[1].node.encode();
1178 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1180 nodes[1].node.claim_funds(payment_preimage);
1181 check_added_monitors!(nodes[1], 1);
1182 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1184 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1185 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1186 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
1188 // Now reload nodes[1]...
1189 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1191 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1192 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1194 nodes[1].node.fail_htlc_backwards(&payment_hash);
1195 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1196 check_added_monitors!(nodes[1], 1);
1197 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1198 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1199 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1200 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1201 // it had already considered the payment fulfilled, and now they just got free money.
1202 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1206 fn get_ldk_payment_preimage() {
1207 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1208 let chanmon_cfgs = create_chanmon_cfgs(2);
1209 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1210 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1211 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1212 create_announced_chan_between_nodes(&nodes, 0, 1);
1214 let amt_msat = 60_000;
1215 let expiry_secs = 60 * 60;
1216 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1218 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1219 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
1220 let scorer = test_utils::TestScorer::new();
1221 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1222 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1223 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
1224 let route = get_route( &nodes[0].node.get_our_node_id(), &route_params,
1225 &nodes[0].network_graph.read_only(),
1226 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()), nodes[0].logger,
1227 &scorer, &Default::default(), &random_seed_bytes).unwrap();
1228 nodes[0].node.send_payment_with_route(&route, payment_hash,
1229 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1230 check_added_monitors!(nodes[0], 1);
1232 // Make sure to use `get_payment_preimage`
1233 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1234 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1235 assert_eq!(events.len(), 1);
1236 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1237 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1241 fn sent_probe_is_probe_of_sending_node() {
1242 let chanmon_cfgs = create_chanmon_cfgs(3);
1243 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1244 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1245 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1247 create_announced_chan_between_nodes(&nodes, 0, 1);
1248 create_announced_chan_between_nodes(&nodes, 1, 2);
1250 // First check we refuse to build a single-hop probe
1251 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1252 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1254 // Then build an actual two-hop probing path
1255 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1257 match nodes[0].node.send_probe(route.paths[0].clone()) {
1258 Ok((payment_hash, payment_id)) => {
1259 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1260 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1261 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1266 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1267 check_added_monitors!(nodes[0], 1);
1271 fn successful_probe_yields_event() {
1272 let chanmon_cfgs = create_chanmon_cfgs(3);
1273 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1274 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1275 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1277 create_announced_chan_between_nodes(&nodes, 0, 1);
1278 create_announced_chan_between_nodes(&nodes, 1, 2);
1280 let recv_value = 100_000;
1281 let (route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], recv_value);
1283 let res = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1285 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[2]]];
1287 send_probe_along_route(&nodes[0], expected_route);
1289 expect_probe_successful_events(&nodes[0], vec![res]);
1291 assert!(!nodes[0].node.has_pending_payments());
1295 fn failed_probe_yields_event() {
1296 let chanmon_cfgs = create_chanmon_cfgs(3);
1297 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1298 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1299 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1301 create_announced_chan_between_nodes(&nodes, 0, 1);
1302 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1304 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1306 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 9_998_000);
1308 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1310 // node[0] -- update_add_htlcs -> node[1]
1311 check_added_monitors!(nodes[0], 1);
1312 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1313 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1314 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1315 check_added_monitors!(nodes[1], 0);
1316 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1317 expect_pending_htlcs_forwardable!(nodes[1]);
1319 // node[0] <- update_fail_htlcs -- node[1]
1320 check_added_monitors!(nodes[1], 1);
1321 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1322 // Skip the PendingHTLCsForwardable event
1323 let _events = nodes[1].node.get_and_clear_pending_events();
1324 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1325 check_added_monitors!(nodes[0], 0);
1326 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1328 let mut events = nodes[0].node.get_and_clear_pending_events();
1329 assert_eq!(events.len(), 1);
1330 match events.drain(..).next().unwrap() {
1331 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1332 assert_eq!(payment_id, ev_pid);
1333 assert_eq!(payment_hash, ev_ph);
1337 assert!(!nodes[0].node.has_pending_payments());
1341 fn onchain_failed_probe_yields_event() {
1342 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1344 let chanmon_cfgs = create_chanmon_cfgs(3);
1345 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1346 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1347 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1349 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1350 create_announced_chan_between_nodes(&nodes, 1, 2);
1352 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1354 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1355 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 1_000);
1356 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1358 // node[0] -- update_add_htlcs -> node[1]
1359 check_added_monitors!(nodes[0], 1);
1360 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1361 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1362 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1363 check_added_monitors!(nodes[1], 0);
1364 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1365 expect_pending_htlcs_forwardable!(nodes[1]);
1367 check_added_monitors!(nodes[1], 1);
1368 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1370 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1371 // Node A, which after 6 confirmations should result in a probe failure event.
1372 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1373 confirm_transaction(&nodes[0], &bs_txn[0]);
1374 check_closed_broadcast!(&nodes[0], true);
1375 check_added_monitors!(nodes[0], 1);
1377 let mut events = nodes[0].node.get_and_clear_pending_events();
1378 assert_eq!(events.len(), 2);
1379 let mut found_probe_failed = false;
1380 for event in events.drain(..) {
1382 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1383 assert_eq!(payment_id, ev_pid);
1384 assert_eq!(payment_hash, ev_ph);
1385 found_probe_failed = true;
1387 Event::ChannelClosed { .. } => {},
1391 assert!(found_probe_failed);
1392 assert!(!nodes[0].node.has_pending_payments());
1396 fn preflight_probes_yield_event_skip_private_hop() {
1397 let chanmon_cfgs = create_chanmon_cfgs(5);
1398 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1400 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1401 let mut no_htlc_limit_config = test_default_channel_config();
1402 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1404 let user_configs = std::iter::repeat(no_htlc_limit_config).take(5).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1405 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &user_configs);
1406 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1408 // Setup channel topology:
1409 // N0 -(1M:0)- N1 -(1M:0)- N2 -(70k:0)- N3 -(50k:0)- N4
1411 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1412 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
1413 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 70_000, 0);
1414 create_unannounced_chan_between_nodes_with_value(&nodes, 3, 4, 50_000, 0);
1416 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1417 invoice_features.set_basic_mpp_optional();
1419 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
1420 .with_bolt11_features(invoice_features).unwrap();
1422 let recv_value = 50_000_000;
1423 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1424 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1426 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[2], &nodes[3]]];
1428 assert_eq!(res.len(), expected_route.len());
1430 send_probe_along_route(&nodes[0], expected_route);
1432 expect_probe_successful_events(&nodes[0], res.clone());
1434 assert!(!nodes[0].node.has_pending_payments());
1438 fn preflight_probes_yield_event() {
1439 let chanmon_cfgs = create_chanmon_cfgs(4);
1440 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1442 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1443 let mut no_htlc_limit_config = test_default_channel_config();
1444 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1446 let user_configs = std::iter::repeat(no_htlc_limit_config).take(4).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1447 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &user_configs);
1448 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1450 // Setup channel topology:
1451 // (1M:0)- N1 -(30k:0)
1455 // (1M:0)- N2 -(70k:0)
1457 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1458 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1459 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 30_000, 0);
1460 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 70_000, 0);
1462 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1463 invoice_features.set_basic_mpp_optional();
1465 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
1466 .with_bolt11_features(invoice_features).unwrap();
1468 let recv_value = 50_000_000;
1469 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1470 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1472 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
1474 assert_eq!(res.len(), expected_route.len());
1476 send_probe_along_route(&nodes[0], expected_route);
1478 expect_probe_successful_events(&nodes[0], res.clone());
1480 assert!(!nodes[0].node.has_pending_payments());
1484 fn preflight_probes_yield_event_and_skip() {
1485 let chanmon_cfgs = create_chanmon_cfgs(5);
1486 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1488 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1489 let mut no_htlc_limit_config = test_default_channel_config();
1490 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1492 let user_configs = std::iter::repeat(no_htlc_limit_config).take(5).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1493 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &user_configs);
1494 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1496 // Setup channel topology:
1497 // (30k:0)- N2 -(1M:0)
1499 // N0 -(100k:0)-> N1 N4
1501 // (70k:0)- N3 -(1M:0)
1503 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1504 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 30_000, 0);
1505 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 70_000, 0);
1506 create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 1_000_000, 0);
1507 create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0);
1509 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1510 invoice_features.set_basic_mpp_optional();
1512 let payment_params = PaymentParameters::from_node_id(nodes[4].node.get_our_node_id(), TEST_FINAL_CLTV)
1513 .with_bolt11_features(invoice_features).unwrap();
1515 let recv_value = 80_000_000;
1516 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1517 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1519 let expected_route : &[&[&Node]] = &[&[&nodes[1], &nodes[2], &nodes[4]]];
1521 // We check that only one probe was sent, the other one was skipped due to limited liquidity.
1522 assert_eq!(res.len(), 1);
1524 send_probe_along_route(&nodes[0], expected_route);
1526 expect_probe_successful_events(&nodes[0], res.clone());
1528 assert!(!nodes[0].node.has_pending_payments());
1532 fn claimed_send_payment_idempotent() {
1533 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1534 let chanmon_cfgs = create_chanmon_cfgs(2);
1535 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1536 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1537 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1539 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1541 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1542 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1544 macro_rules! check_send_rejected {
1546 // If we try to resend a new payment with a different payment_hash but with the same
1547 // payment_id, it should be rejected.
1548 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1549 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1551 Err(PaymentSendFailure::DuplicatePayment) => {},
1552 _ => panic!("Unexpected send result: {:?}", send_result),
1555 // Further, if we try to send a spontaneous payment with the same payment_id it should
1556 // also be rejected.
1557 let send_result = nodes[0].node.send_spontaneous_payment(
1558 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1560 Err(PaymentSendFailure::DuplicatePayment) => {},
1561 _ => panic!("Unexpected send result: {:?}", send_result),
1566 check_send_rejected!();
1568 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1569 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1570 // we must remain just as idempotent as we were before.
1571 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1573 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1574 nodes[0].node.timer_tick_occurred();
1577 check_send_rejected!();
1579 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1580 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1581 // the payment complete. However, they could have called `send_payment` while the event was
1582 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1583 // after the event is handled a duplicate payment should sitll be rejected.
1584 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1585 check_send_rejected!();
1587 // If relatively little time has passed, a duplicate payment should still fail.
1588 nodes[0].node.timer_tick_occurred();
1589 check_send_rejected!();
1591 // However, after some time has passed (at least more than the one timer tick above), a
1592 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1593 // references to the old payment data.
1594 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1595 nodes[0].node.timer_tick_occurred();
1598 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1599 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1600 check_added_monitors!(nodes[0], 1);
1601 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1602 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1606 fn abandoned_send_payment_idempotent() {
1607 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1609 let chanmon_cfgs = create_chanmon_cfgs(2);
1610 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1611 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1612 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1614 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1616 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1617 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1619 macro_rules! check_send_rejected {
1621 // If we try to resend a new payment with a different payment_hash but with the same
1622 // payment_id, it should be rejected.
1623 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1624 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1626 Err(PaymentSendFailure::DuplicatePayment) => {},
1627 _ => panic!("Unexpected send result: {:?}", send_result),
1630 // Further, if we try to send a spontaneous payment with the same payment_id it should
1631 // also be rejected.
1632 let send_result = nodes[0].node.send_spontaneous_payment(
1633 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1635 Err(PaymentSendFailure::DuplicatePayment) => {},
1636 _ => panic!("Unexpected send result: {:?}", send_result),
1641 check_send_rejected!();
1643 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1644 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1646 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1648 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1649 nodes[0].node.timer_tick_occurred();
1651 check_send_rejected!();
1653 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1655 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1656 // failed payment back.
1657 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1658 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1659 check_added_monitors!(nodes[0], 1);
1660 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1661 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1664 #[derive(PartialEq)]
1665 enum InterceptTest {
1672 fn test_trivial_inflight_htlc_tracking(){
1673 // In this test, we test three scenarios:
1674 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1675 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1676 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1677 let chanmon_cfgs = create_chanmon_cfgs(3);
1678 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1679 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1680 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1682 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1683 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1685 // Send and claim the payment. Inflight HTLCs should be empty.
1686 let (_, payment_hash, _, payment_id) = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1687 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1689 let mut node_0_per_peer_lock;
1690 let mut node_0_peer_state_lock;
1691 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1693 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1694 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1695 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1696 channel_1.context().get_short_channel_id().unwrap()
1698 assert_eq!(chan_1_used_liquidity, None);
1701 let mut node_1_per_peer_lock;
1702 let mut node_1_peer_state_lock;
1703 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1705 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1706 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1707 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1708 channel_2.context().get_short_channel_id().unwrap()
1711 assert_eq!(chan_2_used_liquidity, None);
1713 let pending_payments = nodes[0].node.list_recent_payments();
1714 assert_eq!(pending_payments.len(), 1);
1715 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash), payment_id });
1717 // Remove fulfilled payment
1718 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1719 nodes[0].node.timer_tick_occurred();
1722 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1723 let (payment_preimage, payment_hash, _, payment_id) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1724 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1726 let mut node_0_per_peer_lock;
1727 let mut node_0_peer_state_lock;
1728 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1730 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1731 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1732 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1733 channel_1.context().get_short_channel_id().unwrap()
1735 // First hop accounts for expected 1000 msat fee
1736 assert_eq!(chan_1_used_liquidity, Some(501000));
1739 let mut node_1_per_peer_lock;
1740 let mut node_1_peer_state_lock;
1741 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1743 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1744 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1745 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1746 channel_2.context().get_short_channel_id().unwrap()
1749 assert_eq!(chan_2_used_liquidity, Some(500000));
1751 let pending_payments = nodes[0].node.list_recent_payments();
1752 assert_eq!(pending_payments.len(), 1);
1753 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_id, payment_hash, total_msat: 500000 });
1755 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1756 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1758 // Remove fulfilled payment
1759 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1760 nodes[0].node.timer_tick_occurred();
1763 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1765 let mut node_0_per_peer_lock;
1766 let mut node_0_peer_state_lock;
1767 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1769 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1770 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1771 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1772 channel_1.context().get_short_channel_id().unwrap()
1774 assert_eq!(chan_1_used_liquidity, None);
1777 let mut node_1_per_peer_lock;
1778 let mut node_1_peer_state_lock;
1779 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1781 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1782 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1783 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1784 channel_2.context().get_short_channel_id().unwrap()
1786 assert_eq!(chan_2_used_liquidity, None);
1789 let pending_payments = nodes[0].node.list_recent_payments();
1790 assert_eq!(pending_payments.len(), 0);
1794 fn test_holding_cell_inflight_htlcs() {
1795 let chanmon_cfgs = create_chanmon_cfgs(2);
1796 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1797 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1798 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1799 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1801 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1802 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1804 // Queue up two payments - one will be delivered right away, one immediately goes into the
1805 // holding cell as nodes[0] is AwaitingRAA.
1807 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1808 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1809 check_added_monitors!(nodes[0], 1);
1810 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1811 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1812 check_added_monitors!(nodes[0], 0);
1815 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1818 let mut node_0_per_peer_lock;
1819 let mut node_0_peer_state_lock;
1820 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1822 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1823 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1824 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1825 channel.context().get_short_channel_id().unwrap()
1828 assert_eq!(used_liquidity, Some(2000000));
1831 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1832 nodes[0].node.get_and_clear_pending_msg_events();
1836 fn intercepted_payment() {
1837 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1838 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1839 // payment or (b) fail the payment.
1840 do_test_intercepted_payment(InterceptTest::Forward);
1841 do_test_intercepted_payment(InterceptTest::Fail);
1842 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1843 do_test_intercepted_payment(InterceptTest::Timeout);
1846 fn do_test_intercepted_payment(test: InterceptTest) {
1847 let chanmon_cfgs = create_chanmon_cfgs(3);
1848 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1850 let mut zero_conf_chan_config = test_default_channel_config();
1851 zero_conf_chan_config.manually_accept_inbound_channels = true;
1852 let mut intercept_forwards_config = test_default_channel_config();
1853 intercept_forwards_config.accept_intercept_htlcs = true;
1854 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1856 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1857 let scorer = test_utils::TestScorer::new();
1858 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1860 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1862 let amt_msat = 100_000;
1863 let intercept_scid = nodes[1].node.get_intercept_scid();
1864 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1865 .with_route_hints(vec![
1866 RouteHint(vec![RouteHintHop {
1867 src_node_id: nodes[1].node.get_our_node_id(),
1868 short_channel_id: intercept_scid,
1871 proportional_millionths: 0,
1873 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1874 htlc_minimum_msat: None,
1875 htlc_maximum_msat: None,
1878 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1879 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat,);
1880 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params,
1881 &nodes[0].network_graph.read_only(), None, nodes[0].logger, &scorer, &Default::default(),
1882 &random_seed_bytes).unwrap();
1884 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1885 nodes[0].node.send_payment_with_route(&route, payment_hash,
1886 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1887 let payment_event = {
1889 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1890 assert_eq!(added_monitors.len(), 1);
1891 added_monitors.clear();
1893 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1894 assert_eq!(events.len(), 1);
1895 SendEvent::from_event(events.remove(0))
1897 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1898 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1900 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1901 let events = nodes[1].node.get_and_clear_pending_events();
1902 assert_eq!(events.len(), 1);
1903 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1904 crate::events::Event::HTLCIntercepted {
1905 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1907 assert_eq!(pmt_hash, payment_hash);
1908 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1909 assert_eq!(short_channel_id, intercept_scid);
1910 (intercept_id, expected_outbound_amount_msat)
1915 // Check for unknown channel id error.
1916 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();
1917 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable {
1918 err: format!("Channel with id {} not found for the passed counterparty node_id {}",
1919 log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1921 if test == InterceptTest::Fail {
1922 // Ensure we can fail the intercepted payment back.
1923 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1924 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1925 nodes[1].node.process_pending_htlc_forwards();
1926 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1927 check_added_monitors!(&nodes[1], 1);
1928 assert!(update_fail.update_fail_htlcs.len() == 1);
1929 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1930 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1931 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1933 // Ensure the payment fails with the expected error.
1934 let fail_conditions = PaymentFailedConditions::new()
1935 .blamed_scid(intercept_scid)
1936 .blamed_chan_closed(true)
1937 .expected_htlc_error_data(0x4000 | 10, &[]);
1938 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1939 } else if test == InterceptTest::Forward {
1940 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1941 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1942 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();
1943 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1944 err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
1945 temp_chan_id, nodes[2].node.get_our_node_id()) });
1946 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1948 // Open the just-in-time channel so the payment can then be forwarded.
1949 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1951 // Finally, forward the intercepted payment through and claim it.
1952 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1953 expect_pending_htlcs_forwardable!(nodes[1]);
1955 let payment_event = {
1957 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1958 assert_eq!(added_monitors.len(), 1);
1959 added_monitors.clear();
1961 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1962 assert_eq!(events.len(), 1);
1963 SendEvent::from_event(events.remove(0))
1965 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1966 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1967 expect_pending_htlcs_forwardable!(nodes[2]);
1969 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1970 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1971 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1972 let events = nodes[0].node.get_and_clear_pending_events();
1973 assert_eq!(events.len(), 2);
1975 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1976 assert_eq!(payment_preimage, *ev_preimage);
1977 assert_eq!(payment_hash, *ev_hash);
1978 assert_eq!(fee_paid_msat, &Some(1000));
1980 _ => panic!("Unexpected event")
1983 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1984 assert_eq!(hash, Some(payment_hash));
1986 _ => panic!("Unexpected event")
1988 check_added_monitors(&nodes[0], 1);
1989 } else if test == InterceptTest::Timeout {
1990 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
1991 connect_block(&nodes[0], &block);
1992 connect_block(&nodes[1], &block);
1993 for _ in 0..TEST_FINAL_CLTV {
1994 block.header.prev_blockhash = block.block_hash();
1995 connect_block(&nodes[0], &block);
1996 connect_block(&nodes[1], &block);
1998 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1999 check_added_monitors!(nodes[1], 1);
2000 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2001 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
2002 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
2003 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
2004 assert!(htlc_timeout_updates.update_fee.is_none());
2006 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
2007 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
2008 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
2010 // Check for unknown intercept id error.
2011 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
2012 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();
2013 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2014 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
2015 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2020 fn accept_underpaying_htlcs_config() {
2021 do_accept_underpaying_htlcs_config(1);
2022 do_accept_underpaying_htlcs_config(2);
2023 do_accept_underpaying_htlcs_config(3);
2026 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
2027 let chanmon_cfgs = create_chanmon_cfgs(3);
2028 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2029 let mut intercept_forwards_config = test_default_channel_config();
2030 intercept_forwards_config.accept_intercept_htlcs = true;
2031 let mut underpay_config = test_default_channel_config();
2032 underpay_config.channel_config.accept_underpaying_htlcs = true;
2033 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
2034 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2036 let mut chan_ids = Vec::new();
2037 for _ in 0..num_mpp_parts {
2038 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000, 0);
2039 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 2_000_000, 0).0.channel_id;
2040 chan_ids.push(channel_id);
2043 // Send the initial payment.
2044 let amt_msat = 900_000;
2045 let skimmed_fee_msat = 20;
2046 let mut route_hints = Vec::new();
2047 for _ in 0..num_mpp_parts {
2048 route_hints.push(RouteHint(vec![RouteHintHop {
2049 src_node_id: nodes[1].node.get_our_node_id(),
2050 short_channel_id: nodes[1].node.get_intercept_scid(),
2053 proportional_millionths: 0,
2055 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
2056 htlc_minimum_msat: None,
2057 htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
2060 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2061 .with_route_hints(route_hints).unwrap()
2062 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
2063 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2064 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
2065 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2066 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2067 check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
2068 let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
2069 assert_eq!(events.len(), num_mpp_parts);
2071 // Forward the intercepted payments.
2072 for (idx, ev) in events.into_iter().enumerate() {
2073 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
2074 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
2076 let events = nodes[1].node.get_and_clear_pending_events();
2077 assert_eq!(events.len(), 1);
2078 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
2079 crate::events::Event::HTLCIntercepted {
2080 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
2082 assert_eq!(pmt_hash, payment_hash);
2083 (intercept_id, expected_outbound_amount_msat)
2087 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
2088 nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
2089 expect_pending_htlcs_forwardable!(nodes[1]);
2090 let payment_event = {
2092 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2093 assert_eq!(added_monitors.len(), 1);
2094 added_monitors.clear();
2096 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2097 assert_eq!(events.len(), 1);
2098 SendEvent::from_event(events.remove(0))
2100 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
2101 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
2102 if idx == num_mpp_parts - 1 {
2103 expect_pending_htlcs_forwardable!(nodes[2]);
2107 // Claim the payment and check that the skimmed fee is as expected.
2108 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
2109 let events = nodes[2].node.get_and_clear_pending_events();
2110 assert_eq!(events.len(), 1);
2112 crate::events::Event::PaymentClaimable {
2113 ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
2115 assert_eq!(payment_hash, payment_hash);
2116 assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
2117 assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
2118 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2120 crate::events::PaymentPurpose::InvoicePayment { payment_preimage: ev_payment_preimage,
2121 payment_secret: ev_payment_secret, .. } =>
2123 assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
2124 assert_eq!(payment_secret, *ev_payment_secret);
2129 _ => panic!("Unexpected event"),
2131 let mut expected_paths_vecs = Vec::new();
2132 let mut expected_paths = Vec::new();
2133 for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
2134 for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
2135 let total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
2136 &nodes[0], &expected_paths[..], &vec![skimmed_fee_msat as u32; num_mpp_parts][..], false,
2138 // The sender doesn't know that the penultimate hop took an extra fee.
2139 expect_payment_sent(&nodes[0], payment_preimage,
2140 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true, true);
2143 #[derive(PartialEq)]
2154 fn automatic_retries() {
2155 do_automatic_retries(AutoRetry::Success);
2156 do_automatic_retries(AutoRetry::Spontaneous);
2157 do_automatic_retries(AutoRetry::FailAttempts);
2158 do_automatic_retries(AutoRetry::FailTimeout);
2159 do_automatic_retries(AutoRetry::FailOnRestart);
2160 do_automatic_retries(AutoRetry::FailOnRetry);
2162 fn do_automatic_retries(test: AutoRetry) {
2163 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
2165 let chanmon_cfgs = create_chanmon_cfgs(3);
2166 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2168 let new_chain_monitor;
2170 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2171 let node_0_deserialized;
2173 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2174 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2175 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2177 // Marshall data to send the payment
2178 #[cfg(feature = "std")]
2179 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2180 #[cfg(not(feature = "std"))]
2181 let payment_expiry_secs = 60 * 60;
2182 let amt_msat = 1000;
2183 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2184 invoice_features.set_variable_length_onion_required();
2185 invoice_features.set_payment_secret_required();
2186 invoice_features.set_basic_mpp_optional();
2187 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2188 .with_expiry_time(payment_expiry_secs as u64)
2189 .with_bolt11_features(invoice_features).unwrap();
2190 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2191 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
2193 macro_rules! pass_failed_attempt_with_retry_along_path {
2194 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
2195 // Send a payment attempt that fails due to lack of liquidity on the second hop
2196 check_added_monitors!(nodes[0], 1);
2197 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2198 let mut update_add = update_0.update_add_htlcs[0].clone();
2199 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
2200 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
2201 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2202 nodes[1].node.process_pending_htlc_forwards();
2203 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
2204 vec![HTLCDestination::NextHopChannel {
2205 node_id: Some(nodes[2].node.get_our_node_id()),
2206 channel_id: $failing_channel_id,
2208 nodes[1].node.process_pending_htlc_forwards();
2209 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2210 check_added_monitors!(&nodes[1], 1);
2211 assert!(update_1.update_fail_htlcs.len() == 1);
2212 let fail_msg = update_1.update_fail_htlcs[0].clone();
2213 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
2214 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
2216 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
2217 let mut events = nodes[0].node.get_and_clear_pending_events();
2218 assert_eq!(events.len(), 2);
2220 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2221 assert_eq!(payment_hash, ev_payment_hash);
2222 assert_eq!(payment_failed_permanently, false);
2224 _ => panic!("Unexpected event"),
2226 if $expect_pending_htlcs_forwardable {
2228 Event::PendingHTLCsForwardable { .. } => {},
2229 _ => panic!("Unexpected event"),
2233 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
2234 assert_eq!(payment_hash, ev_payment_hash);
2236 _ => panic!("Unexpected event"),
2242 if test == AutoRetry::Success {
2243 // Test that we can succeed on the first retry.
2244 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2245 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2246 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2248 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2249 // attempt, since the initial second hop channel will be excluded from pathfinding
2250 create_announced_chan_between_nodes(&nodes, 1, 2);
2252 // We retry payments in `process_pending_htlc_forwards`
2253 nodes[0].node.process_pending_htlc_forwards();
2254 check_added_monitors!(nodes[0], 1);
2255 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2256 assert_eq!(msg_events.len(), 1);
2257 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
2258 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2259 } else if test == AutoRetry::Spontaneous {
2260 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
2261 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
2262 Retry::Attempts(1)).unwrap();
2263 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2265 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2266 // attempt, since the initial second hop channel will be excluded from pathfinding
2267 create_announced_chan_between_nodes(&nodes, 1, 2);
2269 // We retry payments in `process_pending_htlc_forwards`
2270 nodes[0].node.process_pending_htlc_forwards();
2271 check_added_monitors!(nodes[0], 1);
2272 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2273 assert_eq!(msg_events.len(), 1);
2274 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2275 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2276 } else if test == AutoRetry::FailAttempts {
2277 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2278 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2279 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2280 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2282 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2283 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2284 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2286 // We retry payments in `process_pending_htlc_forwards`
2287 nodes[0].node.process_pending_htlc_forwards();
2288 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2290 // Ensure we won't retry a second time.
2291 nodes[0].node.process_pending_htlc_forwards();
2292 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2293 assert_eq!(msg_events.len(), 0);
2294 } else if test == AutoRetry::FailTimeout {
2295 #[cfg(not(feature = "no-std"))] {
2296 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2297 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2298 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2299 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2301 // Advance the time so the second attempt fails due to timeout.
2302 SinceEpoch::advance(Duration::from_secs(61));
2304 // Make sure we don't retry again.
2305 nodes[0].node.process_pending_htlc_forwards();
2306 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2307 assert_eq!(msg_events.len(), 0);
2309 let mut events = nodes[0].node.get_and_clear_pending_events();
2310 assert_eq!(events.len(), 1);
2312 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2313 assert_eq!(payment_hash, *ev_payment_hash);
2314 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2315 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2317 _ => panic!("Unexpected event"),
2320 } else if test == AutoRetry::FailOnRestart {
2321 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2322 // attempts remaining prior to restart.
2323 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2324 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2325 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2327 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2328 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2329 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2331 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2332 nodes[0].node.process_pending_htlc_forwards();
2333 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2335 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2336 let node_encoded = nodes[0].node.encode();
2337 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2338 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2340 let mut events = nodes[0].node.get_and_clear_pending_events();
2341 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2342 // Make sure we don't retry again.
2343 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2344 assert_eq!(msg_events.len(), 0);
2346 let mut events = nodes[0].node.get_and_clear_pending_events();
2347 assert_eq!(events.len(), 1);
2349 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2350 assert_eq!(payment_hash, *ev_payment_hash);
2351 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2352 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2354 _ => panic!("Unexpected event"),
2356 } else if test == AutoRetry::FailOnRetry {
2357 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2358 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2359 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2361 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2362 // fail to find a route.
2363 nodes[0].node.process_pending_htlc_forwards();
2364 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2365 assert_eq!(msg_events.len(), 0);
2367 let mut events = nodes[0].node.get_and_clear_pending_events();
2368 assert_eq!(events.len(), 1);
2370 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2371 assert_eq!(payment_hash, *ev_payment_hash);
2372 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2373 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2375 _ => panic!("Unexpected event"),
2381 fn auto_retry_partial_failure() {
2382 // Test that we'll retry appropriately on send partial failure and retry partial failure.
2383 let chanmon_cfgs = create_chanmon_cfgs(2);
2384 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2385 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2386 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2388 // Open three channels, the first has plenty of liquidity, the second and third have ~no
2389 // available liquidity, causing any outbound payments routed over it to fail immediately.
2390 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2391 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;
2392 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;
2394 // Marshall data to send the payment
2395 let amt_msat = 10_000_000;
2396 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2397 #[cfg(feature = "std")]
2398 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2399 #[cfg(not(feature = "std"))]
2400 let payment_expiry_secs = 60 * 60;
2401 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2402 invoice_features.set_variable_length_onion_required();
2403 invoice_features.set_payment_secret_required();
2404 invoice_features.set_basic_mpp_optional();
2405 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2406 .with_expiry_time(payment_expiry_secs as u64)
2407 .with_bolt11_features(invoice_features).unwrap();
2409 // Configure the initial send path
2410 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2411 route_params.max_total_routing_fee_msat = None;
2413 let send_route = Route {
2415 Path { hops: vec![RouteHop {
2416 pubkey: nodes[1].node.get_our_node_id(),
2417 node_features: nodes[1].node.node_features(),
2418 short_channel_id: chan_1_id,
2419 channel_features: nodes[1].node.channel_features(),
2420 fee_msat: amt_msat / 2,
2421 cltv_expiry_delta: 100,
2422 maybe_announced_channel: true,
2423 }], blinded_tail: None },
2424 Path { hops: vec![RouteHop {
2425 pubkey: nodes[1].node.get_our_node_id(),
2426 node_features: nodes[1].node.node_features(),
2427 short_channel_id: chan_2_id,
2428 channel_features: nodes[1].node.channel_features(),
2429 fee_msat: amt_msat / 2,
2430 cltv_expiry_delta: 100,
2431 maybe_announced_channel: true,
2432 }], blinded_tail: None },
2434 route_params: Some(route_params.clone()),
2436 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2438 // Configure the retry1 paths
2439 let mut payment_params = route_params.payment_params.clone();
2440 payment_params.previously_failed_channels.push(chan_2_id);
2441 let mut retry_1_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 2);
2442 retry_1_params.max_total_routing_fee_msat = None;
2444 let retry_1_route = Route {
2446 Path { hops: vec![RouteHop {
2447 pubkey: nodes[1].node.get_our_node_id(),
2448 node_features: nodes[1].node.node_features(),
2449 short_channel_id: chan_1_id,
2450 channel_features: nodes[1].node.channel_features(),
2451 fee_msat: amt_msat / 4,
2452 cltv_expiry_delta: 100,
2453 maybe_announced_channel: true,
2454 }], blinded_tail: None },
2455 Path { hops: vec![RouteHop {
2456 pubkey: nodes[1].node.get_our_node_id(),
2457 node_features: nodes[1].node.node_features(),
2458 short_channel_id: chan_3_id,
2459 channel_features: nodes[1].node.channel_features(),
2460 fee_msat: amt_msat / 4,
2461 cltv_expiry_delta: 100,
2462 maybe_announced_channel: true,
2463 }], blinded_tail: None },
2465 route_params: Some(retry_1_params.clone()),
2467 nodes[0].router.expect_find_route(retry_1_params.clone(), Ok(retry_1_route));
2469 // Configure the retry2 path
2470 let mut payment_params = retry_1_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;
2475 let retry_2_route = Route {
2477 Path { hops: vec![RouteHop {
2478 pubkey: nodes[1].node.get_our_node_id(),
2479 node_features: nodes[1].node.node_features(),
2480 short_channel_id: chan_1_id,
2481 channel_features: nodes[1].node.channel_features(),
2482 fee_msat: amt_msat / 4,
2483 cltv_expiry_delta: 100,
2484 maybe_announced_channel: true,
2485 }], blinded_tail: None },
2487 route_params: Some(retry_2_params.clone()),
2489 nodes[0].router.expect_find_route(retry_2_params, Ok(retry_2_route));
2491 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2492 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2493 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2494 let payment_failed_events = nodes[0].node.get_and_clear_pending_events();
2495 assert_eq!(payment_failed_events.len(), 2);
2496 match payment_failed_events[0] {
2497 Event::PaymentPathFailed { .. } => {},
2498 _ => panic!("Unexpected event"),
2500 match payment_failed_events[1] {
2501 Event::PaymentPathFailed { .. } => {},
2502 _ => panic!("Unexpected event"),
2505 // Pass the first part of the payment along the path.
2506 check_added_monitors!(nodes[0], 1); // only one HTLC actually made it out
2507 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2509 // Only one HTLC/channel update actually made it out
2510 assert_eq!(msg_events.len(), 1);
2511 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2513 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2514 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2515 check_added_monitors!(nodes[1], 1);
2516 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2518 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2519 check_added_monitors!(nodes[0], 1);
2520 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2522 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2523 check_added_monitors!(nodes[0], 1);
2524 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2526 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2527 check_added_monitors!(nodes[1], 1);
2529 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2530 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2531 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2532 check_added_monitors!(nodes[1], 1);
2533 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2535 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2536 check_added_monitors!(nodes[0], 1);
2538 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2539 check_added_monitors!(nodes[0], 1);
2540 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2542 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2543 check_added_monitors!(nodes[1], 1);
2545 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2546 nodes[1].node.process_pending_htlc_forwards();
2547 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2548 nodes[1].node.claim_funds(payment_preimage);
2549 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2550 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2551 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2553 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2554 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
2555 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2556 check_added_monitors!(nodes[0], 1);
2557 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2559 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2560 check_added_monitors!(nodes[1], 4);
2561 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2563 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2564 check_added_monitors!(nodes[1], 1);
2565 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2567 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2568 check_added_monitors!(nodes[0], 1);
2569 expect_payment_path_successful!(nodes[0]);
2571 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2572 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2573 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2574 check_added_monitors!(nodes[0], 1);
2575 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2577 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2578 check_added_monitors!(nodes[1], 1);
2580 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2581 check_added_monitors!(nodes[1], 1);
2582 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2584 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2585 check_added_monitors!(nodes[0], 1);
2586 let events = nodes[0].node.get_and_clear_pending_events();
2587 assert_eq!(events.len(), 2);
2588 if let Event::PaymentPathSuccessful { .. } = events[0] {} else { panic!(); }
2589 if let Event::PaymentPathSuccessful { .. } = events[1] {} else { panic!(); }
2593 fn auto_retry_zero_attempts_send_error() {
2594 let chanmon_cfgs = create_chanmon_cfgs(2);
2595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2599 // Open a single channel that does not have sufficient liquidity for the payment we want to
2601 let chan_id = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 989_000_000).0.contents.short_channel_id;
2603 // Marshall data to send the payment
2604 let amt_msat = 10_000_000;
2605 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(amt_msat), None);
2606 #[cfg(feature = "std")]
2607 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2608 #[cfg(not(feature = "std"))]
2609 let payment_expiry_secs = 60 * 60;
2610 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2611 invoice_features.set_variable_length_onion_required();
2612 invoice_features.set_payment_secret_required();
2613 invoice_features.set_basic_mpp_optional();
2614 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2615 .with_expiry_time(payment_expiry_secs as u64)
2616 .with_bolt11_features(invoice_features).unwrap();
2617 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2619 // Override the route search to return a route, rather than failing at the route-finding step.
2620 let send_route = Route {
2622 Path { hops: vec![RouteHop {
2623 pubkey: nodes[1].node.get_our_node_id(),
2624 node_features: nodes[1].node.node_features(),
2625 short_channel_id: chan_id,
2626 channel_features: nodes[1].node.channel_features(),
2628 cltv_expiry_delta: 100,
2629 maybe_announced_channel: true,
2630 }], blinded_tail: None },
2632 route_params: Some(route_params.clone()),
2634 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2636 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2637 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2638 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2639 let events = nodes[0].node.get_and_clear_pending_events();
2640 assert_eq!(events.len(), 2);
2641 if let Event::PaymentPathFailed { .. } = events[0] { } else { panic!(); }
2642 if let Event::PaymentFailed { .. } = events[1] { } else { panic!(); }
2643 check_added_monitors!(nodes[0], 0);
2647 fn fails_paying_after_rejected_by_payee() {
2648 let chanmon_cfgs = create_chanmon_cfgs(2);
2649 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2650 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2651 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2653 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2655 // Marshall data to send the payment
2656 let amt_msat = 20_000;
2657 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2658 #[cfg(feature = "std")]
2659 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2660 #[cfg(not(feature = "std"))]
2661 let payment_expiry_secs = 60 * 60;
2662 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2663 invoice_features.set_variable_length_onion_required();
2664 invoice_features.set_payment_secret_required();
2665 invoice_features.set_basic_mpp_optional();
2666 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2667 .with_expiry_time(payment_expiry_secs as u64)
2668 .with_bolt11_features(invoice_features).unwrap();
2669 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2671 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2672 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2673 check_added_monitors!(nodes[0], 1);
2674 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2675 assert_eq!(events.len(), 1);
2676 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2677 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2678 check_added_monitors!(nodes[1], 0);
2679 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2680 expect_pending_htlcs_forwardable!(nodes[1]);
2681 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2683 nodes[1].node.fail_htlc_backwards(&payment_hash);
2684 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2685 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2689 fn retry_multi_path_single_failed_payment() {
2690 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2691 let chanmon_cfgs = create_chanmon_cfgs(2);
2692 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2693 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2694 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2696 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2697 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2699 let amt_msat = 100_010_000;
2701 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2702 #[cfg(feature = "std")]
2703 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2704 #[cfg(not(feature = "std"))]
2705 let payment_expiry_secs = 60 * 60;
2706 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2707 invoice_features.set_variable_length_onion_required();
2708 invoice_features.set_payment_secret_required();
2709 invoice_features.set_basic_mpp_optional();
2710 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2711 .with_expiry_time(payment_expiry_secs as u64)
2712 .with_bolt11_features(invoice_features).unwrap();
2713 let mut route_params = RouteParameters::from_payment_params_and_value(
2714 payment_params.clone(), amt_msat);
2715 route_params.max_total_routing_fee_msat = None;
2717 let chans = nodes[0].node.list_usable_channels();
2718 let mut route = Route {
2720 Path { hops: vec![RouteHop {
2721 pubkey: nodes[1].node.get_our_node_id(),
2722 node_features: nodes[1].node.node_features(),
2723 short_channel_id: chans[0].short_channel_id.unwrap(),
2724 channel_features: nodes[1].node.channel_features(),
2726 cltv_expiry_delta: 100,
2727 maybe_announced_channel: true,
2728 }], blinded_tail: None },
2729 Path { hops: vec![RouteHop {
2730 pubkey: nodes[1].node.get_our_node_id(),
2731 node_features: nodes[1].node.node_features(),
2732 short_channel_id: chans[1].short_channel_id.unwrap(),
2733 channel_features: nodes[1].node.channel_features(),
2734 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2735 cltv_expiry_delta: 100,
2736 maybe_announced_channel: true,
2737 }], blinded_tail: None },
2739 route_params: Some(route_params.clone()),
2741 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2742 // On retry, split the payment across both channels.
2743 route.paths[0].hops[0].fee_msat = 50_000_001;
2744 route.paths[1].hops[0].fee_msat = 50_000_000;
2745 let mut pay_params = route.route_params.clone().unwrap().payment_params;
2746 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2748 let mut retry_params = RouteParameters::from_payment_params_and_value(pay_params, 100_000_000);
2749 retry_params.max_total_routing_fee_msat = None;
2750 route.route_params.as_mut().unwrap().final_value_msat = 100_000_000;
2751 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2754 let scorer = chanmon_cfgs[0].scorer.read().unwrap();
2755 // The initial send attempt, 2 paths
2756 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2757 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2758 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2759 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2760 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2763 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2764 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2765 let events = nodes[0].node.get_and_clear_pending_events();
2766 assert_eq!(events.len(), 1);
2768 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2769 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2770 short_channel_id: Some(expected_scid), .. } =>
2772 assert_eq!(payment_hash, ev_payment_hash);
2773 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2775 _ => panic!("Unexpected event"),
2777 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2778 assert_eq!(htlc_msgs.len(), 2);
2779 check_added_monitors!(nodes[0], 2);
2783 fn immediate_retry_on_failure() {
2784 // Tests that we can/will retry immediately after a failure
2785 let chanmon_cfgs = create_chanmon_cfgs(2);
2786 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2787 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2788 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2790 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2791 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2793 let amt_msat = 100_000_001;
2794 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2795 #[cfg(feature = "std")]
2796 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2797 #[cfg(not(feature = "std"))]
2798 let payment_expiry_secs = 60 * 60;
2799 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2800 invoice_features.set_variable_length_onion_required();
2801 invoice_features.set_payment_secret_required();
2802 invoice_features.set_basic_mpp_optional();
2803 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2804 .with_expiry_time(payment_expiry_secs as u64)
2805 .with_bolt11_features(invoice_features).unwrap();
2806 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2808 let chans = nodes[0].node.list_usable_channels();
2809 let mut route = Route {
2811 Path { hops: vec![RouteHop {
2812 pubkey: nodes[1].node.get_our_node_id(),
2813 node_features: nodes[1].node.node_features(),
2814 short_channel_id: chans[0].short_channel_id.unwrap(),
2815 channel_features: nodes[1].node.channel_features(),
2816 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2817 cltv_expiry_delta: 100,
2818 maybe_announced_channel: true,
2819 }], blinded_tail: None },
2821 route_params: Some(RouteParameters::from_payment_params_and_value(
2822 PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV),
2825 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2826 // On retry, split the payment across both channels.
2827 route.paths.push(route.paths[0].clone());
2828 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2829 route.paths[0].hops[0].fee_msat = 50_000_000;
2830 route.paths[1].hops[0].fee_msat = 50_000_001;
2831 let mut pay_params = route_params.payment_params.clone();
2832 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2833 nodes[0].router.expect_find_route(
2834 RouteParameters::from_payment_params_and_value(pay_params, amt_msat),
2837 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2838 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2839 let events = nodes[0].node.get_and_clear_pending_events();
2840 assert_eq!(events.len(), 1);
2842 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2843 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2844 short_channel_id: Some(expected_scid), .. } =>
2846 assert_eq!(payment_hash, ev_payment_hash);
2847 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2849 _ => panic!("Unexpected event"),
2851 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2852 assert_eq!(htlc_msgs.len(), 2);
2853 check_added_monitors!(nodes[0], 2);
2857 fn no_extra_retries_on_back_to_back_fail() {
2858 // In a previous release, we had a race where we may exceed the payment retry count if we
2859 // get two failures in a row with the second indicating that all paths had failed (this field,
2860 // `all_paths_failed`, has since been removed).
2861 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2862 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2863 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2864 // pending which we will see later. Thus, when we previously removed the retry tracking map
2865 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2866 // retry entry even though more events for the same payment were still pending. This led to
2867 // us retrying a payment again even though we'd already given up on it.
2869 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2870 // is used to remove the payment retry counter entries instead. This tests for the specific
2871 // excess-retry case while also testing `PaymentFailed` generation.
2873 let chanmon_cfgs = create_chanmon_cfgs(3);
2874 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2875 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2876 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2878 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2879 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2881 let amt_msat = 200_000_000;
2882 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2883 #[cfg(feature = "std")]
2884 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2885 #[cfg(not(feature = "std"))]
2886 let payment_expiry_secs = 60 * 60;
2887 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2888 invoice_features.set_variable_length_onion_required();
2889 invoice_features.set_payment_secret_required();
2890 invoice_features.set_basic_mpp_optional();
2891 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2892 .with_expiry_time(payment_expiry_secs as u64)
2893 .with_bolt11_features(invoice_features).unwrap();
2894 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2895 route_params.max_total_routing_fee_msat = None;
2897 let mut route = Route {
2899 Path { hops: vec![RouteHop {
2900 pubkey: nodes[1].node.get_our_node_id(),
2901 node_features: nodes[1].node.node_features(),
2902 short_channel_id: chan_1_scid,
2903 channel_features: nodes[1].node.channel_features(),
2904 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2905 cltv_expiry_delta: 100,
2906 maybe_announced_channel: true,
2908 pubkey: nodes[2].node.get_our_node_id(),
2909 node_features: nodes[2].node.node_features(),
2910 short_channel_id: chan_2_scid,
2911 channel_features: nodes[2].node.channel_features(),
2912 fee_msat: 100_000_000,
2913 cltv_expiry_delta: 100,
2914 maybe_announced_channel: true,
2915 }], blinded_tail: None },
2916 Path { hops: vec![RouteHop {
2917 pubkey: nodes[1].node.get_our_node_id(),
2918 node_features: nodes[1].node.node_features(),
2919 short_channel_id: chan_1_scid,
2920 channel_features: nodes[1].node.channel_features(),
2921 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2922 cltv_expiry_delta: 100,
2923 maybe_announced_channel: true,
2925 pubkey: nodes[2].node.get_our_node_id(),
2926 node_features: nodes[2].node.node_features(),
2927 short_channel_id: chan_2_scid,
2928 channel_features: nodes[2].node.channel_features(),
2929 fee_msat: 100_000_000,
2930 cltv_expiry_delta: 100,
2931 maybe_announced_channel: true,
2932 }], blinded_tail: None }
2934 route_params: Some(route_params.clone()),
2936 route.route_params.as_mut().unwrap().max_total_routing_fee_msat = None;
2937 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2938 let mut second_payment_params = route_params.payment_params.clone();
2939 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2940 // On retry, we'll only return one path
2941 route.paths.remove(1);
2942 route.paths[0].hops[1].fee_msat = amt_msat;
2943 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat);
2944 retry_params.max_total_routing_fee_msat = None;
2945 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2947 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2948 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2949 let htlc_updates = SendEvent::from_node(&nodes[0]);
2950 check_added_monitors!(nodes[0], 1);
2951 assert_eq!(htlc_updates.msgs.len(), 1);
2953 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2954 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2955 check_added_monitors!(nodes[1], 1);
2956 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2958 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2959 check_added_monitors!(nodes[0], 1);
2960 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2962 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2963 check_added_monitors!(nodes[0], 1);
2964 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2966 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2967 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2968 check_added_monitors!(nodes[1], 1);
2969 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2971 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2972 check_added_monitors!(nodes[1], 1);
2973 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2975 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2976 check_added_monitors!(nodes[0], 1);
2978 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2979 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2980 check_added_monitors!(nodes[0], 1);
2981 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2983 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2984 check_added_monitors!(nodes[1], 1);
2985 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2987 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2988 check_added_monitors!(nodes[1], 1);
2989 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2991 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2992 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2993 check_added_monitors!(nodes[0], 1);
2995 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2996 check_added_monitors!(nodes[0], 1);
2997 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2999 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
3000 check_added_monitors!(nodes[1], 1);
3001 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
3002 check_added_monitors!(nodes[1], 1);
3003 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3005 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
3006 check_added_monitors!(nodes[0], 1);
3008 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
3009 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
3012 // Previously, we retried payments in an event consumer, which would retry each
3013 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
3014 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
3015 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
3016 // by adding the `PaymentFailed` event.
3018 // Because we now retry payments as a batch, we simply return a single-path route in the
3019 // second, batched, request, have that fail, ensure the payment was abandoned.
3020 let mut events = nodes[0].node.get_and_clear_pending_events();
3021 assert_eq!(events.len(), 3);
3023 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3024 assert_eq!(payment_hash, ev_payment_hash);
3025 assert_eq!(payment_failed_permanently, false);
3027 _ => panic!("Unexpected event"),
3030 Event::PendingHTLCsForwardable { .. } => {},
3031 _ => panic!("Unexpected event"),
3034 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3035 assert_eq!(payment_hash, ev_payment_hash);
3036 assert_eq!(payment_failed_permanently, false);
3038 _ => panic!("Unexpected event"),
3041 nodes[0].node.process_pending_htlc_forwards();
3042 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3043 check_added_monitors!(nodes[0], 1);
3045 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3046 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3047 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3048 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3049 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
3051 let mut events = nodes[0].node.get_and_clear_pending_events();
3052 assert_eq!(events.len(), 2);
3054 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3055 assert_eq!(payment_hash, ev_payment_hash);
3056 assert_eq!(payment_failed_permanently, false);
3058 _ => panic!("Unexpected event"),
3061 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
3062 assert_eq!(payment_hash, *ev_payment_hash);
3063 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
3064 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
3066 _ => panic!("Unexpected event"),
3071 fn test_simple_partial_retry() {
3072 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
3073 // full amount of the payment, rather than only the missing amount. Here we simply test for
3074 // this by sending a payment with two parts, failing one, and retrying the second. Note that
3075 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
3077 let chanmon_cfgs = create_chanmon_cfgs(3);
3078 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3079 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3080 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3082 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3083 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
3085 let amt_msat = 200_000_000;
3086 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3087 #[cfg(feature = "std")]
3088 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3089 #[cfg(not(feature = "std"))]
3090 let payment_expiry_secs = 60 * 60;
3091 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3092 invoice_features.set_variable_length_onion_required();
3093 invoice_features.set_payment_secret_required();
3094 invoice_features.set_basic_mpp_optional();
3095 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3096 .with_expiry_time(payment_expiry_secs as u64)
3097 .with_bolt11_features(invoice_features).unwrap();
3098 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
3099 route_params.max_total_routing_fee_msat = None;
3101 let mut route = Route {
3103 Path { hops: vec![RouteHop {
3104 pubkey: nodes[1].node.get_our_node_id(),
3105 node_features: nodes[1].node.node_features(),
3106 short_channel_id: chan_1_scid,
3107 channel_features: nodes[1].node.channel_features(),
3108 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
3109 cltv_expiry_delta: 100,
3110 maybe_announced_channel: true,
3112 pubkey: nodes[2].node.get_our_node_id(),
3113 node_features: nodes[2].node.node_features(),
3114 short_channel_id: chan_2_scid,
3115 channel_features: nodes[2].node.channel_features(),
3116 fee_msat: 100_000_000,
3117 cltv_expiry_delta: 100,
3118 maybe_announced_channel: true,
3119 }], blinded_tail: None },
3120 Path { hops: vec![RouteHop {
3121 pubkey: nodes[1].node.get_our_node_id(),
3122 node_features: nodes[1].node.node_features(),
3123 short_channel_id: chan_1_scid,
3124 channel_features: nodes[1].node.channel_features(),
3126 cltv_expiry_delta: 100,
3127 maybe_announced_channel: true,
3129 pubkey: nodes[2].node.get_our_node_id(),
3130 node_features: nodes[2].node.node_features(),
3131 short_channel_id: chan_2_scid,
3132 channel_features: nodes[2].node.channel_features(),
3133 fee_msat: 100_000_000,
3134 cltv_expiry_delta: 100,
3135 maybe_announced_channel: true,
3136 }], blinded_tail: None }
3138 route_params: Some(route_params.clone()),
3141 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3143 let mut second_payment_params = route_params.payment_params.clone();
3144 second_payment_params.previously_failed_channels = vec![chan_2_scid];
3145 // On retry, we'll only be asked for one path (or 100k sats)
3146 route.paths.remove(0);
3147 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat / 2);
3148 retry_params.max_total_routing_fee_msat = None;
3149 route.route_params.as_mut().unwrap().final_value_msat = amt_msat / 2;
3150 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
3152 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3153 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
3154 let htlc_updates = SendEvent::from_node(&nodes[0]);
3155 check_added_monitors!(nodes[0], 1);
3156 assert_eq!(htlc_updates.msgs.len(), 1);
3158 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
3159 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
3160 check_added_monitors!(nodes[1], 1);
3161 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3163 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
3164 check_added_monitors!(nodes[0], 1);
3165 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
3167 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
3168 check_added_monitors!(nodes[0], 1);
3169 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3171 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
3172 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
3173 check_added_monitors!(nodes[1], 1);
3174 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3176 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
3177 check_added_monitors!(nodes[1], 1);
3178 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3180 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
3181 check_added_monitors!(nodes[0], 1);
3183 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3184 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
3185 check_added_monitors!(nodes[0], 1);
3186 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3188 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
3189 check_added_monitors!(nodes[1], 1);
3191 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
3192 check_added_monitors!(nodes[1], 1);
3194 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3196 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
3197 check_added_monitors!(nodes[0], 1);
3199 let mut events = nodes[0].node.get_and_clear_pending_events();
3200 assert_eq!(events.len(), 2);
3202 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3203 assert_eq!(payment_hash, ev_payment_hash);
3204 assert_eq!(payment_failed_permanently, false);
3206 _ => panic!("Unexpected event"),
3209 Event::PendingHTLCsForwardable { .. } => {},
3210 _ => panic!("Unexpected event"),
3213 nodes[0].node.process_pending_htlc_forwards();
3214 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3215 check_added_monitors!(nodes[0], 1);
3217 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3218 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3220 expect_pending_htlcs_forwardable!(nodes[1]);
3221 check_added_monitors!(nodes[1], 1);
3223 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3224 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
3225 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
3226 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
3228 expect_pending_htlcs_forwardable!(nodes[2]);
3229 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
3233 #[cfg(feature = "std")]
3234 fn test_threaded_payment_retries() {
3235 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
3236 // a single thread and would happily let multiple threads run retries at the same time. Because
3237 // retries are done by first calculating the amount we need to retry, then dropping the
3238 // relevant lock, then actually sending, we would happily let multiple threads retry the same
3239 // amount at the same time, overpaying our original HTLC!
3240 let chanmon_cfgs = create_chanmon_cfgs(4);
3241 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3242 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3243 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3245 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
3246 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
3247 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
3248 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
3250 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3251 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
3252 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
3253 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
3255 let amt_msat = 100_000_000;
3256 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3257 #[cfg(feature = "std")]
3258 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3259 #[cfg(not(feature = "std"))]
3260 let payment_expiry_secs = 60 * 60;
3261 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3262 invoice_features.set_variable_length_onion_required();
3263 invoice_features.set_payment_secret_required();
3264 invoice_features.set_basic_mpp_optional();
3265 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3266 .with_expiry_time(payment_expiry_secs as u64)
3267 .with_bolt11_features(invoice_features).unwrap();
3268 let mut route_params = RouteParameters {
3269 payment_params, final_value_msat: amt_msat, max_total_routing_fee_msat: Some(500_000),
3272 let mut route = Route {
3274 Path { hops: vec![RouteHop {
3275 pubkey: nodes[1].node.get_our_node_id(),
3276 node_features: nodes[1].node.node_features(),
3277 short_channel_id: chan_1_scid,
3278 channel_features: nodes[1].node.channel_features(),
3280 cltv_expiry_delta: 100,
3281 maybe_announced_channel: true,
3283 pubkey: nodes[3].node.get_our_node_id(),
3284 node_features: nodes[2].node.node_features(),
3285 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3286 channel_features: nodes[2].node.channel_features(),
3287 fee_msat: amt_msat / 1000,
3288 cltv_expiry_delta: 100,
3289 maybe_announced_channel: true,
3290 }], blinded_tail: None },
3291 Path { hops: vec![RouteHop {
3292 pubkey: nodes[2].node.get_our_node_id(),
3293 node_features: nodes[2].node.node_features(),
3294 short_channel_id: chan_3_scid,
3295 channel_features: nodes[2].node.channel_features(),
3297 cltv_expiry_delta: 100,
3298 maybe_announced_channel: true,
3300 pubkey: nodes[3].node.get_our_node_id(),
3301 node_features: nodes[3].node.node_features(),
3302 short_channel_id: chan_4_scid,
3303 channel_features: nodes[3].node.channel_features(),
3304 fee_msat: amt_msat - amt_msat / 1000,
3305 cltv_expiry_delta: 100,
3306 maybe_announced_channel: true,
3307 }], blinded_tail: None }
3309 route_params: Some(route_params.clone()),
3311 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3313 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3314 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3315 check_added_monitors!(nodes[0], 2);
3316 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3317 assert_eq!(send_msg_events.len(), 2);
3318 send_msg_events.retain(|msg|
3319 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3320 // Drop the commitment update for nodes[2], we can just let that one sit pending
3322 *node_id == nodes[1].node.get_our_node_id()
3323 } else { panic!(); }
3326 // from here on out, the retry `RouteParameters` amount will be amt/1000
3327 route_params.final_value_msat /= 1000;
3328 route.route_params.as_mut().unwrap().final_value_msat /= 1000;
3331 let end_time = Instant::now() + Duration::from_secs(1);
3332 macro_rules! thread_body { () => { {
3333 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3334 let node_ref = NodePtr::from_node(&nodes[0]);
3336 let node_a = unsafe { &*node_ref.0 };
3337 while Instant::now() < end_time {
3338 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3339 // Ignore if we have any pending events, just always pretend we just got a
3340 // PendingHTLCsForwardable
3341 node_a.node.process_pending_htlc_forwards();
3345 let mut threads = Vec::new();
3346 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3348 // Back in the main thread, poll pending messages and make sure that we never have more than
3349 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3350 // there are HTLC messages shoved in while its running. This allows us to test that we never
3351 // generate an additional update_add_htlc until we've fully failed the first.
3352 let mut previously_failed_channels = Vec::new();
3354 assert_eq!(send_msg_events.len(), 1);
3355 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3356 assert_eq!(send_event.msgs.len(), 1);
3358 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3359 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3361 // Note that we only push one route into `expect_find_route` at a time, because that's all
3362 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3363 // we should still ultimately fail for the same reason - because we're trying to send too
3364 // many HTLCs at once.
3365 let mut new_route_params = route_params.clone();
3366 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3367 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3368 new_route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 100_000);
3369 route.paths[0].hops[1].short_channel_id += 1;
3370 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3372 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3373 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3374 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3375 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3376 // This races with our other threads which may generate an add-HTLCs commitment update via
3377 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3378 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3379 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3380 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3382 let cur_time = Instant::now();
3383 if cur_time > end_time {
3384 for thread in threads.drain(..) { thread.join().unwrap(); }
3387 // Make sure we have some events to handle when we go around...
3388 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3389 nodes[0].node.process_pending_htlc_forwards();
3390 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3391 check_added_monitors!(nodes[0], 2);
3393 if cur_time > end_time {
3399 fn do_no_missing_sent_on_reload(persist_manager_with_payment: bool, at_midpoint: bool) {
3400 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3401 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3402 // it was last persisted.
3403 let chanmon_cfgs = create_chanmon_cfgs(2);
3404 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3405 let (persister_a, persister_b, persister_c);
3406 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3407 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3408 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3409 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3411 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3413 let mut nodes_0_serialized = Vec::new();
3414 if !persist_manager_with_payment {
3415 nodes_0_serialized = nodes[0].node.encode();
3418 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3420 if persist_manager_with_payment {
3421 nodes_0_serialized = nodes[0].node.encode();
3424 nodes[1].node.claim_funds(our_payment_preimage);
3425 check_added_monitors!(nodes[1], 1);
3426 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3429 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3430 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3431 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3432 check_added_monitors!(nodes[0], 1);
3434 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3435 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
3436 commitment_signed_dance!(nodes[0], nodes[1], htlc_fulfill_updates.commitment_signed, false);
3437 // Ignore the PaymentSent event which is now pending on nodes[0] - if we were to handle it we'd
3438 // be expected to ignore the eventual conflicting PaymentFailed, but by not looking at it we
3439 // expect to get the PaymentSent again later.
3440 check_added_monitors(&nodes[0], 0);
3443 // The ChannelMonitor should always be the latest version, as we're required to persist it
3444 // during the commitment signed handling.
3445 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3446 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3448 let events = nodes[0].node.get_and_clear_pending_events();
3449 assert_eq!(events.len(), 2);
3450 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3451 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3452 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3453 // the double-claim that would otherwise appear at the end of this test.
3454 nodes[0].node.timer_tick_occurred();
3455 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3456 assert_eq!(as_broadcasted_txn.len(), 1);
3458 // Ensure that, even after some time, if we restart we still include *something* in the current
3459 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3460 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3461 // A naive implementation of the fix here would wipe the pending payments set, causing a
3462 // failure event when we restart.
3463 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3465 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3466 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);
3467 let events = nodes[0].node.get_and_clear_pending_events();
3468 assert!(events.is_empty());
3470 // Ensure that we don't generate any further events even after the channel-closing commitment
3471 // transaction is confirmed on-chain.
3472 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3473 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3475 let events = nodes[0].node.get_and_clear_pending_events();
3476 assert!(events.is_empty());
3478 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3479 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);
3480 let events = nodes[0].node.get_and_clear_pending_events();
3481 assert!(events.is_empty());
3482 check_added_monitors(&nodes[0], 1);
3486 fn no_missing_sent_on_midpoint_reload() {
3487 do_no_missing_sent_on_reload(false, true);
3488 do_no_missing_sent_on_reload(true, true);
3492 fn no_missing_sent_on_reload() {
3493 do_no_missing_sent_on_reload(false, false);
3494 do_no_missing_sent_on_reload(true, false);
3497 fn do_claim_from_closed_chan(fail_payment: bool) {
3498 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3499 // received had been closed between when the HTLC was received and when we went to claim it.
3500 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3501 // presumably the sender may retry later. Long ago it also reduced total code in the claim
3504 // However, this doesn't make sense if you're trying to do an atomic swap or some other
3505 // protocol that requires atomicity with some other action - if your money got claimed
3506 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3507 // is an over-optimization - there should be a very, very low likelihood that a channel closes
3508 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3509 // Since we now have code to handle this anyway we should allow it.
3511 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3512 // CLTVs on the paths to different value resulting in a different claim deadline.
3513 let chanmon_cfgs = create_chanmon_cfgs(4);
3514 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3515 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3516 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3518 create_announced_chan_between_nodes(&nodes, 0, 1);
3519 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3520 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3521 create_announced_chan_between_nodes(&nodes, 2, 3);
3523 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3524 let mut route_params = RouteParameters::from_payment_params_and_value(
3525 PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3526 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
3528 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3529 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3530 // Make sure the route is ordered as the B->D path before C->D
3531 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3532 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3534 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3535 // the HTLC is being relayed.
3536 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3537 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3538 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3540 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3541 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3542 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3543 check_added_monitors(&nodes[0], 2);
3544 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3545 send_msgs.sort_by(|a, _| {
3547 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3548 let node_b_id = nodes[1].node.get_our_node_id();
3549 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3552 assert_eq!(send_msgs.len(), 2);
3553 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3554 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3555 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3556 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3558 match receive_event.unwrap() {
3559 Event::PaymentClaimable { claim_deadline, .. } => {
3560 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3565 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3567 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3568 - if fail_payment { 0 } else { 2 });
3570 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3571 // and expire both immediately, though, by connecting another 4 blocks.
3572 let reason = HTLCDestination::FailedPayment { payment_hash };
3573 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3574 connect_blocks(&nodes[3], 4);
3575 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3576 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3578 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3579 check_closed_event!(&nodes[1], 1, ClosureReason::HolderForceClosed, false,
3580 [nodes[3].node.get_our_node_id()], 1000000);
3581 check_closed_broadcast(&nodes[1], 1, true);
3582 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3583 assert_eq!(bs_tx.len(), 1);
3585 mine_transaction(&nodes[3], &bs_tx[0]);
3586 check_added_monitors(&nodes[3], 1);
3587 check_closed_broadcast(&nodes[3], 1, true);
3588 check_closed_event!(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false,
3589 [nodes[1].node.get_our_node_id()], 1000000);
3591 nodes[3].node.claim_funds(payment_preimage);
3592 check_added_monitors(&nodes[3], 2);
3593 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3595 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3596 assert_eq!(ds_tx.len(), 1);
3597 check_spends!(&ds_tx[0], &bs_tx[0]);
3599 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3600 check_added_monitors(&nodes[1], 1);
3601 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3603 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3604 check_added_monitors(&nodes[1], 1);
3605 assert_eq!(bs_claims.len(), 1);
3606 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3607 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3608 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3609 } else { panic!(); }
3611 expect_payment_sent!(nodes[0], payment_preimage);
3613 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3614 assert_eq!(ds_claim_msgs.len(), 1);
3615 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3616 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3617 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3618 check_added_monitors(&nodes[2], 1);
3619 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3620 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3622 } else { panic!(); };
3624 assert_eq!(cs_claim_msgs.len(), 1);
3625 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3626 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3627 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3628 } else { panic!(); }
3630 expect_payment_path_successful!(nodes[0]);
3635 fn claim_from_closed_chan() {
3636 do_claim_from_closed_chan(true);
3637 do_claim_from_closed_chan(false);
3641 fn test_custom_tlvs_basic() {
3642 do_test_custom_tlvs(false, false, false);
3643 do_test_custom_tlvs(true, false, false);
3647 fn test_custom_tlvs_explicit_claim() {
3648 // Test that when receiving even custom TLVs the user must explicitly accept in case they
3650 do_test_custom_tlvs(false, true, false);
3651 do_test_custom_tlvs(false, true, true);
3654 fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) {
3655 let chanmon_cfgs = create_chanmon_cfgs(2);
3656 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3657 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None; 2]);
3658 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3660 create_announced_chan_between_nodes(&nodes, 0, 1);
3662 let amt_msat = 100_000;
3663 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat);
3664 let payment_id = PaymentId(our_payment_hash.0);
3665 let custom_tlvs = vec![
3666 (if even_tlvs { 5482373482 } else { 5482373483 }, vec![1, 2, 3, 4]),
3667 (5482373487, vec![0x42u8; 16]),
3669 let onion_fields = RecipientOnionFields {
3670 payment_secret: if spontaneous { None } else { Some(our_payment_secret) },
3671 payment_metadata: None,
3672 custom_tlvs: custom_tlvs.clone()
3675 nodes[0].node.send_spontaneous_payment(&route, Some(our_payment_preimage), onion_fields, payment_id).unwrap();
3677 nodes[0].node.send_payment_with_route(&route, our_payment_hash, onion_fields, payment_id).unwrap();
3679 check_added_monitors(&nodes[0], 1);
3681 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3682 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
3683 let mut payment_event = SendEvent::from_event(ev);
3685 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3686 check_added_monitors!(&nodes[1], 0);
3687 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3688 expect_pending_htlcs_forwardable!(nodes[1]);
3690 let events = nodes[1].node.get_and_clear_pending_events();
3691 assert_eq!(events.len(), 1);
3693 Event::PaymentClaimable { ref onion_fields, .. } => {
3694 assert_eq!(onion_fields.clone().unwrap().custom_tlvs().clone(), custom_tlvs);
3696 _ => panic!("Unexpected event"),
3699 match (known_tlvs, even_tlvs) {
3701 nodes[1].node.claim_funds_with_known_custom_tlvs(our_payment_preimage);
3702 let expected_total_fee_msat = pass_claimed_payment_along_route(&nodes[0], &[&[&nodes[1]]], &[0; 1], false, our_payment_preimage);
3703 expect_payment_sent!(&nodes[0], our_payment_preimage, Some(expected_total_fee_msat));
3706 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3709 nodes[1].node.claim_funds(our_payment_preimage);
3710 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3711 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], expected_destinations);
3712 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, our_payment_hash, PaymentFailureReason::RecipientRejected);
3718 fn test_retry_custom_tlvs() {
3719 // Test that custom TLVs are successfully sent on retries
3720 let chanmon_cfgs = create_chanmon_cfgs(3);
3721 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3722 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3723 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3725 create_announced_chan_between_nodes(&nodes, 0, 1);
3726 let (chan_2_update, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 2, 1);
3729 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3731 let amt_msat = 1_000_000;
3732 let (route, payment_hash, payment_preimage, payment_secret) =
3733 get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
3735 // Initiate the payment
3736 let payment_id = PaymentId(payment_hash.0);
3737 let mut route_params = route.route_params.clone().unwrap();
3739 let custom_tlvs = vec![((1 << 16) + 1, vec![0x42u8; 16])];
3740 let onion_fields = RecipientOnionFields::secret_only(payment_secret);
3741 let onion_fields = onion_fields.with_custom_tlvs(custom_tlvs.clone()).unwrap();
3743 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3744 nodes[0].node.send_payment(payment_hash, onion_fields,
3745 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3746 check_added_monitors!(nodes[0], 1); // one monitor per path
3748 // Add the HTLC along the first hop.
3749 let htlc_updates = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
3750 let msgs::CommitmentUpdate { update_add_htlcs, commitment_signed, .. } = htlc_updates;
3751 assert_eq!(update_add_htlcs.len(), 1);
3752 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_htlcs[0]);
3753 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
3755 // Attempt to forward the payment and complete the path's failure.
3756 expect_pending_htlcs_forwardable!(&nodes[1]);
3757 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1],
3758 vec![HTLCDestination::NextHopChannel {
3759 node_id: Some(nodes[2].node.get_our_node_id()),
3760 channel_id: chan_2_id
3762 check_added_monitors!(nodes[1], 1);
3764 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3765 let msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } = htlc_updates;
3766 assert_eq!(update_fail_htlcs.len(), 1);
3767 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3768 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
3770 let mut events = nodes[0].node.get_and_clear_pending_events();
3772 Event::PendingHTLCsForwardable { .. } => {},
3773 _ => panic!("Unexpected event")
3776 expect_payment_failed_conditions_event(events, payment_hash, false,
3777 PaymentFailedConditions::new().mpp_parts_remain());
3779 // Rebalance the channel so the retry of the payment can succeed.
3780 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3782 // Retry the payment and make sure it succeeds
3783 route_params.payment_params.previously_failed_channels.push(chan_2_update.contents.short_channel_id);
3784 nodes[0].router.expect_find_route(route_params, Ok(route));
3785 nodes[0].node.process_pending_htlc_forwards();
3786 check_added_monitors!(nodes[0], 1);
3787 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3788 assert_eq!(events.len(), 1);
3789 let payment_claimable = pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000,
3790 payment_hash, Some(payment_secret), events.pop().unwrap(), true, None).unwrap();
3791 match payment_claimable {
3792 Event::PaymentClaimable { onion_fields, .. } => {
3793 assert_eq!(&onion_fields.unwrap().custom_tlvs()[..], &custom_tlvs[..]);
3795 _ => panic!("Unexpected event"),
3797 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
3801 fn test_custom_tlvs_consistency() {
3802 let even_type_1 = 1 << 16;
3803 let odd_type_1 = (1 << 16)+ 1;
3804 let even_type_2 = (1 << 16) + 2;
3805 let odd_type_2 = (1 << 16) + 3;
3806 let value_1 = || vec![1, 2, 3, 4];
3807 let differing_value_1 = || vec![1, 2, 3, 5];
3808 let value_2 = || vec![42u8; 16];
3810 // Drop missing odd tlvs
3811 do_test_custom_tlvs_consistency(
3812 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3813 vec![(odd_type_1, value_1())],
3814 Some(vec![(odd_type_1, value_1())]),
3816 // Drop non-matching odd tlvs
3817 do_test_custom_tlvs_consistency(
3818 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3819 vec![(odd_type_1, differing_value_1()), (odd_type_2, value_2())],
3820 Some(vec![(odd_type_2, value_2())]),
3822 // Fail missing even tlvs
3823 do_test_custom_tlvs_consistency(
3824 vec![(odd_type_1, value_1()), (even_type_2, value_2())],
3825 vec![(odd_type_1, value_1())],
3828 // Fail non-matching even tlvs
3829 do_test_custom_tlvs_consistency(
3830 vec![(even_type_1, value_1()), (odd_type_2, value_2())],
3831 vec![(even_type_1, differing_value_1()), (odd_type_2, value_2())],
3836 fn do_test_custom_tlvs_consistency(first_tlvs: Vec<(u64, Vec<u8>)>, second_tlvs: Vec<(u64, Vec<u8>)>,
3837 expected_receive_tlvs: Option<Vec<(u64, Vec<u8>)>>) {
3839 let chanmon_cfgs = create_chanmon_cfgs(4);
3840 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3841 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3842 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3844 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
3845 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
3846 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
3847 let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
3849 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3850 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
3851 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
3852 assert_eq!(route.paths.len(), 2);
3853 route.paths.sort_by(|path_a, _| {
3854 // Sort the path so that the path through nodes[1] comes first
3855 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3856 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
3859 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
3860 let payment_id = PaymentId([42; 32]);
3861 let amt_msat = 15_000_000;
3864 let onion_fields = RecipientOnionFields {
3865 payment_secret: Some(our_payment_secret),
3866 payment_metadata: None,
3867 custom_tlvs: first_tlvs
3869 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
3870 onion_fields.clone(), payment_id, &route).unwrap();
3871 let cur_height = nodes[0].best_block_info().1;
3872 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
3873 onion_fields.clone(), amt_msat, cur_height, payment_id,
3874 &None, session_privs[0]).unwrap();
3875 check_added_monitors!(nodes[0], 1);
3878 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3879 assert_eq!(events.len(), 1);
3880 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, our_payment_hash,
3881 Some(our_payment_secret), events.pop().unwrap(), false, None);
3883 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
3886 let onion_fields = RecipientOnionFields {
3887 payment_secret: Some(our_payment_secret),
3888 payment_metadata: None,
3889 custom_tlvs: second_tlvs
3891 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
3892 onion_fields.clone(), amt_msat, cur_height, payment_id, &None, session_privs[1]).unwrap();
3893 check_added_monitors!(nodes[0], 1);
3896 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3897 assert_eq!(events.len(), 1);
3898 let payment_event = SendEvent::from_event(events.pop().unwrap());
3900 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3901 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
3903 expect_pending_htlcs_forwardable!(nodes[2]);
3904 check_added_monitors!(nodes[2], 1);
3906 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
3907 assert_eq!(events.len(), 1);
3908 let payment_event = SendEvent::from_event(events.pop().unwrap());
3910 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
3911 check_added_monitors!(nodes[3], 0);
3912 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
3914 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3915 nodes[3].node.process_pending_htlc_forwards();
3917 if let Some(expected_tlvs) = expected_receive_tlvs {
3918 // Claim and match expected
3919 let events = nodes[3].node.get_and_clear_pending_events();
3920 assert_eq!(events.len(), 1);
3922 Event::PaymentClaimable { ref onion_fields, .. } => {
3923 assert_eq!(onion_fields.clone().unwrap().custom_tlvs, expected_tlvs);
3925 _ => panic!("Unexpected event"),
3928 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]],
3929 false, our_payment_preimage);
3930 expect_payment_sent(&nodes[0], our_payment_preimage, Some(Some(2000)), true, true);
3933 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3934 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], expected_destinations);
3935 check_added_monitors!(nodes[3], 1);
3937 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
3938 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
3939 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
3941 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![
3942 HTLCDestination::NextHopChannel {
3943 node_id: Some(nodes[3].node.get_our_node_id()),
3944 channel_id: chan_2_3.2
3946 check_added_monitors!(nodes[2], 1);
3948 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
3949 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
3950 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
3952 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true,
3953 PaymentFailedConditions::new().mpp_parts_remain());
3957 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3958 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3959 // another results in the HTLC being rejected.
3961 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3962 // first of which we'll deliver and the second of which we'll fail and then re-send with
3963 // modified payment metadata, which will in turn result in it being failed by the recipient.
3964 let chanmon_cfgs = create_chanmon_cfgs(4);
3965 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3967 let new_chain_monitor;
3969 let mut config = test_default_channel_config();
3970 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3971 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3972 let nodes_0_deserialized;
3974 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3976 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3977 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3978 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3979 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3981 // Pay more than half of each channel's max, requiring MPP
3982 let amt_msat = 750_000_000;
3983 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3984 let payment_id = PaymentId(payment_hash.0);
3985 let payment_metadata = vec![44, 49, 52, 142];
3987 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3988 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3989 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
3991 // Send the MPP payment, delivering the updated commitment state to nodes[1].
3992 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3993 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata), custom_tlvs: vec![],
3994 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3995 check_added_monitors!(nodes[0], 2);
3997 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3998 assert_eq!(send_events.len(), 2);
3999 let first_send = SendEvent::from_event(send_events.pop().unwrap());
4000 let second_send = SendEvent::from_event(send_events.pop().unwrap());
4002 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
4003 (&first_send, &second_send)
4005 (&second_send, &first_send)
4007 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
4008 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
4010 expect_pending_htlcs_forwardable!(nodes[1]);
4011 check_added_monitors(&nodes[1], 1);
4012 let b_forward_ev = SendEvent::from_node(&nodes[1]);
4013 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
4014 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
4016 expect_pending_htlcs_forwardable!(nodes[3]);
4018 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
4019 // will result in nodes[2] failing the HTLC back.
4020 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4021 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
4023 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
4024 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
4026 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
4027 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
4028 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
4030 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
4031 assert_eq!(payment_fail_retryable_evs.len(), 2);
4032 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
4033 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
4035 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
4036 // stored for our payment.
4038 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
4041 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
4042 // the payment state.
4044 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
4045 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
4046 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
4047 persister, new_chain_monitor, nodes_0_deserialized);
4048 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4049 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
4051 let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
4052 reconnect_args.send_channel_ready = (true, true);
4053 reconnect_nodes(reconnect_args);
4055 // Create a new channel between C and D as A will refuse to retry on the existing one because
4057 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
4059 // Now retry the failed HTLC.
4060 nodes[0].node.process_pending_htlc_forwards();
4061 check_added_monitors(&nodes[0], 1);
4062 let as_resend = SendEvent::from_node(&nodes[0]);
4063 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
4064 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
4066 expect_pending_htlcs_forwardable!(nodes[2]);
4067 check_added_monitors(&nodes[2], 1);
4068 let cs_forward = SendEvent::from_node(&nodes[2]);
4069 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
4070 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
4072 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
4073 // the payment metadata was modified, failing only the one modified HTLC and retaining the
4076 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
4077 nodes[3].node.process_pending_htlc_forwards();
4078 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
4079 &[HTLCDestination::FailedPayment {payment_hash}]);
4080 nodes[3].node.process_pending_htlc_forwards();
4082 check_added_monitors(&nodes[3], 1);
4083 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
4085 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
4086 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
4087 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
4088 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
4090 expect_pending_htlcs_forwardable!(nodes[3]);
4091 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
4092 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
4097 fn test_payment_metadata_consistency() {
4098 do_test_payment_metadata_consistency(true, true);
4099 do_test_payment_metadata_consistency(true, false);
4100 do_test_payment_metadata_consistency(false, true);
4101 do_test_payment_metadata_consistency(false, false);