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};
19 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
20 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails, RecipientOnionFields, HTLCForwardInfo, PendingHTLCRouting, PendingAddHTLCInfo};
21 use crate::ln::features::InvoiceFeatures;
22 use crate::ln::{msgs, PaymentSecret, PaymentPreimage};
23 use crate::ln::msgs::ChannelMessageHandler;
24 use crate::ln::outbound_payment::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::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
31 use crate::util::string::UntrustedString;
33 use bitcoin::network::constants::Network;
35 use crate::prelude::*;
37 use crate::ln::functional_test_utils::*;
38 use crate::routing::gossip::NodeId;
39 #[cfg(feature = "std")]
41 crate::util::time::tests::SinceEpoch,
42 std::time::{SystemTime, Instant, Duration}
47 let chanmon_cfgs = create_chanmon_cfgs(4);
48 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
49 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
50 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
52 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
53 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
54 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
55 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
57 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
58 let path = route.paths[0].clone();
59 route.paths.push(path);
60 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
61 route.paths[0].hops[0].short_channel_id = chan_1_id;
62 route.paths[0].hops[1].short_channel_id = chan_3_id;
63 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
64 route.paths[1].hops[0].short_channel_id = chan_2_id;
65 route.paths[1].hops[1].short_channel_id = chan_4_id;
66 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
67 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
72 let chanmon_cfgs = create_chanmon_cfgs(4);
73 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
74 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
75 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
77 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
78 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
79 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
80 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
82 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
84 let amt_msat = 1_000_000;
85 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
86 let path = route.paths[0].clone();
87 route.paths.push(path);
88 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
89 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
90 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
91 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
92 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
93 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
95 // Initiate the MPP payment.
96 let payment_id = PaymentId(payment_hash.0);
97 let mut route_params = RouteParameters {
98 payment_params: route.payment_params.clone().unwrap(),
99 final_value_msat: amt_msat,
102 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
103 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
104 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
105 check_added_monitors!(nodes[0], 2); // one monitor per path
106 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
107 assert_eq!(events.len(), 2);
109 // Pass half of the payment along the success path.
110 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
111 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
113 // Add the HTLC along the first hop.
114 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
115 let (update_add, commitment_signed) = match fail_path_msgs_1 {
116 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
117 assert_eq!(update_add_htlcs.len(), 1);
118 assert!(update_fail_htlcs.is_empty());
119 assert!(update_fulfill_htlcs.is_empty());
120 assert!(update_fail_malformed_htlcs.is_empty());
121 assert!(update_fee.is_none());
122 (update_add_htlcs[0].clone(), commitment_signed.clone())
124 _ => panic!("Unexpected event"),
126 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
127 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
129 // Attempt to forward the payment and complete the 2nd path's failure.
130 expect_pending_htlcs_forwardable!(&nodes[2]);
131 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 }]);
132 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
133 assert!(htlc_updates.update_add_htlcs.is_empty());
134 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
135 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
136 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
137 check_added_monitors!(nodes[2], 1);
138 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
139 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
140 let mut events = nodes[0].node.get_and_clear_pending_events();
142 Event::PendingHTLCsForwardable { .. } => {},
143 _ => panic!("Unexpected event")
146 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
148 // Rebalance the channel so the second half of the payment can succeed.
149 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
151 // Retry the second half of the payment and make sure it succeeds.
152 route.paths.remove(0);
153 route_params.final_value_msat = 1_000_000;
154 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
155 nodes[0].router.expect_find_route(route_params, Ok(route));
156 nodes[0].node.process_pending_htlc_forwards();
157 check_added_monitors!(nodes[0], 1);
158 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
159 assert_eq!(events.len(), 1);
160 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
161 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
164 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
165 let chanmon_cfgs = create_chanmon_cfgs(4);
166 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
167 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
168 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
170 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
171 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
172 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
173 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
175 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
176 let path = route.paths[0].clone();
177 route.paths.push(path);
178 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
179 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
180 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
181 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
182 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
183 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
185 // Initiate the MPP payment.
186 nodes[0].node.send_payment_with_route(&route, payment_hash,
187 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
188 check_added_monitors!(nodes[0], 2); // one monitor per path
189 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
190 assert_eq!(events.len(), 2);
192 // Pass half of the payment along the first path.
193 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
194 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
196 if send_partial_mpp {
197 // Time out the partial MPP
198 for _ in 0..MPP_TIMEOUT_TICKS {
199 nodes[3].node.timer_tick_occurred();
202 // Failed HTLC from node 3 -> 1
203 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
204 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
205 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
206 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
207 check_added_monitors!(nodes[3], 1);
208 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
210 // Failed HTLC from node 1 -> 0
211 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 }]);
212 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
213 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
214 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
215 check_added_monitors!(nodes[1], 1);
216 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
218 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
220 // Pass half of the payment along the second path.
221 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
222 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
224 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
225 for _ in 0..MPP_TIMEOUT_TICKS {
226 nodes[3].node.timer_tick_occurred();
229 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
234 fn mpp_receive_timeout() {
235 do_mpp_receive_timeout(true);
236 do_mpp_receive_timeout(false);
240 fn test_mpp_keysend() {
241 let mut mpp_keysend_config = test_default_channel_config();
242 mpp_keysend_config.accept_mpp_keysend = true;
243 let chanmon_cfgs = create_chanmon_cfgs(4);
244 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
245 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
246 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
248 create_announced_chan_between_nodes(&nodes, 0, 1);
249 create_announced_chan_between_nodes(&nodes, 0, 2);
250 create_announced_chan_between_nodes(&nodes, 1, 3);
251 create_announced_chan_between_nodes(&nodes, 2, 3);
252 let network_graph = nodes[0].network_graph.clone();
254 let payer_pubkey = nodes[0].node.get_our_node_id();
255 let payee_pubkey = nodes[3].node.get_our_node_id();
256 let recv_value = 15_000_000;
257 let route_params = RouteParameters {
258 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, true),
259 final_value_msat: recv_value,
261 let scorer = test_utils::TestScorer::new();
262 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
263 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger,
264 &scorer, &(), &random_seed_bytes).unwrap();
266 let payment_preimage = PaymentPreimage([42; 32]);
267 let payment_secret = PaymentSecret(payment_preimage.0);
268 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
269 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_preimage.0)).unwrap();
270 check_added_monitors!(nodes[0], 2);
272 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
273 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
274 assert_eq!(events.len(), 2);
276 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
277 pass_along_path(&nodes[0], expected_route[0], recv_value, payment_hash.clone(),
278 Some(payment_secret), ev.clone(), false, Some(payment_preimage));
280 let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
281 pass_along_path(&nodes[0], expected_route[1], recv_value, payment_hash.clone(),
282 Some(payment_secret), ev.clone(), true, Some(payment_preimage));
283 claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
287 fn test_reject_mpp_keysend_htlc() {
288 // This test enforces that we reject MPP keysend HTLCs if our config states we don't support
289 // MPP keysend. When receiving a payment, if we don't support MPP keysend we'll reject the
290 // payment if it's keysend and has a payment secret, never reaching our payment validation
291 // logic. To check that we enforce rejecting MPP keysends in our payment logic, here we send
292 // keysend payments without payment secrets, then modify them by adding payment secrets in the
293 // final node in between receiving the HTLCs and actually processing them.
294 let mut reject_mpp_keysend_cfg = test_default_channel_config();
295 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
297 let chanmon_cfgs = create_chanmon_cfgs(4);
298 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
299 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(reject_mpp_keysend_cfg)]);
300 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
301 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
302 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
303 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
304 let (update_a, _, chan_4_channel_id, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
305 let chan_4_id = update_a.contents.short_channel_id;
307 let (mut route, payment_hash, payment_preimage, _) = get_route_and_payment_hash!(nodes[0], nodes[3], amount);
309 // Pay along nodes[1]
310 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
311 route.paths[0].hops[0].short_channel_id = chan_1_id;
312 route.paths[0].hops[1].short_channel_id = chan_3_id;
314 let payment_id_0 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
315 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_0).unwrap();
316 check_added_monitors!(nodes[0], 1);
318 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
319 let update_add_0 = update_0.update_add_htlcs[0].clone();
320 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
321 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
322 expect_pending_htlcs_forwardable!(nodes[1]);
324 check_added_monitors!(&nodes[1], 1);
325 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[3].node.get_our_node_id());
326 let update_add_1 = update_1.update_add_htlcs[0].clone();
327 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
328 commitment_signed_dance!(nodes[3], nodes[1], update_1.commitment_signed, false, true);
330 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
331 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
332 for f in pending_forwards.iter_mut() {
334 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
335 match forward_info.routing {
336 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
337 *payment_data = Some(msgs::FinalOnionHopData {
338 payment_secret: PaymentSecret([42; 32]),
339 total_msat: amount * 2,
342 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
349 expect_pending_htlcs_forwardable!(nodes[3]);
351 // Pay along nodes[2]
352 route.paths[0].hops[0].pubkey = nodes[2].node.get_our_node_id();
353 route.paths[0].hops[0].short_channel_id = chan_2_id;
354 route.paths[0].hops[1].short_channel_id = chan_4_id;
356 let payment_id_1 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
357 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
358 check_added_monitors!(nodes[0], 1);
360 let update_2 = get_htlc_update_msgs!(nodes[0], nodes[2].node.get_our_node_id());
361 let update_add_2 = update_2.update_add_htlcs[0].clone();
362 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_2);
363 commitment_signed_dance!(nodes[2], nodes[0], &update_2.commitment_signed, false, true);
364 expect_pending_htlcs_forwardable!(nodes[2]);
366 check_added_monitors!(&nodes[2], 1);
367 let update_3 = get_htlc_update_msgs!(nodes[2], nodes[3].node.get_our_node_id());
368 let update_add_3 = update_3.update_add_htlcs[0].clone();
369 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &update_add_3);
370 commitment_signed_dance!(nodes[3], nodes[2], update_3.commitment_signed, false, true);
372 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
373 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
374 for f in pending_forwards.iter_mut() {
376 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
377 match forward_info.routing {
378 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
379 *payment_data = Some(msgs::FinalOnionHopData {
380 payment_secret: PaymentSecret([42; 32]),
381 total_msat: amount * 2,
384 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
391 expect_pending_htlcs_forwardable!(nodes[3]);
392 check_added_monitors!(nodes[3], 1);
394 // Fail back along nodes[2]
395 let update_fail_0 = get_htlc_update_msgs!(&nodes[3], &nodes[2].node.get_our_node_id());
396 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &update_fail_0.update_fail_htlcs[0]);
397 commitment_signed_dance!(nodes[2], nodes[3], update_fail_0.commitment_signed, false);
398 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 }]);
399 check_added_monitors!(nodes[2], 1);
401 let update_fail_1 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
402 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_1.update_fail_htlcs[0]);
403 commitment_signed_dance!(nodes[0], nodes[2], update_fail_1.commitment_signed, false);
405 expect_payment_failed_conditions(&nodes[0], payment_hash, true, PaymentFailedConditions::new());
406 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
411 fn no_pending_leak_on_initial_send_failure() {
412 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
413 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
414 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
415 // pending payment forever and never time it out.
416 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
417 // try, and then check that no pending payment is being tracked.
418 let chanmon_cfgs = create_chanmon_cfgs(2);
419 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
420 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
421 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
423 create_announced_chan_between_nodes(&nodes, 0, 1);
425 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
427 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
428 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
430 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
431 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
432 ), true, APIError::ChannelUnavailable { ref err },
433 assert_eq!(err, "Peer for first hop currently disconnected"));
435 assert!(!nodes[0].node.has_pending_payments());
438 fn do_retry_with_no_persist(confirm_before_reload: bool) {
439 // If we send a pending payment and `send_payment` returns success, we should always either
440 // return a payment failure event or a payment success event, and on failure the payment should
443 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
444 // always persisted asynchronously), the ChannelManager has to reload some payment data from
445 // ChannelMonitor(s) in some cases. This tests that reloading.
447 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
448 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
449 // which has separate codepaths for "commitment transaction already confirmed" and not.
450 let chanmon_cfgs = create_chanmon_cfgs(3);
451 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
452 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
453 let persister: test_utils::TestPersister;
454 let new_chain_monitor: test_utils::TestChainMonitor;
455 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
456 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
458 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
459 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
461 // Serialize the ChannelManager prior to sending payments
462 let nodes_0_serialized = nodes[0].node.encode();
464 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
466 let amt_msat = 1_000_000;
467 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
468 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
469 let route_params = RouteParameters {
470 payment_params: route.payment_params.clone().unwrap(),
471 final_value_msat: amt_msat,
473 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
474 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
475 check_added_monitors!(nodes[0], 1);
477 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
478 assert_eq!(events.len(), 1);
479 let payment_event = SendEvent::from_event(events.pop().unwrap());
480 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
482 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
483 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
484 // which would prevent retry.
485 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
486 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
488 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
489 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
490 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
491 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
493 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
495 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
496 if confirm_before_reload {
497 mine_transaction(&nodes[0], &as_commitment_tx);
498 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
501 // The ChannelMonitor should always be the latest version, as we're required to persist it
502 // during the `commitment_signed_dance!()`.
503 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
504 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
506 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
507 // force-close the channel.
508 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
509 assert!(nodes[0].node.list_channels().is_empty());
510 assert!(nodes[0].node.has_pending_payments());
511 nodes[0].node.timer_tick_occurred();
512 if !confirm_before_reload {
513 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
514 assert_eq!(as_broadcasted_txn.len(), 1);
515 assert_eq!(as_broadcasted_txn[0].txid(), as_commitment_tx.txid());
517 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
519 check_added_monitors!(nodes[0], 1);
521 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
522 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
523 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
525 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
527 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
528 // error, as the channel has hit the chain.
529 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
530 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
532 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
533 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
534 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
535 assert_eq!(as_err.len(), 1);
537 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
538 assert_eq!(node_id, nodes[1].node.get_our_node_id());
539 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
540 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())) });
541 check_added_monitors!(nodes[1], 1);
542 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
544 _ => panic!("Unexpected event"),
546 check_closed_broadcast!(nodes[1], false);
548 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
549 // we close in a moment.
550 nodes[2].node.claim_funds(payment_preimage_1);
551 check_added_monitors!(nodes[2], 1);
552 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
554 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
555 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
556 check_added_monitors!(nodes[1], 1);
557 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
558 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
560 if confirm_before_reload {
561 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
562 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
565 // Create a new channel on which to retry the payment before we fail the payment via the
566 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
567 // connecting several blocks while creating the channel (implying time has passed).
568 create_announced_chan_between_nodes(&nodes, 0, 1);
569 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
571 mine_transaction(&nodes[1], &as_commitment_tx);
572 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
573 assert_eq!(bs_htlc_claim_txn.len(), 1);
574 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
576 if !confirm_before_reload {
577 mine_transaction(&nodes[0], &as_commitment_tx);
579 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
580 expect_payment_sent!(nodes[0], payment_preimage_1);
581 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
582 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
583 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
584 assert_eq!(txn.len(), 2);
585 (txn.remove(0), txn.remove(0))
587 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
588 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
589 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
590 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
592 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
594 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
595 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
597 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
598 // reloaded) via a route over the new channel, which work without issue and eventually be
599 // received and claimed at the recipient just like any other payment.
600 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
602 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
603 // and not the original fee. We also update node[1]'s relevant config as
604 // do_claim_payment_along_route expects us to never overpay.
606 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
607 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
608 .unwrap().lock().unwrap();
609 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
610 let mut new_config = channel.context.config();
611 new_config.forwarding_fee_base_msat += 100_000;
612 channel.context.update_config(&new_config);
613 new_route.paths[0].hops[0].fee_msat += 100_000;
616 // Force expiration of the channel's previous config.
617 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
618 nodes[1].node.timer_tick_occurred();
621 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
622 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
623 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
624 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
625 check_added_monitors!(nodes[0], 1);
626 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
627 assert_eq!(events.len(), 1);
628 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
629 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
630 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
634 fn retry_with_no_persist() {
635 do_retry_with_no_persist(true);
636 do_retry_with_no_persist(false);
639 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
640 // Test that an off-chain completed payment is not retryable on restart. This was previously
641 // broken for dust payments, but we test for both dust and non-dust payments.
643 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
645 let chanmon_cfgs = create_chanmon_cfgs(3);
646 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
648 let mut manually_accept_config = test_default_channel_config();
649 manually_accept_config.manually_accept_inbound_channels = true;
651 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
653 let first_persister: test_utils::TestPersister;
654 let first_new_chain_monitor: test_utils::TestChainMonitor;
655 let first_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
656 let second_persister: test_utils::TestPersister;
657 let second_new_chain_monitor: test_utils::TestChainMonitor;
658 let second_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
659 let third_persister: test_utils::TestPersister;
660 let third_new_chain_monitor: test_utils::TestChainMonitor;
661 let third_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
663 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
665 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
666 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
667 confirm_transaction(&nodes[0], &funding_tx);
668 confirm_transaction(&nodes[1], &funding_tx);
669 // Ignore the announcement_signatures messages
670 nodes[0].node.get_and_clear_pending_msg_events();
671 nodes[1].node.get_and_clear_pending_msg_events();
672 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
674 // Serialize the ChannelManager prior to sending payments
675 let mut nodes_0_serialized = nodes[0].node.encode();
677 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
678 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 });
680 // The ChannelMonitor should always be the latest version, as we're required to persist it
681 // during the `commitment_signed_dance!()`.
682 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
684 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);
685 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
687 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
688 // force-close the channel.
689 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
690 nodes[0].node.timer_tick_occurred();
691 assert!(nodes[0].node.list_channels().is_empty());
692 assert!(nodes[0].node.has_pending_payments());
693 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
694 check_added_monitors!(nodes[0], 1);
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);
710 let bs_commitment_tx;
712 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
713 assert_eq!(node_id, nodes[1].node.get_our_node_id());
714 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
715 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())) });
716 check_added_monitors!(nodes[1], 1);
717 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
719 _ => panic!("Unexpected event"),
721 check_closed_broadcast!(nodes[1], false);
723 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
724 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
725 // incoming HTLCs with the same payment hash later.
726 nodes[2].node.fail_htlc_backwards(&payment_hash);
727 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
728 check_added_monitors!(nodes[2], 1);
730 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
731 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
732 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
733 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
734 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
736 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
737 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
738 // after the commitment transaction, so always connect the commitment transaction.
739 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
740 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
742 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
743 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
744 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
745 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
746 assert_eq!(as_htlc_timeout.len(), 1);
748 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
749 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
750 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
751 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
754 // Create a new channel on which to retry the payment before we fail the payment via the
755 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
756 // connecting several blocks while creating the channel (implying time has passed).
757 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
758 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
759 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
761 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
762 // confirming, we will fail as it's considered still-pending...
763 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
764 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
765 Err(PaymentSendFailure::DuplicatePayment) => {},
766 _ => panic!("Unexpected error")
768 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
770 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
771 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
772 // (which should also still work).
773 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
774 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
775 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
777 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
778 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
779 nodes_0_serialized = nodes[0].node.encode();
781 // After the payment failed, we're free to send it again.
782 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
783 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
784 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
786 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);
787 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
789 nodes[0].node.test_process_background_events();
790 check_added_monitors(&nodes[0], 1);
792 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
794 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
795 // the payment is not (spuriously) listed as still pending.
796 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
797 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
798 check_added_monitors!(nodes[0], 1);
799 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
800 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
802 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
803 Err(PaymentSendFailure::DuplicatePayment) => {},
804 _ => panic!("Unexpected error")
806 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
809 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
810 nodes_0_serialized = nodes[0].node.encode();
812 // Check that after reload we can send the payment again (though we shouldn't, since it was
813 // claimed previously).
814 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);
815 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
817 nodes[0].node.test_process_background_events();
818 check_added_monitors(&nodes[0], 1);
820 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
822 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
823 Err(PaymentSendFailure::DuplicatePayment) => {},
824 _ => panic!("Unexpected error")
826 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
830 fn test_completed_payment_not_retryable_on_reload() {
831 do_test_completed_payment_not_retryable_on_reload(true);
832 do_test_completed_payment_not_retryable_on_reload(false);
836 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
837 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
838 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
839 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
840 // the ChannelMonitor tells it to.
842 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
843 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
844 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
845 let chanmon_cfgs = create_chanmon_cfgs(2);
846 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
847 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
848 let persister: test_utils::TestPersister;
849 let new_chain_monitor: test_utils::TestChainMonitor;
850 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
851 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
853 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
855 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
857 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
858 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
859 check_closed_broadcast!(nodes[0], true);
860 check_added_monitors!(nodes[0], 1);
861 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
863 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
864 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
866 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
867 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
868 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
869 assert_eq!(node_txn.len(), 3);
870 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
871 check_spends!(node_txn[1], funding_tx);
872 check_spends!(node_txn[2], node_txn[1]);
873 let timeout_txn = vec![node_txn[2].clone()];
875 nodes[1].node.claim_funds(payment_preimage);
876 check_added_monitors!(nodes[1], 1);
877 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
879 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[1].clone()]));
880 check_closed_broadcast!(nodes[1], true);
881 check_added_monitors!(nodes[1], 1);
882 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
883 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
884 assert_eq!(claim_txn.len(), 1);
885 check_spends!(claim_txn[0], node_txn[1]);
887 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[1].clone()]));
889 if confirm_commitment_tx {
890 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
893 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] });
896 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
897 connect_block(&nodes[0], &claim_block);
898 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
901 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
902 // returning InProgress. This should cause the claim event to never make its way to the
904 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
905 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
908 connect_blocks(&nodes[0], 1);
910 connect_block(&nodes[0], &claim_block);
913 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
914 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
915 .get_mut(&funding_txo).unwrap().drain().collect();
916 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
917 // If we're testing connection idempotency we may get substantially more.
918 assert!(mon_updates.len() >= 1);
919 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
920 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
922 // If we persist the ChannelManager here, we should get the PaymentSent event after
924 let mut chan_manager_serialized = Vec::new();
925 if !persist_manager_post_event {
926 chan_manager_serialized = nodes[0].node.encode();
929 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
930 // payment sent event.
931 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
932 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
933 for update in mon_updates {
934 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
937 expect_payment_failed!(nodes[0], payment_hash, false);
939 expect_payment_sent!(nodes[0], payment_preimage);
942 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
944 if persist_manager_post_event {
945 chan_manager_serialized = nodes[0].node.encode();
948 // Now reload nodes[0]...
949 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
951 if persist_manager_post_event {
952 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
953 } else if payment_timeout {
954 expect_payment_failed!(nodes[0], payment_hash, false);
956 expect_payment_sent!(nodes[0], payment_preimage);
959 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
960 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
961 // payment events should kick in, leaving us with no pending events here.
962 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
963 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
964 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
965 check_added_monitors(&nodes[0], 1);
969 fn test_dup_htlc_onchain_fails_on_reload() {
970 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
971 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
972 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
973 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
974 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
975 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
979 fn test_fulfill_restart_failure() {
980 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
981 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
982 // again, or fail it, giving us free money.
984 // Of course probably they won't fail it and give us free money, but because we have code to
985 // handle it, we should test the logic for it anyway. We do that here.
986 let chanmon_cfgs = create_chanmon_cfgs(2);
987 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
988 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
989 let persister: test_utils::TestPersister;
990 let new_chain_monitor: test_utils::TestChainMonitor;
991 let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
992 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
994 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
995 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
997 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
998 // pre-fulfill, which we do by serializing it here.
999 let chan_manager_serialized = nodes[1].node.encode();
1000 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1002 nodes[1].node.claim_funds(payment_preimage);
1003 check_added_monitors!(nodes[1], 1);
1004 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1006 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1007 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1008 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
1010 // Now reload nodes[1]...
1011 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1013 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1014 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
1016 nodes[1].node.fail_htlc_backwards(&payment_hash);
1017 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1018 check_added_monitors!(nodes[1], 1);
1019 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1020 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1021 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1022 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1023 // it had already considered the payment fulfilled, and now they just got free money.
1024 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1028 fn get_ldk_payment_preimage() {
1029 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1030 let chanmon_cfgs = create_chanmon_cfgs(2);
1031 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1032 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1033 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1034 create_announced_chan_between_nodes(&nodes, 0, 1);
1036 let amt_msat = 60_000;
1037 let expiry_secs = 60 * 60;
1038 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1040 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1041 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
1042 let scorer = test_utils::TestScorer::new();
1043 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1044 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1045 let route = get_route(
1046 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
1047 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
1048 amt_msat, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
1049 nodes[0].node.send_payment_with_route(&route, payment_hash,
1050 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1051 check_added_monitors!(nodes[0], 1);
1053 // Make sure to use `get_payment_preimage`
1054 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1055 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1056 assert_eq!(events.len(), 1);
1057 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1058 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1062 fn sent_probe_is_probe_of_sending_node() {
1063 let chanmon_cfgs = create_chanmon_cfgs(3);
1064 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1065 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1066 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1068 create_announced_chan_between_nodes(&nodes, 0, 1);
1069 create_announced_chan_between_nodes(&nodes, 1, 2);
1071 // First check we refuse to build a single-hop probe
1072 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1073 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1075 // Then build an actual two-hop probing path
1076 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1078 match nodes[0].node.send_probe(route.paths[0].clone()) {
1079 Ok((payment_hash, payment_id)) => {
1080 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1081 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1082 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1087 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1088 check_added_monitors!(nodes[0], 1);
1092 fn successful_probe_yields_event() {
1093 let chanmon_cfgs = create_chanmon_cfgs(3);
1094 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1095 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1096 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1098 create_announced_chan_between_nodes(&nodes, 0, 1);
1099 create_announced_chan_between_nodes(&nodes, 1, 2);
1101 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1103 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1105 // node[0] -- update_add_htlcs -> node[1]
1106 check_added_monitors!(nodes[0], 1);
1107 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1108 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1109 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1110 check_added_monitors!(nodes[1], 0);
1111 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1112 expect_pending_htlcs_forwardable!(nodes[1]);
1114 // node[1] -- update_add_htlcs -> node[2]
1115 check_added_monitors!(nodes[1], 1);
1116 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1117 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1118 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1119 check_added_monitors!(nodes[2], 0);
1120 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
1122 // node[1] <- update_fail_htlcs -- node[2]
1123 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1124 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1125 check_added_monitors!(nodes[1], 0);
1126 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1128 // node[0] <- update_fail_htlcs -- node[1]
1129 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1130 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1131 check_added_monitors!(nodes[0], 0);
1132 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1134 let mut events = nodes[0].node.get_and_clear_pending_events();
1135 assert_eq!(events.len(), 1);
1136 match events.drain(..).next().unwrap() {
1137 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1138 assert_eq!(payment_id, ev_pid);
1139 assert_eq!(payment_hash, ev_ph);
1143 assert!(!nodes[0].node.has_pending_payments());
1147 fn failed_probe_yields_event() {
1148 let chanmon_cfgs = create_chanmon_cfgs(3);
1149 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1150 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1151 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1153 create_announced_chan_between_nodes(&nodes, 0, 1);
1154 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1156 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1158 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000);
1160 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1162 // node[0] -- update_add_htlcs -> node[1]
1163 check_added_monitors!(nodes[0], 1);
1164 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1165 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1166 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1167 check_added_monitors!(nodes[1], 0);
1168 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1169 expect_pending_htlcs_forwardable!(nodes[1]);
1171 // node[0] <- update_fail_htlcs -- node[1]
1172 check_added_monitors!(nodes[1], 1);
1173 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1174 // Skip the PendingHTLCsForwardable event
1175 let _events = nodes[1].node.get_and_clear_pending_events();
1176 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1177 check_added_monitors!(nodes[0], 0);
1178 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1180 let mut events = nodes[0].node.get_and_clear_pending_events();
1181 assert_eq!(events.len(), 1);
1182 match events.drain(..).next().unwrap() {
1183 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1184 assert_eq!(payment_id, ev_pid);
1185 assert_eq!(payment_hash, ev_ph);
1189 assert!(!nodes[0].node.has_pending_payments());
1193 fn onchain_failed_probe_yields_event() {
1194 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1196 let chanmon_cfgs = create_chanmon_cfgs(3);
1197 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1198 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1199 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1201 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1202 create_announced_chan_between_nodes(&nodes, 1, 2);
1204 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1206 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1207 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000);
1208 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1210 // node[0] -- update_add_htlcs -> node[1]
1211 check_added_monitors!(nodes[0], 1);
1212 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1213 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1214 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1215 check_added_monitors!(nodes[1], 0);
1216 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1217 expect_pending_htlcs_forwardable!(nodes[1]);
1219 check_added_monitors!(nodes[1], 1);
1220 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1222 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1223 // Node A, which after 6 confirmations should result in a probe failure event.
1224 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1225 confirm_transaction(&nodes[0], &bs_txn[0]);
1226 check_closed_broadcast!(&nodes[0], true);
1227 check_added_monitors!(nodes[0], 1);
1229 let mut events = nodes[0].node.get_and_clear_pending_events();
1230 assert_eq!(events.len(), 2);
1231 let mut found_probe_failed = false;
1232 for event in events.drain(..) {
1234 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1235 assert_eq!(payment_id, ev_pid);
1236 assert_eq!(payment_hash, ev_ph);
1237 found_probe_failed = true;
1239 Event::ChannelClosed { .. } => {},
1243 assert!(found_probe_failed);
1244 assert!(!nodes[0].node.has_pending_payments());
1248 fn claimed_send_payment_idempotent() {
1249 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1250 let chanmon_cfgs = create_chanmon_cfgs(2);
1251 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1252 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1253 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1255 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1257 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1258 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1260 macro_rules! check_send_rejected {
1262 // If we try to resend a new payment with a different payment_hash but with the same
1263 // payment_id, it should be rejected.
1264 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1265 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1267 Err(PaymentSendFailure::DuplicatePayment) => {},
1268 _ => panic!("Unexpected send result: {:?}", send_result),
1271 // Further, if we try to send a spontaneous payment with the same payment_id it should
1272 // also be rejected.
1273 let send_result = nodes[0].node.send_spontaneous_payment(
1274 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1276 Err(PaymentSendFailure::DuplicatePayment) => {},
1277 _ => panic!("Unexpected send result: {:?}", send_result),
1282 check_send_rejected!();
1284 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1285 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1286 // we must remain just as idempotent as we were before.
1287 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1289 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1290 nodes[0].node.timer_tick_occurred();
1293 check_send_rejected!();
1295 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1296 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1297 // the payment complete. However, they could have called `send_payment` while the event was
1298 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1299 // after the event is handled a duplicate payment should sitll be rejected.
1300 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1301 check_send_rejected!();
1303 // If relatively little time has passed, a duplicate payment should still fail.
1304 nodes[0].node.timer_tick_occurred();
1305 check_send_rejected!();
1307 // However, after some time has passed (at least more than the one timer tick above), a
1308 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1309 // references to the old payment data.
1310 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1311 nodes[0].node.timer_tick_occurred();
1314 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1315 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1316 check_added_monitors!(nodes[0], 1);
1317 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1318 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1322 fn abandoned_send_payment_idempotent() {
1323 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1325 let chanmon_cfgs = create_chanmon_cfgs(2);
1326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1328 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1330 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1332 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1333 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1335 macro_rules! check_send_rejected {
1337 // If we try to resend a new payment with a different payment_hash but with the same
1338 // payment_id, it should be rejected.
1339 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1340 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1342 Err(PaymentSendFailure::DuplicatePayment) => {},
1343 _ => panic!("Unexpected send result: {:?}", send_result),
1346 // Further, if we try to send a spontaneous payment with the same payment_id it should
1347 // also be rejected.
1348 let send_result = nodes[0].node.send_spontaneous_payment(
1349 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1351 Err(PaymentSendFailure::DuplicatePayment) => {},
1352 _ => panic!("Unexpected send result: {:?}", send_result),
1357 check_send_rejected!();
1359 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1360 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1362 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1364 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1365 nodes[0].node.timer_tick_occurred();
1367 check_send_rejected!();
1369 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1371 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1372 // failed payment back.
1373 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1374 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1375 check_added_monitors!(nodes[0], 1);
1376 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1377 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1380 #[derive(PartialEq)]
1381 enum InterceptTest {
1388 fn test_trivial_inflight_htlc_tracking(){
1389 // In this test, we test three scenarios:
1390 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1391 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1392 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1393 let chanmon_cfgs = create_chanmon_cfgs(3);
1394 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1395 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1396 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1398 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1399 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1401 // Send and claim the payment. Inflight HTLCs should be empty.
1402 let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1403 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1405 let mut node_0_per_peer_lock;
1406 let mut node_0_peer_state_lock;
1407 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1409 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1410 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1411 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1412 channel_1.context.get_short_channel_id().unwrap()
1414 assert_eq!(chan_1_used_liquidity, None);
1417 let mut node_1_per_peer_lock;
1418 let mut node_1_peer_state_lock;
1419 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1421 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1422 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1423 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1424 channel_2.context.get_short_channel_id().unwrap()
1427 assert_eq!(chan_2_used_liquidity, None);
1429 let pending_payments = nodes[0].node.list_recent_payments();
1430 assert_eq!(pending_payments.len(), 1);
1431 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1433 // Remove fulfilled payment
1434 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1435 nodes[0].node.timer_tick_occurred();
1438 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1439 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1440 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1442 let mut node_0_per_peer_lock;
1443 let mut node_0_peer_state_lock;
1444 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1446 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1447 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1448 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1449 channel_1.context.get_short_channel_id().unwrap()
1451 // First hop accounts for expected 1000 msat fee
1452 assert_eq!(chan_1_used_liquidity, Some(501000));
1455 let mut node_1_per_peer_lock;
1456 let mut node_1_peer_state_lock;
1457 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1459 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1460 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1461 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1462 channel_2.context.get_short_channel_id().unwrap()
1465 assert_eq!(chan_2_used_liquidity, Some(500000));
1467 let pending_payments = nodes[0].node.list_recent_payments();
1468 assert_eq!(pending_payments.len(), 1);
1469 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1471 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1472 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1474 // Remove fulfilled payment
1475 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1476 nodes[0].node.timer_tick_occurred();
1479 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1481 let mut node_0_per_peer_lock;
1482 let mut node_0_peer_state_lock;
1483 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1485 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1486 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1487 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1488 channel_1.context.get_short_channel_id().unwrap()
1490 assert_eq!(chan_1_used_liquidity, None);
1493 let mut node_1_per_peer_lock;
1494 let mut node_1_peer_state_lock;
1495 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1497 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1498 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1499 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1500 channel_2.context.get_short_channel_id().unwrap()
1502 assert_eq!(chan_2_used_liquidity, None);
1505 let pending_payments = nodes[0].node.list_recent_payments();
1506 assert_eq!(pending_payments.len(), 0);
1510 fn test_holding_cell_inflight_htlcs() {
1511 let chanmon_cfgs = create_chanmon_cfgs(2);
1512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1514 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1515 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1517 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1518 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1520 // Queue up two payments - one will be delivered right away, one immediately goes into the
1521 // holding cell as nodes[0] is AwaitingRAA.
1523 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1524 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1525 check_added_monitors!(nodes[0], 1);
1526 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1527 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1528 check_added_monitors!(nodes[0], 0);
1531 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1534 let mut node_0_per_peer_lock;
1535 let mut node_0_peer_state_lock;
1536 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1538 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1539 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1540 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1541 channel.context.get_short_channel_id().unwrap()
1544 assert_eq!(used_liquidity, Some(2000000));
1547 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1548 nodes[0].node.get_and_clear_pending_msg_events();
1552 fn intercepted_payment() {
1553 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1554 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1555 // payment or (b) fail the payment.
1556 do_test_intercepted_payment(InterceptTest::Forward);
1557 do_test_intercepted_payment(InterceptTest::Fail);
1558 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1559 do_test_intercepted_payment(InterceptTest::Timeout);
1562 fn do_test_intercepted_payment(test: InterceptTest) {
1563 let chanmon_cfgs = create_chanmon_cfgs(3);
1564 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1566 let mut zero_conf_chan_config = test_default_channel_config();
1567 zero_conf_chan_config.manually_accept_inbound_channels = true;
1568 let mut intercept_forwards_config = test_default_channel_config();
1569 intercept_forwards_config.accept_intercept_htlcs = true;
1570 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1572 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1573 let scorer = test_utils::TestScorer::new();
1574 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1576 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1578 let amt_msat = 100_000;
1579 let intercept_scid = nodes[1].node.get_intercept_scid();
1580 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1581 .with_route_hints(vec![
1582 RouteHint(vec![RouteHintHop {
1583 src_node_id: nodes[1].node.get_our_node_id(),
1584 short_channel_id: intercept_scid,
1587 proportional_millionths: 0,
1589 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1590 htlc_minimum_msat: None,
1591 htlc_maximum_msat: None,
1594 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1595 let route_params = RouteParameters {
1597 final_value_msat: amt_msat,
1599 let route = get_route(
1600 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1601 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1602 nodes[0].logger, &scorer, &(), &random_seed_bytes,
1605 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1606 nodes[0].node.send_payment_with_route(&route, payment_hash,
1607 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1608 let payment_event = {
1610 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1611 assert_eq!(added_monitors.len(), 1);
1612 added_monitors.clear();
1614 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1615 assert_eq!(events.len(), 1);
1616 SendEvent::from_event(events.remove(0))
1618 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1619 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1621 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1622 let events = nodes[1].node.get_and_clear_pending_events();
1623 assert_eq!(events.len(), 1);
1624 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1625 crate::events::Event::HTLCIntercepted {
1626 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1628 assert_eq!(pmt_hash, payment_hash);
1629 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1630 assert_eq!(short_channel_id, intercept_scid);
1631 (intercept_id, expected_outbound_amount_msat)
1636 // Check for unknown channel id error.
1637 let unknown_chan_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &[42; 32], nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1638 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable {
1639 err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1640 log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1642 if test == InterceptTest::Fail {
1643 // Ensure we can fail the intercepted payment back.
1644 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1645 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1646 nodes[1].node.process_pending_htlc_forwards();
1647 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1648 check_added_monitors!(&nodes[1], 1);
1649 assert!(update_fail.update_fail_htlcs.len() == 1);
1650 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1651 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1652 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1654 // Ensure the payment fails with the expected error.
1655 let fail_conditions = PaymentFailedConditions::new()
1656 .blamed_scid(intercept_scid)
1657 .blamed_chan_closed(true)
1658 .expected_htlc_error_data(0x4000 | 10, &[]);
1659 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1660 } else if test == InterceptTest::Forward {
1661 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1662 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1663 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();
1664 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1665 err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1666 log_bytes!(temp_chan_id), nodes[2].node.get_our_node_id()) });
1667 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1669 // Open the just-in-time channel so the payment can then be forwarded.
1670 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1672 // Finally, forward the intercepted payment through and claim it.
1673 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1674 expect_pending_htlcs_forwardable!(nodes[1]);
1676 let payment_event = {
1678 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1679 assert_eq!(added_monitors.len(), 1);
1680 added_monitors.clear();
1682 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1683 assert_eq!(events.len(), 1);
1684 SendEvent::from_event(events.remove(0))
1686 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1687 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1688 expect_pending_htlcs_forwardable!(nodes[2]);
1690 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1691 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1692 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1693 let events = nodes[0].node.get_and_clear_pending_events();
1694 assert_eq!(events.len(), 2);
1696 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1697 assert_eq!(payment_preimage, *ev_preimage);
1698 assert_eq!(payment_hash, *ev_hash);
1699 assert_eq!(fee_paid_msat, &Some(1000));
1701 _ => panic!("Unexpected event")
1704 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1705 assert_eq!(hash, Some(payment_hash));
1707 _ => panic!("Unexpected event")
1709 } else if test == InterceptTest::Timeout {
1710 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
1711 connect_block(&nodes[0], &block);
1712 connect_block(&nodes[1], &block);
1713 for _ in 0..TEST_FINAL_CLTV {
1714 block.header.prev_blockhash = block.block_hash();
1715 connect_block(&nodes[0], &block);
1716 connect_block(&nodes[1], &block);
1718 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1719 check_added_monitors!(nodes[1], 1);
1720 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1721 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1722 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1723 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1724 assert!(htlc_timeout_updates.update_fee.is_none());
1726 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1727 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1728 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1730 // Check for unknown intercept id error.
1731 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1732 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();
1733 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1734 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1735 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1740 fn accept_underpaying_htlcs_config() {
1741 do_accept_underpaying_htlcs_config(1);
1742 do_accept_underpaying_htlcs_config(2);
1743 do_accept_underpaying_htlcs_config(3);
1746 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
1747 let chanmon_cfgs = create_chanmon_cfgs(3);
1748 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1749 let mut intercept_forwards_config = test_default_channel_config();
1750 intercept_forwards_config.accept_intercept_htlcs = true;
1751 let mut underpay_config = test_default_channel_config();
1752 underpay_config.channel_config.accept_underpaying_htlcs = true;
1753 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
1754 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1756 let mut chan_ids = Vec::new();
1757 for _ in 0..num_mpp_parts {
1758 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000, 0);
1759 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 2_000_000, 0).0.channel_id;
1760 chan_ids.push(channel_id);
1763 // Send the initial payment.
1764 let amt_msat = 900_000;
1765 let skimmed_fee_msat = 20;
1766 let mut route_hints = Vec::new();
1767 for _ in 0..num_mpp_parts {
1768 route_hints.push(RouteHint(vec![RouteHintHop {
1769 src_node_id: nodes[1].node.get_our_node_id(),
1770 short_channel_id: nodes[1].node.get_intercept_scid(),
1773 proportional_millionths: 0,
1775 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1776 htlc_minimum_msat: None,
1777 htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
1780 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1781 .with_route_hints(route_hints).unwrap()
1782 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1783 let route_params = RouteParameters {
1785 final_value_msat: amt_msat,
1787 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1788 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1789 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
1790 check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
1791 let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
1792 assert_eq!(events.len(), num_mpp_parts);
1794 // Forward the intercepted payments.
1795 for (idx, ev) in events.into_iter().enumerate() {
1796 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
1797 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
1799 let events = nodes[1].node.get_and_clear_pending_events();
1800 assert_eq!(events.len(), 1);
1801 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
1802 crate::events::Event::HTLCIntercepted {
1803 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
1805 assert_eq!(pmt_hash, payment_hash);
1806 (intercept_id, expected_outbound_amount_msat)
1810 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
1811 nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
1812 expect_pending_htlcs_forwardable!(nodes[1]);
1813 let payment_event = {
1815 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1816 assert_eq!(added_monitors.len(), 1);
1817 added_monitors.clear();
1819 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1820 assert_eq!(events.len(), 1);
1821 SendEvent::from_event(events.remove(0))
1823 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1824 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
1825 if idx == num_mpp_parts - 1 {
1826 expect_pending_htlcs_forwardable!(nodes[2]);
1830 // Claim the payment and check that the skimmed fee is as expected.
1831 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1832 let events = nodes[2].node.get_and_clear_pending_events();
1833 assert_eq!(events.len(), 1);
1835 crate::events::Event::PaymentClaimable {
1836 ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
1838 assert_eq!(payment_hash, payment_hash);
1839 assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
1840 assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
1841 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1843 crate::events::PaymentPurpose::InvoicePayment { payment_preimage: ev_payment_preimage,
1844 payment_secret: ev_payment_secret, .. } =>
1846 assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
1847 assert_eq!(payment_secret, *ev_payment_secret);
1852 _ => panic!("Unexpected event"),
1854 let mut expected_paths_vecs = Vec::new();
1855 let mut expected_paths = Vec::new();
1856 for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
1857 for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
1858 let total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
1859 &nodes[0], &expected_paths[..], &vec![skimmed_fee_msat as u32; num_mpp_parts][..], false,
1861 // The sender doesn't know that the penultimate hop took an extra fee.
1862 expect_payment_sent(&nodes[0], payment_preimage,
1863 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true);
1866 #[derive(PartialEq)]
1877 fn automatic_retries() {
1878 do_automatic_retries(AutoRetry::Success);
1879 do_automatic_retries(AutoRetry::Spontaneous);
1880 do_automatic_retries(AutoRetry::FailAttempts);
1881 do_automatic_retries(AutoRetry::FailTimeout);
1882 do_automatic_retries(AutoRetry::FailOnRestart);
1883 do_automatic_retries(AutoRetry::FailOnRetry);
1885 fn do_automatic_retries(test: AutoRetry) {
1886 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1888 let chanmon_cfgs = create_chanmon_cfgs(3);
1889 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1890 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1893 let new_chain_monitor;
1894 let node_0_deserialized;
1896 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1897 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1898 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1900 // Marshall data to send the payment
1901 #[cfg(feature = "std")]
1902 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1903 #[cfg(not(feature = "std"))]
1904 let payment_expiry_secs = 60 * 60;
1905 let amt_msat = 1000;
1906 let mut invoice_features = InvoiceFeatures::empty();
1907 invoice_features.set_variable_length_onion_required();
1908 invoice_features.set_payment_secret_required();
1909 invoice_features.set_basic_mpp_optional();
1910 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1911 .with_expiry_time(payment_expiry_secs as u64)
1912 .with_bolt11_features(invoice_features).unwrap();
1913 let route_params = RouteParameters {
1915 final_value_msat: amt_msat,
1917 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1919 macro_rules! pass_failed_attempt_with_retry_along_path {
1920 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1921 // Send a payment attempt that fails due to lack of liquidity on the second hop
1922 check_added_monitors!(nodes[0], 1);
1923 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1924 let mut update_add = update_0.update_add_htlcs[0].clone();
1925 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1926 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1927 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1928 nodes[1].node.process_pending_htlc_forwards();
1929 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1930 vec![HTLCDestination::NextHopChannel {
1931 node_id: Some(nodes[2].node.get_our_node_id()),
1932 channel_id: $failing_channel_id,
1934 nodes[1].node.process_pending_htlc_forwards();
1935 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1936 check_added_monitors!(&nodes[1], 1);
1937 assert!(update_1.update_fail_htlcs.len() == 1);
1938 let fail_msg = update_1.update_fail_htlcs[0].clone();
1939 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1940 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1942 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1943 let mut events = nodes[0].node.get_and_clear_pending_events();
1944 assert_eq!(events.len(), 2);
1946 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1947 assert_eq!(payment_hash, ev_payment_hash);
1948 assert_eq!(payment_failed_permanently, false);
1950 _ => panic!("Unexpected event"),
1952 if $expect_pending_htlcs_forwardable {
1954 Event::PendingHTLCsForwardable { .. } => {},
1955 _ => panic!("Unexpected event"),
1959 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1960 assert_eq!(payment_hash, ev_payment_hash);
1962 _ => panic!("Unexpected event"),
1968 if test == AutoRetry::Success {
1969 // Test that we can succeed on the first retry.
1970 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1971 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1972 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1974 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1975 // attempt, since the initial second hop channel will be excluded from pathfinding
1976 create_announced_chan_between_nodes(&nodes, 1, 2);
1978 // We retry payments in `process_pending_htlc_forwards`
1979 nodes[0].node.process_pending_htlc_forwards();
1980 check_added_monitors!(nodes[0], 1);
1981 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1982 assert_eq!(msg_events.len(), 1);
1983 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1984 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1985 } else if test == AutoRetry::Spontaneous {
1986 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
1987 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
1988 Retry::Attempts(1)).unwrap();
1989 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1991 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1992 // attempt, since the initial second hop channel will be excluded from pathfinding
1993 create_announced_chan_between_nodes(&nodes, 1, 2);
1995 // We retry payments in `process_pending_htlc_forwards`
1996 nodes[0].node.process_pending_htlc_forwards();
1997 check_added_monitors!(nodes[0], 1);
1998 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1999 assert_eq!(msg_events.len(), 1);
2000 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2001 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2002 } else if test == AutoRetry::FailAttempts {
2003 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2004 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2005 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2006 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2008 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2009 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2010 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2012 // We retry payments in `process_pending_htlc_forwards`
2013 nodes[0].node.process_pending_htlc_forwards();
2014 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2016 // Ensure we won't retry a second time.
2017 nodes[0].node.process_pending_htlc_forwards();
2018 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2019 assert_eq!(msg_events.len(), 0);
2020 } else if test == AutoRetry::FailTimeout {
2021 #[cfg(not(feature = "no-std"))] {
2022 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2023 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2024 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2025 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2027 // Advance the time so the second attempt fails due to timeout.
2028 SinceEpoch::advance(Duration::from_secs(61));
2030 // Make sure we don't retry again.
2031 nodes[0].node.process_pending_htlc_forwards();
2032 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2033 assert_eq!(msg_events.len(), 0);
2035 let mut events = nodes[0].node.get_and_clear_pending_events();
2036 assert_eq!(events.len(), 1);
2038 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2039 assert_eq!(payment_hash, *ev_payment_hash);
2040 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2041 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2043 _ => panic!("Unexpected event"),
2046 } else if test == AutoRetry::FailOnRestart {
2047 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2048 // attempts remaining prior to restart.
2049 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2050 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2051 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2053 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2054 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2055 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2057 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2058 nodes[0].node.process_pending_htlc_forwards();
2059 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2061 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2062 let node_encoded = nodes[0].node.encode();
2063 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2064 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2066 let mut events = nodes[0].node.get_and_clear_pending_events();
2067 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2068 // Make sure we don't retry again.
2069 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2070 assert_eq!(msg_events.len(), 0);
2072 let mut events = nodes[0].node.get_and_clear_pending_events();
2073 assert_eq!(events.len(), 1);
2075 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2076 assert_eq!(payment_hash, *ev_payment_hash);
2077 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2078 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2080 _ => panic!("Unexpected event"),
2082 } else if test == AutoRetry::FailOnRetry {
2083 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2084 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2085 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2087 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2088 // fail to find a route.
2089 nodes[0].node.process_pending_htlc_forwards();
2090 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2091 assert_eq!(msg_events.len(), 0);
2093 let mut events = nodes[0].node.get_and_clear_pending_events();
2094 assert_eq!(events.len(), 1);
2096 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2097 assert_eq!(payment_hash, *ev_payment_hash);
2098 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2099 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2101 _ => panic!("Unexpected event"),
2107 fn auto_retry_partial_failure() {
2108 // Test that we'll retry appropriately on send partial failure and retry partial failure.
2109 let chanmon_cfgs = create_chanmon_cfgs(2);
2110 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2111 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2112 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2114 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2115 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2116 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2118 // Marshall data to send the payment
2119 let amt_msat = 20_000;
2120 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2121 #[cfg(feature = "std")]
2122 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2123 #[cfg(not(feature = "std"))]
2124 let payment_expiry_secs = 60 * 60;
2125 let mut invoice_features = InvoiceFeatures::empty();
2126 invoice_features.set_variable_length_onion_required();
2127 invoice_features.set_payment_secret_required();
2128 invoice_features.set_basic_mpp_optional();
2129 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2130 .with_expiry_time(payment_expiry_secs as u64)
2131 .with_bolt11_features(invoice_features).unwrap();
2132 let route_params = RouteParameters {
2134 final_value_msat: amt_msat,
2137 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
2138 // second (for the initial send path2 over chan_2) fails.
2139 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2140 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2141 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
2142 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
2143 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2144 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2145 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2147 // Configure the initial send, retry1 and retry2's paths.
2148 let send_route = Route {
2150 Path { hops: vec![RouteHop {
2151 pubkey: nodes[1].node.get_our_node_id(),
2152 node_features: nodes[1].node.node_features(),
2153 short_channel_id: chan_1_id,
2154 channel_features: nodes[1].node.channel_features(),
2155 fee_msat: amt_msat / 2,
2156 cltv_expiry_delta: 100,
2157 }], blinded_tail: None },
2158 Path { hops: vec![RouteHop {
2159 pubkey: nodes[1].node.get_our_node_id(),
2160 node_features: nodes[1].node.node_features(),
2161 short_channel_id: chan_2_id,
2162 channel_features: nodes[1].node.channel_features(),
2163 fee_msat: amt_msat / 2,
2164 cltv_expiry_delta: 100,
2165 }], blinded_tail: None },
2167 payment_params: Some(route_params.payment_params.clone()),
2169 let retry_1_route = Route {
2171 Path { hops: vec![RouteHop {
2172 pubkey: nodes[1].node.get_our_node_id(),
2173 node_features: nodes[1].node.node_features(),
2174 short_channel_id: chan_1_id,
2175 channel_features: nodes[1].node.channel_features(),
2176 fee_msat: amt_msat / 4,
2177 cltv_expiry_delta: 100,
2178 }], blinded_tail: None },
2179 Path { hops: vec![RouteHop {
2180 pubkey: nodes[1].node.get_our_node_id(),
2181 node_features: nodes[1].node.node_features(),
2182 short_channel_id: chan_3_id,
2183 channel_features: nodes[1].node.channel_features(),
2184 fee_msat: amt_msat / 4,
2185 cltv_expiry_delta: 100,
2186 }], blinded_tail: None },
2188 payment_params: Some(route_params.payment_params.clone()),
2190 let retry_2_route = Route {
2192 Path { hops: vec![RouteHop {
2193 pubkey: nodes[1].node.get_our_node_id(),
2194 node_features: nodes[1].node.node_features(),
2195 short_channel_id: chan_1_id,
2196 channel_features: nodes[1].node.channel_features(),
2197 fee_msat: amt_msat / 4,
2198 cltv_expiry_delta: 100,
2199 }], blinded_tail: None },
2201 payment_params: Some(route_params.payment_params.clone()),
2203 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2204 let mut payment_params = route_params.payment_params.clone();
2205 payment_params.previously_failed_channels.push(chan_2_id);
2206 nodes[0].router.expect_find_route(RouteParameters {
2207 payment_params, final_value_msat: amt_msat / 2,
2208 }, Ok(retry_1_route));
2209 let mut payment_params = route_params.payment_params.clone();
2210 payment_params.previously_failed_channels.push(chan_3_id);
2211 nodes[0].router.expect_find_route(RouteParameters {
2212 payment_params, final_value_msat: amt_msat / 4,
2213 }, Ok(retry_2_route));
2215 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2216 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2217 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2218 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
2219 assert_eq!(closed_chan_events.len(), 4);
2220 match closed_chan_events[0] {
2221 Event::ChannelClosed { .. } => {},
2222 _ => panic!("Unexpected event"),
2224 match closed_chan_events[1] {
2225 Event::PaymentPathFailed { .. } => {},
2226 _ => panic!("Unexpected event"),
2228 match closed_chan_events[2] {
2229 Event::ChannelClosed { .. } => {},
2230 _ => panic!("Unexpected event"),
2232 match closed_chan_events[3] {
2233 Event::PaymentPathFailed { .. } => {},
2234 _ => panic!("Unexpected event"),
2237 // Pass the first part of the payment along the path.
2238 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
2239 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2241 // First message is the first update_add, remaining messages are broadcasting channel updates and
2242 // errors for the permfailed channels
2243 assert_eq!(msg_events.len(), 5);
2244 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2246 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2247 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2248 check_added_monitors!(nodes[1], 1);
2249 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2251 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2252 check_added_monitors!(nodes[0], 1);
2253 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2255 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2256 check_added_monitors!(nodes[0], 1);
2257 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2259 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2260 check_added_monitors!(nodes[1], 1);
2262 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2263 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2264 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2265 check_added_monitors!(nodes[1], 1);
2266 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2268 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2269 check_added_monitors!(nodes[0], 1);
2271 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2272 check_added_monitors!(nodes[0], 1);
2273 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2275 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2276 check_added_monitors!(nodes[1], 1);
2278 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2279 nodes[1].node.process_pending_htlc_forwards();
2280 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2281 nodes[1].node.claim_funds(payment_preimage);
2282 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2283 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2284 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2286 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2287 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2288 check_added_monitors!(nodes[0], 1);
2289 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2291 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2292 check_added_monitors!(nodes[1], 4);
2293 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2295 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2296 check_added_monitors!(nodes[1], 1);
2297 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2299 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2300 check_added_monitors!(nodes[0], 1);
2302 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2303 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2304 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2305 check_added_monitors!(nodes[0], 1);
2306 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2308 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2309 check_added_monitors!(nodes[1], 1);
2311 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2312 check_added_monitors!(nodes[1], 1);
2313 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2315 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2316 check_added_monitors!(nodes[0], 1);
2317 expect_payment_sent!(nodes[0], payment_preimage);
2321 fn auto_retry_zero_attempts_send_error() {
2322 let chanmon_cfgs = create_chanmon_cfgs(2);
2323 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2324 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2325 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2327 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2328 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2330 // Marshall data to send the payment
2331 let amt_msat = 20_000;
2332 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2333 #[cfg(feature = "std")]
2334 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2335 #[cfg(not(feature = "std"))]
2336 let payment_expiry_secs = 60 * 60;
2337 let mut invoice_features = InvoiceFeatures::empty();
2338 invoice_features.set_variable_length_onion_required();
2339 invoice_features.set_payment_secret_required();
2340 invoice_features.set_basic_mpp_optional();
2341 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2342 .with_expiry_time(payment_expiry_secs as u64)
2343 .with_bolt11_features(invoice_features).unwrap();
2344 let route_params = RouteParameters {
2346 final_value_msat: amt_msat,
2349 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2350 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2351 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2352 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2353 let events = nodes[0].node.get_and_clear_pending_events();
2354 assert_eq!(events.len(), 3);
2355 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2356 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2357 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2358 check_added_monitors!(nodes[0], 2);
2362 fn fails_paying_after_rejected_by_payee() {
2363 let chanmon_cfgs = create_chanmon_cfgs(2);
2364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2366 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2368 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2370 // Marshall data to send the payment
2371 let amt_msat = 20_000;
2372 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2373 #[cfg(feature = "std")]
2374 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2375 #[cfg(not(feature = "std"))]
2376 let payment_expiry_secs = 60 * 60;
2377 let mut invoice_features = InvoiceFeatures::empty();
2378 invoice_features.set_variable_length_onion_required();
2379 invoice_features.set_payment_secret_required();
2380 invoice_features.set_basic_mpp_optional();
2381 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2382 .with_expiry_time(payment_expiry_secs as u64)
2383 .with_bolt11_features(invoice_features).unwrap();
2384 let route_params = RouteParameters {
2386 final_value_msat: amt_msat,
2389 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2390 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2391 check_added_monitors!(nodes[0], 1);
2392 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2393 assert_eq!(events.len(), 1);
2394 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2395 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2396 check_added_monitors!(nodes[1], 0);
2397 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2398 expect_pending_htlcs_forwardable!(nodes[1]);
2399 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2401 nodes[1].node.fail_htlc_backwards(&payment_hash);
2402 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2403 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2407 fn retry_multi_path_single_failed_payment() {
2408 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2409 let chanmon_cfgs = create_chanmon_cfgs(2);
2410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2412 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2414 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2415 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2417 let amt_msat = 100_010_000;
2419 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2420 #[cfg(feature = "std")]
2421 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2422 #[cfg(not(feature = "std"))]
2423 let payment_expiry_secs = 60 * 60;
2424 let mut invoice_features = InvoiceFeatures::empty();
2425 invoice_features.set_variable_length_onion_required();
2426 invoice_features.set_payment_secret_required();
2427 invoice_features.set_basic_mpp_optional();
2428 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2429 .with_expiry_time(payment_expiry_secs as u64)
2430 .with_bolt11_features(invoice_features).unwrap();
2431 let route_params = RouteParameters {
2432 payment_params: payment_params.clone(),
2433 final_value_msat: amt_msat,
2436 let chans = nodes[0].node.list_usable_channels();
2437 let mut route = Route {
2439 Path { hops: vec![RouteHop {
2440 pubkey: nodes[1].node.get_our_node_id(),
2441 node_features: nodes[1].node.node_features(),
2442 short_channel_id: chans[0].short_channel_id.unwrap(),
2443 channel_features: nodes[1].node.channel_features(),
2445 cltv_expiry_delta: 100,
2446 }], blinded_tail: None },
2447 Path { hops: vec![RouteHop {
2448 pubkey: nodes[1].node.get_our_node_id(),
2449 node_features: nodes[1].node.node_features(),
2450 short_channel_id: chans[1].short_channel_id.unwrap(),
2451 channel_features: nodes[1].node.channel_features(),
2452 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2453 cltv_expiry_delta: 100,
2454 }], blinded_tail: None },
2456 payment_params: Some(payment_params),
2458 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2459 // On retry, split the payment across both channels.
2460 route.paths[0].hops[0].fee_msat = 50_000_001;
2461 route.paths[1].hops[0].fee_msat = 50_000_000;
2462 let mut pay_params = route.payment_params.clone().unwrap();
2463 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2464 nodes[0].router.expect_find_route(RouteParameters {
2465 payment_params: pay_params,
2466 // Note that the second request here requests the amount we originally failed to send,
2467 // not the amount remaining on the full payment, which should be changed.
2468 final_value_msat: 100_000_001,
2469 }, Ok(route.clone()));
2472 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2473 // The initial send attempt, 2 paths
2474 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2475 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2476 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2477 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2478 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2481 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2482 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2483 let events = nodes[0].node.get_and_clear_pending_events();
2484 assert_eq!(events.len(), 1);
2486 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2487 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2488 short_channel_id: Some(expected_scid), .. } =>
2490 assert_eq!(payment_hash, ev_payment_hash);
2491 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2493 _ => panic!("Unexpected event"),
2495 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2496 assert_eq!(htlc_msgs.len(), 2);
2497 check_added_monitors!(nodes[0], 2);
2501 fn immediate_retry_on_failure() {
2502 // Tests that we can/will retry immediately after a failure
2503 let chanmon_cfgs = create_chanmon_cfgs(2);
2504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2506 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2508 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2509 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2511 let amt_msat = 100_000_001;
2512 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2513 #[cfg(feature = "std")]
2514 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2515 #[cfg(not(feature = "std"))]
2516 let payment_expiry_secs = 60 * 60;
2517 let mut invoice_features = InvoiceFeatures::empty();
2518 invoice_features.set_variable_length_onion_required();
2519 invoice_features.set_payment_secret_required();
2520 invoice_features.set_basic_mpp_optional();
2521 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2522 .with_expiry_time(payment_expiry_secs as u64)
2523 .with_bolt11_features(invoice_features).unwrap();
2524 let route_params = RouteParameters {
2526 final_value_msat: amt_msat,
2529 let chans = nodes[0].node.list_usable_channels();
2530 let mut route = Route {
2532 Path { hops: vec![RouteHop {
2533 pubkey: nodes[1].node.get_our_node_id(),
2534 node_features: nodes[1].node.node_features(),
2535 short_channel_id: chans[0].short_channel_id.unwrap(),
2536 channel_features: nodes[1].node.channel_features(),
2537 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2538 cltv_expiry_delta: 100,
2539 }], blinded_tail: None },
2541 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2543 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2544 // On retry, split the payment across both channels.
2545 route.paths.push(route.paths[0].clone());
2546 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2547 route.paths[0].hops[0].fee_msat = 50_000_000;
2548 route.paths[1].hops[0].fee_msat = 50_000_001;
2549 let mut pay_params = route_params.payment_params.clone();
2550 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2551 nodes[0].router.expect_find_route(RouteParameters {
2552 payment_params: pay_params, final_value_msat: amt_msat,
2553 }, Ok(route.clone()));
2555 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2556 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2557 let events = nodes[0].node.get_and_clear_pending_events();
2558 assert_eq!(events.len(), 1);
2560 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2561 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2562 short_channel_id: Some(expected_scid), .. } =>
2564 assert_eq!(payment_hash, ev_payment_hash);
2565 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2567 _ => panic!("Unexpected event"),
2569 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2570 assert_eq!(htlc_msgs.len(), 2);
2571 check_added_monitors!(nodes[0], 2);
2575 fn no_extra_retries_on_back_to_back_fail() {
2576 // In a previous release, we had a race where we may exceed the payment retry count if we
2577 // get two failures in a row with the second indicating that all paths had failed (this field,
2578 // `all_paths_failed`, has since been removed).
2579 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2580 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2581 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2582 // pending which we will see later. Thus, when we previously removed the retry tracking map
2583 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2584 // retry entry even though more events for the same payment were still pending. This led to
2585 // us retrying a payment again even though we'd already given up on it.
2587 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2588 // is used to remove the payment retry counter entries instead. This tests for the specific
2589 // excess-retry case while also testing `PaymentFailed` generation.
2591 let chanmon_cfgs = create_chanmon_cfgs(3);
2592 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2593 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2594 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2596 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2597 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2599 let amt_msat = 200_000_000;
2600 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2601 #[cfg(feature = "std")]
2602 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2603 #[cfg(not(feature = "std"))]
2604 let payment_expiry_secs = 60 * 60;
2605 let mut invoice_features = InvoiceFeatures::empty();
2606 invoice_features.set_variable_length_onion_required();
2607 invoice_features.set_payment_secret_required();
2608 invoice_features.set_basic_mpp_optional();
2609 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2610 .with_expiry_time(payment_expiry_secs as u64)
2611 .with_bolt11_features(invoice_features).unwrap();
2612 let route_params = RouteParameters {
2614 final_value_msat: amt_msat,
2617 let mut route = Route {
2619 Path { hops: vec![RouteHop {
2620 pubkey: nodes[1].node.get_our_node_id(),
2621 node_features: nodes[1].node.node_features(),
2622 short_channel_id: chan_1_scid,
2623 channel_features: nodes[1].node.channel_features(),
2624 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2625 cltv_expiry_delta: 100,
2627 pubkey: nodes[2].node.get_our_node_id(),
2628 node_features: nodes[2].node.node_features(),
2629 short_channel_id: chan_2_scid,
2630 channel_features: nodes[2].node.channel_features(),
2631 fee_msat: 100_000_000,
2632 cltv_expiry_delta: 100,
2633 }], blinded_tail: None },
2634 Path { hops: vec![RouteHop {
2635 pubkey: nodes[1].node.get_our_node_id(),
2636 node_features: nodes[1].node.node_features(),
2637 short_channel_id: chan_1_scid,
2638 channel_features: nodes[1].node.channel_features(),
2639 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2640 cltv_expiry_delta: 100,
2642 pubkey: nodes[2].node.get_our_node_id(),
2643 node_features: nodes[2].node.node_features(),
2644 short_channel_id: chan_2_scid,
2645 channel_features: nodes[2].node.channel_features(),
2646 fee_msat: 100_000_000,
2647 cltv_expiry_delta: 100,
2648 }], blinded_tail: None }
2650 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2652 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2653 let mut second_payment_params = route_params.payment_params.clone();
2654 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2655 // On retry, we'll only return one path
2656 route.paths.remove(1);
2657 route.paths[0].hops[1].fee_msat = amt_msat;
2658 nodes[0].router.expect_find_route(RouteParameters {
2659 payment_params: second_payment_params,
2660 final_value_msat: amt_msat,
2661 }, Ok(route.clone()));
2663 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2664 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2665 let htlc_updates = SendEvent::from_node(&nodes[0]);
2666 check_added_monitors!(nodes[0], 1);
2667 assert_eq!(htlc_updates.msgs.len(), 1);
2669 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2670 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2671 check_added_monitors!(nodes[1], 1);
2672 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2674 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2675 check_added_monitors!(nodes[0], 1);
2676 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2678 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2679 check_added_monitors!(nodes[0], 1);
2680 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2682 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2683 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2684 check_added_monitors!(nodes[1], 1);
2685 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2687 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2688 check_added_monitors!(nodes[1], 1);
2689 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2691 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2692 check_added_monitors!(nodes[0], 1);
2694 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2695 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2696 check_added_monitors!(nodes[0], 1);
2697 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2699 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2700 check_added_monitors!(nodes[1], 1);
2701 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2703 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2704 check_added_monitors!(nodes[1], 1);
2705 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2707 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2708 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2709 check_added_monitors!(nodes[0], 1);
2711 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2712 check_added_monitors!(nodes[0], 1);
2713 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2715 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2716 check_added_monitors!(nodes[1], 1);
2717 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2718 check_added_monitors!(nodes[1], 1);
2719 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2721 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2722 check_added_monitors!(nodes[0], 1);
2724 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2725 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2728 // Previously, we retried payments in an event consumer, which would retry each
2729 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2730 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2731 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2732 // by adding the `PaymentFailed` event.
2734 // Because we now retry payments as a batch, we simply return a single-path route in the
2735 // second, batched, request, have that fail, ensure the payment was abandoned.
2736 let mut events = nodes[0].node.get_and_clear_pending_events();
2737 assert_eq!(events.len(), 3);
2739 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2740 assert_eq!(payment_hash, ev_payment_hash);
2741 assert_eq!(payment_failed_permanently, false);
2743 _ => panic!("Unexpected event"),
2746 Event::PendingHTLCsForwardable { .. } => {},
2747 _ => panic!("Unexpected event"),
2750 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2751 assert_eq!(payment_hash, ev_payment_hash);
2752 assert_eq!(payment_failed_permanently, false);
2754 _ => panic!("Unexpected event"),
2757 nodes[0].node.process_pending_htlc_forwards();
2758 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2759 check_added_monitors!(nodes[0], 1);
2761 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2762 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2763 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2764 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2765 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2767 let mut events = nodes[0].node.get_and_clear_pending_events();
2768 assert_eq!(events.len(), 2);
2770 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2771 assert_eq!(payment_hash, ev_payment_hash);
2772 assert_eq!(payment_failed_permanently, false);
2774 _ => panic!("Unexpected event"),
2777 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2778 assert_eq!(payment_hash, *ev_payment_hash);
2779 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2780 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2782 _ => panic!("Unexpected event"),
2787 fn test_simple_partial_retry() {
2788 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2789 // full amount of the payment, rather than only the missing amount. Here we simply test for
2790 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2791 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2793 let chanmon_cfgs = create_chanmon_cfgs(3);
2794 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2795 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2796 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2798 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2799 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2801 let amt_msat = 200_000_000;
2802 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2803 #[cfg(feature = "std")]
2804 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2805 #[cfg(not(feature = "std"))]
2806 let payment_expiry_secs = 60 * 60;
2807 let mut invoice_features = InvoiceFeatures::empty();
2808 invoice_features.set_variable_length_onion_required();
2809 invoice_features.set_payment_secret_required();
2810 invoice_features.set_basic_mpp_optional();
2811 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2812 .with_expiry_time(payment_expiry_secs as u64)
2813 .with_bolt11_features(invoice_features).unwrap();
2814 let route_params = RouteParameters {
2816 final_value_msat: amt_msat,
2819 let mut route = Route {
2821 Path { hops: vec![RouteHop {
2822 pubkey: nodes[1].node.get_our_node_id(),
2823 node_features: nodes[1].node.node_features(),
2824 short_channel_id: chan_1_scid,
2825 channel_features: nodes[1].node.channel_features(),
2826 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2827 cltv_expiry_delta: 100,
2829 pubkey: nodes[2].node.get_our_node_id(),
2830 node_features: nodes[2].node.node_features(),
2831 short_channel_id: chan_2_scid,
2832 channel_features: nodes[2].node.channel_features(),
2833 fee_msat: 100_000_000,
2834 cltv_expiry_delta: 100,
2835 }], blinded_tail: None },
2836 Path { hops: vec![RouteHop {
2837 pubkey: nodes[1].node.get_our_node_id(),
2838 node_features: nodes[1].node.node_features(),
2839 short_channel_id: chan_1_scid,
2840 channel_features: nodes[1].node.channel_features(),
2842 cltv_expiry_delta: 100,
2844 pubkey: nodes[2].node.get_our_node_id(),
2845 node_features: nodes[2].node.node_features(),
2846 short_channel_id: chan_2_scid,
2847 channel_features: nodes[2].node.channel_features(),
2848 fee_msat: 100_000_000,
2849 cltv_expiry_delta: 100,
2850 }], blinded_tail: None }
2852 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2854 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2855 let mut second_payment_params = route_params.payment_params.clone();
2856 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2857 // On retry, we'll only be asked for one path (or 100k sats)
2858 route.paths.remove(0);
2859 nodes[0].router.expect_find_route(RouteParameters {
2860 payment_params: second_payment_params,
2861 final_value_msat: amt_msat / 2,
2862 }, Ok(route.clone()));
2864 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2865 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2866 let htlc_updates = SendEvent::from_node(&nodes[0]);
2867 check_added_monitors!(nodes[0], 1);
2868 assert_eq!(htlc_updates.msgs.len(), 1);
2870 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2871 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2872 check_added_monitors!(nodes[1], 1);
2873 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2875 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2876 check_added_monitors!(nodes[0], 1);
2877 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2879 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2880 check_added_monitors!(nodes[0], 1);
2881 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2883 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2884 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2885 check_added_monitors!(nodes[1], 1);
2886 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2888 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2889 check_added_monitors!(nodes[1], 1);
2890 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2892 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2893 check_added_monitors!(nodes[0], 1);
2895 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2896 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2897 check_added_monitors!(nodes[0], 1);
2898 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2900 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2901 check_added_monitors!(nodes[1], 1);
2903 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2904 check_added_monitors!(nodes[1], 1);
2906 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2908 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2909 check_added_monitors!(nodes[0], 1);
2911 let mut events = nodes[0].node.get_and_clear_pending_events();
2912 assert_eq!(events.len(), 2);
2914 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2915 assert_eq!(payment_hash, ev_payment_hash);
2916 assert_eq!(payment_failed_permanently, false);
2918 _ => panic!("Unexpected event"),
2921 Event::PendingHTLCsForwardable { .. } => {},
2922 _ => panic!("Unexpected event"),
2925 nodes[0].node.process_pending_htlc_forwards();
2926 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2927 check_added_monitors!(nodes[0], 1);
2929 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2930 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2932 expect_pending_htlcs_forwardable!(nodes[1]);
2933 check_added_monitors!(nodes[1], 1);
2935 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2936 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2937 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2938 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2940 expect_pending_htlcs_forwardable!(nodes[2]);
2941 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2945 #[cfg(feature = "std")]
2946 fn test_threaded_payment_retries() {
2947 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2948 // a single thread and would happily let multiple threads run retries at the same time. Because
2949 // retries are done by first calculating the amount we need to retry, then dropping the
2950 // relevant lock, then actually sending, we would happily let multiple threads retry the same
2951 // amount at the same time, overpaying our original HTLC!
2952 let chanmon_cfgs = create_chanmon_cfgs(4);
2953 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2954 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2955 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2957 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2958 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2959 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2960 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2962 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2963 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2964 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2965 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2967 let amt_msat = 100_000_000;
2968 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2969 #[cfg(feature = "std")]
2970 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2971 #[cfg(not(feature = "std"))]
2972 let payment_expiry_secs = 60 * 60;
2973 let mut invoice_features = InvoiceFeatures::empty();
2974 invoice_features.set_variable_length_onion_required();
2975 invoice_features.set_payment_secret_required();
2976 invoice_features.set_basic_mpp_optional();
2977 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2978 .with_expiry_time(payment_expiry_secs as u64)
2979 .with_bolt11_features(invoice_features).unwrap();
2980 let mut route_params = RouteParameters {
2982 final_value_msat: amt_msat,
2985 let mut route = Route {
2987 Path { hops: vec![RouteHop {
2988 pubkey: nodes[1].node.get_our_node_id(),
2989 node_features: nodes[1].node.node_features(),
2990 short_channel_id: chan_1_scid,
2991 channel_features: nodes[1].node.channel_features(),
2993 cltv_expiry_delta: 100,
2995 pubkey: nodes[3].node.get_our_node_id(),
2996 node_features: nodes[2].node.node_features(),
2997 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2998 channel_features: nodes[2].node.channel_features(),
2999 fee_msat: amt_msat / 1000,
3000 cltv_expiry_delta: 100,
3001 }], blinded_tail: None },
3002 Path { hops: vec![RouteHop {
3003 pubkey: nodes[2].node.get_our_node_id(),
3004 node_features: nodes[2].node.node_features(),
3005 short_channel_id: chan_3_scid,
3006 channel_features: nodes[2].node.channel_features(),
3008 cltv_expiry_delta: 100,
3010 pubkey: nodes[3].node.get_our_node_id(),
3011 node_features: nodes[3].node.node_features(),
3012 short_channel_id: chan_4_scid,
3013 channel_features: nodes[3].node.channel_features(),
3014 fee_msat: amt_msat - amt_msat / 1000,
3015 cltv_expiry_delta: 100,
3016 }], blinded_tail: None }
3018 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
3020 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3022 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3023 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3024 check_added_monitors!(nodes[0], 2);
3025 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3026 assert_eq!(send_msg_events.len(), 2);
3027 send_msg_events.retain(|msg|
3028 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3029 // Drop the commitment update for nodes[2], we can just let that one sit pending
3031 *node_id == nodes[1].node.get_our_node_id()
3032 } else { panic!(); }
3035 // from here on out, the retry `RouteParameters` amount will be amt/1000
3036 route_params.final_value_msat /= 1000;
3039 let end_time = Instant::now() + Duration::from_secs(1);
3040 macro_rules! thread_body { () => { {
3041 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3042 let node_ref = NodePtr::from_node(&nodes[0]);
3044 let node_a = unsafe { &*node_ref.0 };
3045 while Instant::now() < end_time {
3046 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3047 // Ignore if we have any pending events, just always pretend we just got a
3048 // PendingHTLCsForwardable
3049 node_a.node.process_pending_htlc_forwards();
3053 let mut threads = Vec::new();
3054 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3056 // Back in the main thread, poll pending messages and make sure that we never have more than
3057 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3058 // there are HTLC messages shoved in while its running. This allows us to test that we never
3059 // generate an additional update_add_htlc until we've fully failed the first.
3060 let mut previously_failed_channels = Vec::new();
3062 assert_eq!(send_msg_events.len(), 1);
3063 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3064 assert_eq!(send_event.msgs.len(), 1);
3066 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3067 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3069 // Note that we only push one route into `expect_find_route` at a time, because that's all
3070 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3071 // we should still ultimately fail for the same reason - because we're trying to send too
3072 // many HTLCs at once.
3073 let mut new_route_params = route_params.clone();
3074 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3075 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3076 route.paths[0].hops[1].short_channel_id += 1;
3077 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3079 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3080 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3081 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3082 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3083 // This races with our other threads which may generate an add-HTLCs commitment update via
3084 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3085 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3086 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3087 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3089 let cur_time = Instant::now();
3090 if cur_time > end_time {
3091 for thread in threads.drain(..) { thread.join().unwrap(); }
3094 // Make sure we have some events to handle when we go around...
3095 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3096 nodes[0].node.process_pending_htlc_forwards();
3097 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3098 check_added_monitors!(nodes[0], 2);
3100 if cur_time > end_time {
3106 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
3107 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3108 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3109 // it was last persisted.
3110 let chanmon_cfgs = create_chanmon_cfgs(2);
3111 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3112 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3113 let (persister_a, persister_b, persister_c);
3114 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3115 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3116 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3118 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3120 let mut nodes_0_serialized = Vec::new();
3121 if !persist_manager_with_payment {
3122 nodes_0_serialized = nodes[0].node.encode();
3125 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3127 if persist_manager_with_payment {
3128 nodes_0_serialized = nodes[0].node.encode();
3131 nodes[1].node.claim_funds(our_payment_preimage);
3132 check_added_monitors!(nodes[1], 1);
3133 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3135 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3136 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3137 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3138 check_added_monitors!(nodes[0], 1);
3140 // The ChannelMonitor should always be the latest version, as we're required to persist it
3141 // during the commitment signed handling.
3142 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3143 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3145 let events = nodes[0].node.get_and_clear_pending_events();
3146 assert_eq!(events.len(), 2);
3147 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3148 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3149 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3150 // the double-claim that would otherwise appear at the end of this test.
3151 nodes[0].node.timer_tick_occurred();
3152 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3153 assert_eq!(as_broadcasted_txn.len(), 1);
3155 // Ensure that, even after some time, if we restart we still include *something* in the current
3156 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3157 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3158 // A naive implementation of the fix here would wipe the pending payments set, causing a
3159 // failure event when we restart.
3160 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3162 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3163 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);
3164 let events = nodes[0].node.get_and_clear_pending_events();
3165 assert!(events.is_empty());
3167 // Ensure that we don't generate any further events even after the channel-closing commitment
3168 // transaction is confirmed on-chain.
3169 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3170 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3172 let events = nodes[0].node.get_and_clear_pending_events();
3173 assert!(events.is_empty());
3175 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3176 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);
3177 let events = nodes[0].node.get_and_clear_pending_events();
3178 assert!(events.is_empty());
3179 check_added_monitors(&nodes[0], 1);
3183 fn no_missing_sent_on_midpoint_reload() {
3184 do_no_missing_sent_on_midpoint_reload(false);
3185 do_no_missing_sent_on_midpoint_reload(true);
3188 fn do_claim_from_closed_chan(fail_payment: bool) {
3189 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3190 // received had been closed between when the HTLC was received and when we went to claim it.
3191 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3192 // presumably the sender may retry later. Long ago it also reduced total code in the claim
3195 // However, this doesn't make sense if you're trying to do an atomic swap or some other
3196 // protocol that requires atomicity with some other action - if your money got claimed
3197 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3198 // is an over-optimization - there should be a very, very low likelihood that a channel closes
3199 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3200 // Since we now have code to handle this anyway we should allow it.
3202 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3203 // CLTVs on the paths to different value resulting in a different claim deadline.
3204 let chanmon_cfgs = create_chanmon_cfgs(4);
3205 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3206 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3207 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3209 create_announced_chan_between_nodes(&nodes, 0, 1);
3210 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3211 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3212 create_announced_chan_between_nodes(&nodes, 2, 3);
3214 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3215 let mut route_params = RouteParameters {
3216 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3217 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
3218 final_value_msat: 10_000_000,
3220 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3221 None, &nodes[0].node.compute_inflight_htlcs()).unwrap();
3222 // Make sure the route is ordered as the B->D path before C->D
3223 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3224 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3226 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3227 // the HTLC is being relayed.
3228 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3229 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3230 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3232 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3233 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3234 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3235 check_added_monitors(&nodes[0], 2);
3236 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3237 send_msgs.sort_by(|a, _| {
3239 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3240 let node_b_id = nodes[1].node.get_our_node_id();
3241 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3244 assert_eq!(send_msgs.len(), 2);
3245 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3246 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3247 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3248 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3250 match receive_event.unwrap() {
3251 Event::PaymentClaimable { claim_deadline, .. } => {
3252 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3257 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3259 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3260 - if fail_payment { 0 } else { 2 });
3262 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3263 // and expire both immediately, though, by connecting another 4 blocks.
3264 let reason = HTLCDestination::FailedPayment { payment_hash };
3265 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3266 connect_blocks(&nodes[3], 4);
3267 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3268 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3270 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3271 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false);
3272 check_closed_broadcast(&nodes[1], 1, true);
3273 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3274 assert_eq!(bs_tx.len(), 1);
3276 mine_transaction(&nodes[3], &bs_tx[0]);
3277 check_added_monitors(&nodes[3], 1);
3278 check_closed_broadcast(&nodes[3], 1, true);
3279 check_closed_event(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false);
3281 nodes[3].node.claim_funds(payment_preimage);
3282 check_added_monitors(&nodes[3], 2);
3283 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3285 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3286 assert_eq!(ds_tx.len(), 1);
3287 check_spends!(&ds_tx[0], &bs_tx[0]);
3289 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3290 check_added_monitors(&nodes[1], 1);
3291 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3293 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3294 check_added_monitors(&nodes[1], 1);
3295 assert_eq!(bs_claims.len(), 1);
3296 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3297 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3298 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3299 } else { panic!(); }
3301 expect_payment_sent!(nodes[0], payment_preimage);
3303 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3304 assert_eq!(ds_claim_msgs.len(), 1);
3305 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3306 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3307 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3308 check_added_monitors(&nodes[2], 1);
3309 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3310 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3312 } else { panic!(); };
3314 assert_eq!(cs_claim_msgs.len(), 1);
3315 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3316 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3317 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3318 } else { panic!(); }
3320 expect_payment_path_successful!(nodes[0]);
3325 fn claim_from_closed_chan() {
3326 do_claim_from_closed_chan(true);
3327 do_claim_from_closed_chan(false);
3330 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3331 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3332 // another results in the HTLC being rejected.
3334 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3335 // first of which we'll deliver and the second of which we'll fail and then re-send with
3336 // modified payment metadata, which will in turn result in it being failed by the recipient.
3337 let chanmon_cfgs = create_chanmon_cfgs(4);
3338 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3339 let mut config = test_default_channel_config();
3340 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3341 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3344 let new_chain_monitor;
3345 let nodes_0_deserialized;
3347 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3349 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3350 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3351 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3352 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3354 // Pay more than half of each channel's max, requiring MPP
3355 let amt_msat = 750_000_000;
3356 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3357 let payment_id = PaymentId(payment_hash.0);
3358 let payment_metadata = vec![44, 49, 52, 142];
3360 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3361 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3362 let mut route_params = RouteParameters {
3364 final_value_msat: amt_msat,
3367 // Send the MPP payment, delivering the updated commitment state to nodes[1].
3368 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3369 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata),
3370 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3371 check_added_monitors!(nodes[0], 2);
3373 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3374 assert_eq!(send_events.len(), 2);
3375 let first_send = SendEvent::from_event(send_events.pop().unwrap());
3376 let second_send = SendEvent::from_event(send_events.pop().unwrap());
3378 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3379 (&first_send, &second_send)
3381 (&second_send, &first_send)
3383 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3384 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3386 expect_pending_htlcs_forwardable!(nodes[1]);
3387 check_added_monitors(&nodes[1], 1);
3388 let b_forward_ev = SendEvent::from_node(&nodes[1]);
3389 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3390 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3392 expect_pending_htlcs_forwardable!(nodes[3]);
3394 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3395 // will result in nodes[2] failing the HTLC back.
3396 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3397 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3399 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3400 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3402 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3403 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3404 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3406 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3407 assert_eq!(payment_fail_retryable_evs.len(), 2);
3408 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3409 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3411 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3412 // stored for our payment.
3414 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3417 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3418 // the payment state.
3420 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3421 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3422 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3423 persister, new_chain_monitor, nodes_0_deserialized);
3424 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3425 reconnect_nodes(&nodes[1], &nodes[3], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3427 reconnect_nodes(&nodes[2], &nodes[3], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3429 // Create a new channel between C and D as A will refuse to retry on the existing one because
3431 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3433 // Now retry the failed HTLC.
3434 nodes[0].node.process_pending_htlc_forwards();
3435 check_added_monitors(&nodes[0], 1);
3436 let as_resend = SendEvent::from_node(&nodes[0]);
3437 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3438 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3440 expect_pending_htlcs_forwardable!(nodes[2]);
3441 check_added_monitors(&nodes[2], 1);
3442 let cs_forward = SendEvent::from_node(&nodes[2]);
3443 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3444 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3446 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3447 // the payment metadata was modified, failing only the one modified HTLC and retaining the
3450 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3451 nodes[3].node.process_pending_htlc_forwards();
3452 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3453 &[HTLCDestination::FailedPayment {payment_hash}]);
3454 nodes[3].node.process_pending_htlc_forwards();
3456 check_added_monitors(&nodes[3], 1);
3457 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3459 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3460 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3461 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3462 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3464 expect_pending_htlcs_forwardable!(nodes[3]);
3465 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3466 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3471 fn test_payment_metadata_consistency() {
3472 do_test_payment_metadata_consistency(true, true);
3473 do_test_payment_metadata_consistency(true, false);
3474 do_test_payment_metadata_consistency(false, true);
3475 do_test_payment_metadata_consistency(false, false);