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::Bolt11InvoiceFeatures;
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(ReconnectArgs::new(&nodes[1], &nodes[2]));
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, [nodes[1].node.get_our_node_id()], 100000);
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 {}",
541 &nodes[1].node.get_our_node_id())) }, [nodes[0].node.get_our_node_id()], 100000);
542 check_added_monitors!(nodes[1], 1);
543 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
545 _ => panic!("Unexpected event"),
547 check_closed_broadcast!(nodes[1], false);
549 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
550 // we close in a moment.
551 nodes[2].node.claim_funds(payment_preimage_1);
552 check_added_monitors!(nodes[2], 1);
553 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
555 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
556 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
557 check_added_monitors!(nodes[1], 1);
558 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
559 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
561 if confirm_before_reload {
562 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
563 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
566 // Create a new channel on which to retry the payment before we fail the payment via the
567 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
568 // connecting several blocks while creating the channel (implying time has passed).
569 create_announced_chan_between_nodes(&nodes, 0, 1);
570 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
572 mine_transaction(&nodes[1], &as_commitment_tx);
573 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
574 assert_eq!(bs_htlc_claim_txn.len(), 1);
575 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
577 if !confirm_before_reload {
578 mine_transaction(&nodes[0], &as_commitment_tx);
580 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
581 expect_payment_sent!(nodes[0], payment_preimage_1);
582 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
583 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
584 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
585 assert_eq!(txn.len(), 2);
586 (txn.remove(0), txn.remove(0))
588 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
589 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
590 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
591 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
593 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
595 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
596 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
598 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
599 // reloaded) via a route over the new channel, which work without issue and eventually be
600 // received and claimed at the recipient just like any other payment.
601 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
603 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
604 // and not the original fee. We also update node[1]'s relevant config as
605 // do_claim_payment_along_route expects us to never overpay.
607 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
608 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
609 .unwrap().lock().unwrap();
610 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
611 let mut new_config = channel.context.config();
612 new_config.forwarding_fee_base_msat += 100_000;
613 channel.context.update_config(&new_config);
614 new_route.paths[0].hops[0].fee_msat += 100_000;
617 // Force expiration of the channel's previous config.
618 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
619 nodes[1].node.timer_tick_occurred();
622 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
623 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
624 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
625 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
626 check_added_monitors!(nodes[0], 1);
627 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
628 assert_eq!(events.len(), 1);
629 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
630 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
631 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
635 fn retry_with_no_persist() {
636 do_retry_with_no_persist(true);
637 do_retry_with_no_persist(false);
640 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
641 // Test that an off-chain completed payment is not retryable on restart. This was previously
642 // broken for dust payments, but we test for both dust and non-dust payments.
644 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
646 let chanmon_cfgs = create_chanmon_cfgs(3);
647 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
649 let mut manually_accept_config = test_default_channel_config();
650 manually_accept_config.manually_accept_inbound_channels = true;
652 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
654 let first_persister: test_utils::TestPersister;
655 let first_new_chain_monitor: test_utils::TestChainMonitor;
656 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>;
657 let second_persister: test_utils::TestPersister;
658 let second_new_chain_monitor: test_utils::TestChainMonitor;
659 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>;
660 let third_persister: test_utils::TestPersister;
661 let third_new_chain_monitor: test_utils::TestChainMonitor;
662 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>;
664 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
666 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
667 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
668 confirm_transaction(&nodes[0], &funding_tx);
669 confirm_transaction(&nodes[1], &funding_tx);
670 // Ignore the announcement_signatures messages
671 nodes[0].node.get_and_clear_pending_msg_events();
672 nodes[1].node.get_and_clear_pending_msg_events();
673 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
675 // Serialize the ChannelManager prior to sending payments
676 let mut nodes_0_serialized = nodes[0].node.encode();
678 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
679 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 });
681 // The ChannelMonitor should always be the latest version, as we're required to persist it
682 // during the `commitment_signed_dance!()`.
683 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
685 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);
686 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
688 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
689 // force-close the channel.
690 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
691 nodes[0].node.timer_tick_occurred();
692 assert!(nodes[0].node.list_channels().is_empty());
693 assert!(nodes[0].node.has_pending_payments());
694 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
695 check_added_monitors!(nodes[0], 1);
697 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
698 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
700 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
702 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
703 // error, as the channel has hit the chain.
704 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
705 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
707 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
708 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
709 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
710 assert_eq!(as_err.len(), 1);
711 let bs_commitment_tx;
713 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
714 assert_eq!(node_id, nodes[1].node.get_our_node_id());
715 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
716 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())) }
717 , [nodes[0].node.get_our_node_id()], 100000);
718 check_added_monitors!(nodes[1], 1);
719 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
721 _ => panic!("Unexpected event"),
723 check_closed_broadcast!(nodes[1], false);
725 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
726 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
727 // incoming HTLCs with the same payment hash later.
728 nodes[2].node.fail_htlc_backwards(&payment_hash);
729 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
730 check_added_monitors!(nodes[2], 1);
732 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
733 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
734 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
735 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
736 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
738 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
739 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
740 // after the commitment transaction, so always connect the commitment transaction.
741 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
742 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
744 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
745 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
746 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
747 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
748 assert_eq!(as_htlc_timeout.len(), 1);
750 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
751 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
752 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
753 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
756 // Create a new channel on which to retry the payment before we fail the payment via the
757 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
758 // connecting several blocks while creating the channel (implying time has passed).
759 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
760 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
761 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
763 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
764 // confirming, we will fail as it's considered still-pending...
765 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
766 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
767 Err(PaymentSendFailure::DuplicatePayment) => {},
768 _ => panic!("Unexpected error")
770 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
772 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
773 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
774 // (which should also still work).
775 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
776 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
777 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
779 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
780 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
781 nodes_0_serialized = nodes[0].node.encode();
783 // After the payment failed, we're free to send it again.
784 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
785 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
786 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
788 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);
789 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
791 nodes[0].node.test_process_background_events();
792 check_added_monitors(&nodes[0], 1);
794 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
795 reconnect_args.send_channel_ready = (true, true);
796 reconnect_nodes(reconnect_args);
798 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
799 // the payment is not (spuriously) listed as still pending.
800 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
801 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
802 check_added_monitors!(nodes[0], 1);
803 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
804 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
806 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
807 Err(PaymentSendFailure::DuplicatePayment) => {},
808 _ => panic!("Unexpected error")
810 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
812 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
813 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
814 nodes_0_serialized = nodes[0].node.encode();
816 // Check that after reload we can send the payment again (though we shouldn't, since it was
817 // claimed previously).
818 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);
819 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
821 nodes[0].node.test_process_background_events();
822 check_added_monitors(&nodes[0], 1);
824 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
826 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
827 Err(PaymentSendFailure::DuplicatePayment) => {},
828 _ => panic!("Unexpected error")
830 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
834 fn test_completed_payment_not_retryable_on_reload() {
835 do_test_completed_payment_not_retryable_on_reload(true);
836 do_test_completed_payment_not_retryable_on_reload(false);
840 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
841 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
842 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
843 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
844 // the ChannelMonitor tells it to.
846 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
847 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
848 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
849 let chanmon_cfgs = create_chanmon_cfgs(2);
850 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
851 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
852 let persister: test_utils::TestPersister;
853 let new_chain_monitor: test_utils::TestChainMonitor;
854 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>;
855 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
857 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
859 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
861 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
862 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
863 check_closed_broadcast!(nodes[0], true);
864 check_added_monitors!(nodes[0], 1);
865 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
867 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
868 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
870 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
871 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
872 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
873 assert_eq!(node_txn.len(), 3);
874 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
875 check_spends!(node_txn[1], funding_tx);
876 check_spends!(node_txn[2], node_txn[1]);
877 let timeout_txn = vec![node_txn[2].clone()];
879 nodes[1].node.claim_funds(payment_preimage);
880 check_added_monitors!(nodes[1], 1);
881 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
883 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[1].clone()]));
884 check_closed_broadcast!(nodes[1], true);
885 check_added_monitors!(nodes[1], 1);
886 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
887 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
888 assert_eq!(claim_txn.len(), 1);
889 check_spends!(claim_txn[0], node_txn[1]);
891 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[1].clone()]));
893 if confirm_commitment_tx {
894 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
897 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] });
900 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
901 connect_block(&nodes[0], &claim_block);
902 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
905 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
906 // returning InProgress. This should cause the claim event to never make its way to the
908 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
909 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
912 connect_blocks(&nodes[0], 1);
914 connect_block(&nodes[0], &claim_block);
917 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
918 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
919 .get_mut(&funding_txo).unwrap().drain().collect();
920 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
921 // If we're testing connection idempotency we may get substantially more.
922 assert!(mon_updates.len() >= 1);
923 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
924 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
926 // If we persist the ChannelManager here, we should get the PaymentSent event after
928 let mut chan_manager_serialized = Vec::new();
929 if !persist_manager_post_event {
930 chan_manager_serialized = nodes[0].node.encode();
933 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
934 // payment sent event.
935 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
936 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
937 for update in mon_updates {
938 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
941 expect_payment_failed!(nodes[0], payment_hash, false);
943 expect_payment_sent!(nodes[0], payment_preimage);
946 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
948 if persist_manager_post_event {
949 chan_manager_serialized = nodes[0].node.encode();
952 // Now reload nodes[0]...
953 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
955 if persist_manager_post_event {
956 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
957 } else if payment_timeout {
958 expect_payment_failed!(nodes[0], payment_hash, false);
960 expect_payment_sent!(nodes[0], payment_preimage);
963 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
964 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
965 // payment events should kick in, leaving us with no pending events here.
966 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
967 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
968 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
969 check_added_monitors(&nodes[0], 1);
973 fn test_dup_htlc_onchain_fails_on_reload() {
974 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
975 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
976 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
977 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
978 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
979 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
983 fn test_fulfill_restart_failure() {
984 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
985 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
986 // again, or fail it, giving us free money.
988 // Of course probably they won't fail it and give us free money, but because we have code to
989 // handle it, we should test the logic for it anyway. We do that here.
990 let chanmon_cfgs = create_chanmon_cfgs(2);
991 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
992 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
993 let persister: test_utils::TestPersister;
994 let new_chain_monitor: test_utils::TestChainMonitor;
995 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>;
996 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
998 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
999 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
1001 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
1002 // pre-fulfill, which we do by serializing it here.
1003 let chan_manager_serialized = nodes[1].node.encode();
1004 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1006 nodes[1].node.claim_funds(payment_preimage);
1007 check_added_monitors!(nodes[1], 1);
1008 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1010 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1011 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1012 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
1014 // Now reload nodes[1]...
1015 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1017 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1018 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1020 nodes[1].node.fail_htlc_backwards(&payment_hash);
1021 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1022 check_added_monitors!(nodes[1], 1);
1023 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1024 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1025 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1026 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1027 // it had already considered the payment fulfilled, and now they just got free money.
1028 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1032 fn get_ldk_payment_preimage() {
1033 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1034 let chanmon_cfgs = create_chanmon_cfgs(2);
1035 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1036 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1037 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1038 create_announced_chan_between_nodes(&nodes, 0, 1);
1040 let amt_msat = 60_000;
1041 let expiry_secs = 60 * 60;
1042 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1044 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1045 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
1046 let scorer = test_utils::TestScorer::new();
1047 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1048 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1049 let route = get_route(
1050 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
1051 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
1052 amt_msat, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
1053 nodes[0].node.send_payment_with_route(&route, payment_hash,
1054 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1055 check_added_monitors!(nodes[0], 1);
1057 // Make sure to use `get_payment_preimage`
1058 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1059 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1060 assert_eq!(events.len(), 1);
1061 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1062 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1066 fn sent_probe_is_probe_of_sending_node() {
1067 let chanmon_cfgs = create_chanmon_cfgs(3);
1068 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1069 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1070 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1072 create_announced_chan_between_nodes(&nodes, 0, 1);
1073 create_announced_chan_between_nodes(&nodes, 1, 2);
1075 // First check we refuse to build a single-hop probe
1076 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1077 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1079 // Then build an actual two-hop probing path
1080 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1082 match nodes[0].node.send_probe(route.paths[0].clone()) {
1083 Ok((payment_hash, payment_id)) => {
1084 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1085 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1086 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1091 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1092 check_added_monitors!(nodes[0], 1);
1096 fn successful_probe_yields_event() {
1097 let chanmon_cfgs = create_chanmon_cfgs(3);
1098 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1099 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1100 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1102 create_announced_chan_between_nodes(&nodes, 0, 1);
1103 create_announced_chan_between_nodes(&nodes, 1, 2);
1105 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1107 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1109 // node[0] -- update_add_htlcs -> node[1]
1110 check_added_monitors!(nodes[0], 1);
1111 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1112 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1113 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1114 check_added_monitors!(nodes[1], 0);
1115 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1116 expect_pending_htlcs_forwardable!(nodes[1]);
1118 // node[1] -- update_add_htlcs -> node[2]
1119 check_added_monitors!(nodes[1], 1);
1120 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1121 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1122 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1123 check_added_monitors!(nodes[2], 0);
1124 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
1126 // node[1] <- update_fail_htlcs -- node[2]
1127 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1128 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1129 check_added_monitors!(nodes[1], 0);
1130 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1132 // node[0] <- update_fail_htlcs -- node[1]
1133 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1134 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1135 check_added_monitors!(nodes[0], 0);
1136 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1138 let mut events = nodes[0].node.get_and_clear_pending_events();
1139 assert_eq!(events.len(), 1);
1140 match events.drain(..).next().unwrap() {
1141 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1142 assert_eq!(payment_id, ev_pid);
1143 assert_eq!(payment_hash, ev_ph);
1147 assert!(!nodes[0].node.has_pending_payments());
1151 fn failed_probe_yields_event() {
1152 let chanmon_cfgs = create_chanmon_cfgs(3);
1153 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1154 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1155 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1157 create_announced_chan_between_nodes(&nodes, 0, 1);
1158 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1160 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1162 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000);
1164 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1166 // node[0] -- update_add_htlcs -> node[1]
1167 check_added_monitors!(nodes[0], 1);
1168 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1169 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1170 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1171 check_added_monitors!(nodes[1], 0);
1172 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1173 expect_pending_htlcs_forwardable!(nodes[1]);
1175 // node[0] <- update_fail_htlcs -- node[1]
1176 check_added_monitors!(nodes[1], 1);
1177 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1178 // Skip the PendingHTLCsForwardable event
1179 let _events = nodes[1].node.get_and_clear_pending_events();
1180 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1181 check_added_monitors!(nodes[0], 0);
1182 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1184 let mut events = nodes[0].node.get_and_clear_pending_events();
1185 assert_eq!(events.len(), 1);
1186 match events.drain(..).next().unwrap() {
1187 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1188 assert_eq!(payment_id, ev_pid);
1189 assert_eq!(payment_hash, ev_ph);
1193 assert!(!nodes[0].node.has_pending_payments());
1197 fn onchain_failed_probe_yields_event() {
1198 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1200 let chanmon_cfgs = create_chanmon_cfgs(3);
1201 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1202 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1203 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1205 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1206 create_announced_chan_between_nodes(&nodes, 1, 2);
1208 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1210 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1211 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000);
1212 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1214 // node[0] -- update_add_htlcs -> node[1]
1215 check_added_monitors!(nodes[0], 1);
1216 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1217 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1218 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1219 check_added_monitors!(nodes[1], 0);
1220 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1221 expect_pending_htlcs_forwardable!(nodes[1]);
1223 check_added_monitors!(nodes[1], 1);
1224 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1226 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1227 // Node A, which after 6 confirmations should result in a probe failure event.
1228 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1229 confirm_transaction(&nodes[0], &bs_txn[0]);
1230 check_closed_broadcast!(&nodes[0], true);
1231 check_added_monitors!(nodes[0], 1);
1233 let mut events = nodes[0].node.get_and_clear_pending_events();
1234 assert_eq!(events.len(), 2);
1235 let mut found_probe_failed = false;
1236 for event in events.drain(..) {
1238 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1239 assert_eq!(payment_id, ev_pid);
1240 assert_eq!(payment_hash, ev_ph);
1241 found_probe_failed = true;
1243 Event::ChannelClosed { .. } => {},
1247 assert!(found_probe_failed);
1248 assert!(!nodes[0].node.has_pending_payments());
1252 fn claimed_send_payment_idempotent() {
1253 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1254 let chanmon_cfgs = create_chanmon_cfgs(2);
1255 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1256 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1257 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1259 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1261 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1262 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1264 macro_rules! check_send_rejected {
1266 // If we try to resend a new payment with a different payment_hash but with the same
1267 // payment_id, it should be rejected.
1268 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1269 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1271 Err(PaymentSendFailure::DuplicatePayment) => {},
1272 _ => panic!("Unexpected send result: {:?}", send_result),
1275 // Further, if we try to send a spontaneous payment with the same payment_id it should
1276 // also be rejected.
1277 let send_result = nodes[0].node.send_spontaneous_payment(
1278 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1280 Err(PaymentSendFailure::DuplicatePayment) => {},
1281 _ => panic!("Unexpected send result: {:?}", send_result),
1286 check_send_rejected!();
1288 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1289 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1290 // we must remain just as idempotent as we were before.
1291 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1293 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1294 nodes[0].node.timer_tick_occurred();
1297 check_send_rejected!();
1299 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1300 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1301 // the payment complete. However, they could have called `send_payment` while the event was
1302 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1303 // after the event is handled a duplicate payment should sitll be rejected.
1304 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1305 check_send_rejected!();
1307 // If relatively little time has passed, a duplicate payment should still fail.
1308 nodes[0].node.timer_tick_occurred();
1309 check_send_rejected!();
1311 // However, after some time has passed (at least more than the one timer tick above), a
1312 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1313 // references to the old payment data.
1314 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1315 nodes[0].node.timer_tick_occurred();
1318 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1319 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1320 check_added_monitors!(nodes[0], 1);
1321 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1322 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1326 fn abandoned_send_payment_idempotent() {
1327 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1329 let chanmon_cfgs = create_chanmon_cfgs(2);
1330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1332 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1334 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1336 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1337 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1339 macro_rules! check_send_rejected {
1341 // If we try to resend a new payment with a different payment_hash but with the same
1342 // payment_id, it should be rejected.
1343 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1344 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1346 Err(PaymentSendFailure::DuplicatePayment) => {},
1347 _ => panic!("Unexpected send result: {:?}", send_result),
1350 // Further, if we try to send a spontaneous payment with the same payment_id it should
1351 // also be rejected.
1352 let send_result = nodes[0].node.send_spontaneous_payment(
1353 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1355 Err(PaymentSendFailure::DuplicatePayment) => {},
1356 _ => panic!("Unexpected send result: {:?}", send_result),
1361 check_send_rejected!();
1363 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1364 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1366 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1368 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1369 nodes[0].node.timer_tick_occurred();
1371 check_send_rejected!();
1373 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1375 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1376 // failed payment back.
1377 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1378 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1379 check_added_monitors!(nodes[0], 1);
1380 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1381 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1384 #[derive(PartialEq)]
1385 enum InterceptTest {
1392 fn test_trivial_inflight_htlc_tracking(){
1393 // In this test, we test three scenarios:
1394 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1395 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1396 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1397 let chanmon_cfgs = create_chanmon_cfgs(3);
1398 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1399 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1400 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1402 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1403 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1405 // Send and claim the payment. Inflight HTLCs should be empty.
1406 let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1407 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1409 let mut node_0_per_peer_lock;
1410 let mut node_0_peer_state_lock;
1411 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1413 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1414 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1415 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1416 channel_1.context.get_short_channel_id().unwrap()
1418 assert_eq!(chan_1_used_liquidity, None);
1421 let mut node_1_per_peer_lock;
1422 let mut node_1_peer_state_lock;
1423 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1425 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1426 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1427 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1428 channel_2.context.get_short_channel_id().unwrap()
1431 assert_eq!(chan_2_used_liquidity, None);
1433 let pending_payments = nodes[0].node.list_recent_payments();
1434 assert_eq!(pending_payments.len(), 1);
1435 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1437 // Remove fulfilled payment
1438 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1439 nodes[0].node.timer_tick_occurred();
1442 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1443 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1444 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1446 let mut node_0_per_peer_lock;
1447 let mut node_0_peer_state_lock;
1448 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1450 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1451 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1452 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1453 channel_1.context.get_short_channel_id().unwrap()
1455 // First hop accounts for expected 1000 msat fee
1456 assert_eq!(chan_1_used_liquidity, Some(501000));
1459 let mut node_1_per_peer_lock;
1460 let mut node_1_peer_state_lock;
1461 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1463 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1464 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1465 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1466 channel_2.context.get_short_channel_id().unwrap()
1469 assert_eq!(chan_2_used_liquidity, Some(500000));
1471 let pending_payments = nodes[0].node.list_recent_payments();
1472 assert_eq!(pending_payments.len(), 1);
1473 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1475 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1476 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1478 // Remove fulfilled payment
1479 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1480 nodes[0].node.timer_tick_occurred();
1483 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1485 let mut node_0_per_peer_lock;
1486 let mut node_0_peer_state_lock;
1487 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1489 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1490 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1491 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1492 channel_1.context.get_short_channel_id().unwrap()
1494 assert_eq!(chan_1_used_liquidity, None);
1497 let mut node_1_per_peer_lock;
1498 let mut node_1_peer_state_lock;
1499 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1501 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1502 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1503 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1504 channel_2.context.get_short_channel_id().unwrap()
1506 assert_eq!(chan_2_used_liquidity, None);
1509 let pending_payments = nodes[0].node.list_recent_payments();
1510 assert_eq!(pending_payments.len(), 0);
1514 fn test_holding_cell_inflight_htlcs() {
1515 let chanmon_cfgs = create_chanmon_cfgs(2);
1516 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1517 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1518 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1519 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1521 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1522 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1524 // Queue up two payments - one will be delivered right away, one immediately goes into the
1525 // holding cell as nodes[0] is AwaitingRAA.
1527 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1528 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1529 check_added_monitors!(nodes[0], 1);
1530 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1531 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1532 check_added_monitors!(nodes[0], 0);
1535 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1538 let mut node_0_per_peer_lock;
1539 let mut node_0_peer_state_lock;
1540 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1542 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1543 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1544 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1545 channel.context.get_short_channel_id().unwrap()
1548 assert_eq!(used_liquidity, Some(2000000));
1551 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1552 nodes[0].node.get_and_clear_pending_msg_events();
1556 fn intercepted_payment() {
1557 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1558 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1559 // payment or (b) fail the payment.
1560 do_test_intercepted_payment(InterceptTest::Forward);
1561 do_test_intercepted_payment(InterceptTest::Fail);
1562 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1563 do_test_intercepted_payment(InterceptTest::Timeout);
1566 fn do_test_intercepted_payment(test: InterceptTest) {
1567 let chanmon_cfgs = create_chanmon_cfgs(3);
1568 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1570 let mut zero_conf_chan_config = test_default_channel_config();
1571 zero_conf_chan_config.manually_accept_inbound_channels = true;
1572 let mut intercept_forwards_config = test_default_channel_config();
1573 intercept_forwards_config.accept_intercept_htlcs = true;
1574 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1576 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1577 let scorer = test_utils::TestScorer::new();
1578 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1580 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1582 let amt_msat = 100_000;
1583 let intercept_scid = nodes[1].node.get_intercept_scid();
1584 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1585 .with_route_hints(vec![
1586 RouteHint(vec![RouteHintHop {
1587 src_node_id: nodes[1].node.get_our_node_id(),
1588 short_channel_id: intercept_scid,
1591 proportional_millionths: 0,
1593 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1594 htlc_minimum_msat: None,
1595 htlc_maximum_msat: None,
1598 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1599 let route_params = RouteParameters {
1601 final_value_msat: amt_msat,
1603 let route = get_route(
1604 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1605 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1606 nodes[0].logger, &scorer, &(), &random_seed_bytes,
1609 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1610 nodes[0].node.send_payment_with_route(&route, payment_hash,
1611 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1612 let payment_event = {
1614 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1615 assert_eq!(added_monitors.len(), 1);
1616 added_monitors.clear();
1618 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1619 assert_eq!(events.len(), 1);
1620 SendEvent::from_event(events.remove(0))
1622 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1623 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1625 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1626 let events = nodes[1].node.get_and_clear_pending_events();
1627 assert_eq!(events.len(), 1);
1628 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1629 crate::events::Event::HTLCIntercepted {
1630 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1632 assert_eq!(pmt_hash, payment_hash);
1633 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1634 assert_eq!(short_channel_id, intercept_scid);
1635 (intercept_id, expected_outbound_amount_msat)
1640 // Check for unknown channel id error.
1641 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();
1642 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable {
1643 err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1644 log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1646 if test == InterceptTest::Fail {
1647 // Ensure we can fail the intercepted payment back.
1648 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1649 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1650 nodes[1].node.process_pending_htlc_forwards();
1651 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1652 check_added_monitors!(&nodes[1], 1);
1653 assert!(update_fail.update_fail_htlcs.len() == 1);
1654 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1655 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1656 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1658 // Ensure the payment fails with the expected error.
1659 let fail_conditions = PaymentFailedConditions::new()
1660 .blamed_scid(intercept_scid)
1661 .blamed_chan_closed(true)
1662 .expected_htlc_error_data(0x4000 | 10, &[]);
1663 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1664 } else if test == InterceptTest::Forward {
1665 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1666 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1667 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();
1668 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1669 err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1670 log_bytes!(temp_chan_id), nodes[2].node.get_our_node_id()) });
1671 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1673 // Open the just-in-time channel so the payment can then be forwarded.
1674 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1676 // Finally, forward the intercepted payment through and claim it.
1677 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1678 expect_pending_htlcs_forwardable!(nodes[1]);
1680 let payment_event = {
1682 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1683 assert_eq!(added_monitors.len(), 1);
1684 added_monitors.clear();
1686 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1687 assert_eq!(events.len(), 1);
1688 SendEvent::from_event(events.remove(0))
1690 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1691 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1692 expect_pending_htlcs_forwardable!(nodes[2]);
1694 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1695 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1696 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1697 let events = nodes[0].node.get_and_clear_pending_events();
1698 assert_eq!(events.len(), 2);
1700 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1701 assert_eq!(payment_preimage, *ev_preimage);
1702 assert_eq!(payment_hash, *ev_hash);
1703 assert_eq!(fee_paid_msat, &Some(1000));
1705 _ => panic!("Unexpected event")
1708 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1709 assert_eq!(hash, Some(payment_hash));
1711 _ => panic!("Unexpected event")
1713 } else if test == InterceptTest::Timeout {
1714 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
1715 connect_block(&nodes[0], &block);
1716 connect_block(&nodes[1], &block);
1717 for _ in 0..TEST_FINAL_CLTV {
1718 block.header.prev_blockhash = block.block_hash();
1719 connect_block(&nodes[0], &block);
1720 connect_block(&nodes[1], &block);
1722 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1723 check_added_monitors!(nodes[1], 1);
1724 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1725 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1726 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1727 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1728 assert!(htlc_timeout_updates.update_fee.is_none());
1730 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1731 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1732 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1734 // Check for unknown intercept id error.
1735 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1736 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();
1737 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1738 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1739 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1744 fn accept_underpaying_htlcs_config() {
1745 do_accept_underpaying_htlcs_config(1);
1746 do_accept_underpaying_htlcs_config(2);
1747 do_accept_underpaying_htlcs_config(3);
1750 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
1751 let chanmon_cfgs = create_chanmon_cfgs(3);
1752 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1753 let mut intercept_forwards_config = test_default_channel_config();
1754 intercept_forwards_config.accept_intercept_htlcs = true;
1755 let mut underpay_config = test_default_channel_config();
1756 underpay_config.channel_config.accept_underpaying_htlcs = true;
1757 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
1758 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1760 let mut chan_ids = Vec::new();
1761 for _ in 0..num_mpp_parts {
1762 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000, 0);
1763 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 2_000_000, 0).0.channel_id;
1764 chan_ids.push(channel_id);
1767 // Send the initial payment.
1768 let amt_msat = 900_000;
1769 let skimmed_fee_msat = 20;
1770 let mut route_hints = Vec::new();
1771 for _ in 0..num_mpp_parts {
1772 route_hints.push(RouteHint(vec![RouteHintHop {
1773 src_node_id: nodes[1].node.get_our_node_id(),
1774 short_channel_id: nodes[1].node.get_intercept_scid(),
1777 proportional_millionths: 0,
1779 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1780 htlc_minimum_msat: None,
1781 htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
1784 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1785 .with_route_hints(route_hints).unwrap()
1786 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1787 let route_params = RouteParameters {
1789 final_value_msat: amt_msat,
1791 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1792 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1793 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
1794 check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
1795 let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
1796 assert_eq!(events.len(), num_mpp_parts);
1798 // Forward the intercepted payments.
1799 for (idx, ev) in events.into_iter().enumerate() {
1800 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
1801 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
1803 let events = nodes[1].node.get_and_clear_pending_events();
1804 assert_eq!(events.len(), 1);
1805 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
1806 crate::events::Event::HTLCIntercepted {
1807 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
1809 assert_eq!(pmt_hash, payment_hash);
1810 (intercept_id, expected_outbound_amount_msat)
1814 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
1815 nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
1816 expect_pending_htlcs_forwardable!(nodes[1]);
1817 let payment_event = {
1819 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1820 assert_eq!(added_monitors.len(), 1);
1821 added_monitors.clear();
1823 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1824 assert_eq!(events.len(), 1);
1825 SendEvent::from_event(events.remove(0))
1827 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1828 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
1829 if idx == num_mpp_parts - 1 {
1830 expect_pending_htlcs_forwardable!(nodes[2]);
1834 // Claim the payment and check that the skimmed fee is as expected.
1835 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1836 let events = nodes[2].node.get_and_clear_pending_events();
1837 assert_eq!(events.len(), 1);
1839 crate::events::Event::PaymentClaimable {
1840 ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
1842 assert_eq!(payment_hash, payment_hash);
1843 assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
1844 assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
1845 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1847 crate::events::PaymentPurpose::InvoicePayment { payment_preimage: ev_payment_preimage,
1848 payment_secret: ev_payment_secret, .. } =>
1850 assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
1851 assert_eq!(payment_secret, *ev_payment_secret);
1856 _ => panic!("Unexpected event"),
1858 let mut expected_paths_vecs = Vec::new();
1859 let mut expected_paths = Vec::new();
1860 for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
1861 for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
1862 let total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
1863 &nodes[0], &expected_paths[..], &vec![skimmed_fee_msat as u32; num_mpp_parts][..], false,
1865 // The sender doesn't know that the penultimate hop took an extra fee.
1866 expect_payment_sent(&nodes[0], payment_preimage,
1867 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true);
1870 #[derive(PartialEq)]
1881 fn automatic_retries() {
1882 do_automatic_retries(AutoRetry::Success);
1883 do_automatic_retries(AutoRetry::Spontaneous);
1884 do_automatic_retries(AutoRetry::FailAttempts);
1885 do_automatic_retries(AutoRetry::FailTimeout);
1886 do_automatic_retries(AutoRetry::FailOnRestart);
1887 do_automatic_retries(AutoRetry::FailOnRetry);
1889 fn do_automatic_retries(test: AutoRetry) {
1890 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1892 let chanmon_cfgs = create_chanmon_cfgs(3);
1893 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1894 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1897 let new_chain_monitor;
1898 let node_0_deserialized;
1900 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1901 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1902 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1904 // Marshall data to send the payment
1905 #[cfg(feature = "std")]
1906 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1907 #[cfg(not(feature = "std"))]
1908 let payment_expiry_secs = 60 * 60;
1909 let amt_msat = 1000;
1910 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1911 invoice_features.set_variable_length_onion_required();
1912 invoice_features.set_payment_secret_required();
1913 invoice_features.set_basic_mpp_optional();
1914 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1915 .with_expiry_time(payment_expiry_secs as u64)
1916 .with_bolt11_features(invoice_features).unwrap();
1917 let route_params = RouteParameters {
1919 final_value_msat: amt_msat,
1921 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1923 macro_rules! pass_failed_attempt_with_retry_along_path {
1924 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1925 // Send a payment attempt that fails due to lack of liquidity on the second hop
1926 check_added_monitors!(nodes[0], 1);
1927 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1928 let mut update_add = update_0.update_add_htlcs[0].clone();
1929 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1930 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1931 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1932 nodes[1].node.process_pending_htlc_forwards();
1933 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1934 vec![HTLCDestination::NextHopChannel {
1935 node_id: Some(nodes[2].node.get_our_node_id()),
1936 channel_id: $failing_channel_id,
1938 nodes[1].node.process_pending_htlc_forwards();
1939 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1940 check_added_monitors!(&nodes[1], 1);
1941 assert!(update_1.update_fail_htlcs.len() == 1);
1942 let fail_msg = update_1.update_fail_htlcs[0].clone();
1943 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1944 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1946 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1947 let mut events = nodes[0].node.get_and_clear_pending_events();
1948 assert_eq!(events.len(), 2);
1950 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1951 assert_eq!(payment_hash, ev_payment_hash);
1952 assert_eq!(payment_failed_permanently, false);
1954 _ => panic!("Unexpected event"),
1956 if $expect_pending_htlcs_forwardable {
1958 Event::PendingHTLCsForwardable { .. } => {},
1959 _ => panic!("Unexpected event"),
1963 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1964 assert_eq!(payment_hash, ev_payment_hash);
1966 _ => panic!("Unexpected event"),
1972 if test == AutoRetry::Success {
1973 // Test that we can succeed on the first retry.
1974 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1975 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1976 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1978 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1979 // attempt, since the initial second hop channel will be excluded from pathfinding
1980 create_announced_chan_between_nodes(&nodes, 1, 2);
1982 // We retry payments in `process_pending_htlc_forwards`
1983 nodes[0].node.process_pending_htlc_forwards();
1984 check_added_monitors!(nodes[0], 1);
1985 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1986 assert_eq!(msg_events.len(), 1);
1987 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1988 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1989 } else if test == AutoRetry::Spontaneous {
1990 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
1991 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
1992 Retry::Attempts(1)).unwrap();
1993 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1995 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1996 // attempt, since the initial second hop channel will be excluded from pathfinding
1997 create_announced_chan_between_nodes(&nodes, 1, 2);
1999 // We retry payments in `process_pending_htlc_forwards`
2000 nodes[0].node.process_pending_htlc_forwards();
2001 check_added_monitors!(nodes[0], 1);
2002 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2003 assert_eq!(msg_events.len(), 1);
2004 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2005 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2006 } else if test == AutoRetry::FailAttempts {
2007 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2008 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2009 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2010 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2012 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2013 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2014 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2016 // We retry payments in `process_pending_htlc_forwards`
2017 nodes[0].node.process_pending_htlc_forwards();
2018 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2020 // Ensure we won't retry a second time.
2021 nodes[0].node.process_pending_htlc_forwards();
2022 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2023 assert_eq!(msg_events.len(), 0);
2024 } else if test == AutoRetry::FailTimeout {
2025 #[cfg(not(feature = "no-std"))] {
2026 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2027 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2028 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2029 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2031 // Advance the time so the second attempt fails due to timeout.
2032 SinceEpoch::advance(Duration::from_secs(61));
2034 // Make sure we don't retry again.
2035 nodes[0].node.process_pending_htlc_forwards();
2036 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2037 assert_eq!(msg_events.len(), 0);
2039 let mut events = nodes[0].node.get_and_clear_pending_events();
2040 assert_eq!(events.len(), 1);
2042 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2043 assert_eq!(payment_hash, *ev_payment_hash);
2044 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2045 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2047 _ => panic!("Unexpected event"),
2050 } else if test == AutoRetry::FailOnRestart {
2051 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2052 // attempts remaining prior to restart.
2053 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2054 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2055 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2057 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2058 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2059 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2061 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2062 nodes[0].node.process_pending_htlc_forwards();
2063 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2065 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2066 let node_encoded = nodes[0].node.encode();
2067 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2068 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2070 let mut events = nodes[0].node.get_and_clear_pending_events();
2071 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2072 // Make sure we don't retry again.
2073 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2074 assert_eq!(msg_events.len(), 0);
2076 let mut events = nodes[0].node.get_and_clear_pending_events();
2077 assert_eq!(events.len(), 1);
2079 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2080 assert_eq!(payment_hash, *ev_payment_hash);
2081 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2082 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2084 _ => panic!("Unexpected event"),
2086 } else if test == AutoRetry::FailOnRetry {
2087 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2088 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2089 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2091 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2092 // fail to find a route.
2093 nodes[0].node.process_pending_htlc_forwards();
2094 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2095 assert_eq!(msg_events.len(), 0);
2097 let mut events = nodes[0].node.get_and_clear_pending_events();
2098 assert_eq!(events.len(), 1);
2100 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2101 assert_eq!(payment_hash, *ev_payment_hash);
2102 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2103 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2105 _ => panic!("Unexpected event"),
2111 fn auto_retry_partial_failure() {
2112 // Test that we'll retry appropriately on send partial failure and retry partial failure.
2113 let chanmon_cfgs = create_chanmon_cfgs(2);
2114 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2115 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2116 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2118 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2119 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2120 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2122 // Marshall data to send the payment
2123 let amt_msat = 20_000;
2124 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2125 #[cfg(feature = "std")]
2126 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2127 #[cfg(not(feature = "std"))]
2128 let payment_expiry_secs = 60 * 60;
2129 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2130 invoice_features.set_variable_length_onion_required();
2131 invoice_features.set_payment_secret_required();
2132 invoice_features.set_basic_mpp_optional();
2133 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2134 .with_expiry_time(payment_expiry_secs as u64)
2135 .with_bolt11_features(invoice_features).unwrap();
2136 let route_params = RouteParameters {
2138 final_value_msat: amt_msat,
2141 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
2142 // second (for the initial send path2 over chan_2) fails.
2143 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2144 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2145 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
2146 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
2147 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2148 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2149 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2151 // Configure the initial send, retry1 and retry2's paths.
2152 let send_route = Route {
2154 Path { hops: vec![RouteHop {
2155 pubkey: nodes[1].node.get_our_node_id(),
2156 node_features: nodes[1].node.node_features(),
2157 short_channel_id: chan_1_id,
2158 channel_features: nodes[1].node.channel_features(),
2159 fee_msat: amt_msat / 2,
2160 cltv_expiry_delta: 100,
2161 }], blinded_tail: None },
2162 Path { hops: vec![RouteHop {
2163 pubkey: nodes[1].node.get_our_node_id(),
2164 node_features: nodes[1].node.node_features(),
2165 short_channel_id: chan_2_id,
2166 channel_features: nodes[1].node.channel_features(),
2167 fee_msat: amt_msat / 2,
2168 cltv_expiry_delta: 100,
2169 }], blinded_tail: None },
2171 payment_params: Some(route_params.payment_params.clone()),
2173 let retry_1_route = Route {
2175 Path { hops: vec![RouteHop {
2176 pubkey: nodes[1].node.get_our_node_id(),
2177 node_features: nodes[1].node.node_features(),
2178 short_channel_id: chan_1_id,
2179 channel_features: nodes[1].node.channel_features(),
2180 fee_msat: amt_msat / 4,
2181 cltv_expiry_delta: 100,
2182 }], blinded_tail: None },
2183 Path { hops: vec![RouteHop {
2184 pubkey: nodes[1].node.get_our_node_id(),
2185 node_features: nodes[1].node.node_features(),
2186 short_channel_id: chan_3_id,
2187 channel_features: nodes[1].node.channel_features(),
2188 fee_msat: amt_msat / 4,
2189 cltv_expiry_delta: 100,
2190 }], blinded_tail: None },
2192 payment_params: Some(route_params.payment_params.clone()),
2194 let retry_2_route = Route {
2196 Path { hops: vec![RouteHop {
2197 pubkey: nodes[1].node.get_our_node_id(),
2198 node_features: nodes[1].node.node_features(),
2199 short_channel_id: chan_1_id,
2200 channel_features: nodes[1].node.channel_features(),
2201 fee_msat: amt_msat / 4,
2202 cltv_expiry_delta: 100,
2203 }], blinded_tail: None },
2205 payment_params: Some(route_params.payment_params.clone()),
2207 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2208 let mut payment_params = route_params.payment_params.clone();
2209 payment_params.previously_failed_channels.push(chan_2_id);
2210 nodes[0].router.expect_find_route(RouteParameters {
2211 payment_params, final_value_msat: amt_msat / 2,
2212 }, Ok(retry_1_route));
2213 let mut payment_params = route_params.payment_params.clone();
2214 payment_params.previously_failed_channels.push(chan_3_id);
2215 nodes[0].router.expect_find_route(RouteParameters {
2216 payment_params, final_value_msat: amt_msat / 4,
2217 }, Ok(retry_2_route));
2219 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2220 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2221 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2222 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
2223 assert_eq!(closed_chan_events.len(), 4);
2224 match closed_chan_events[0] {
2225 Event::ChannelClosed { .. } => {},
2226 _ => panic!("Unexpected event"),
2228 match closed_chan_events[1] {
2229 Event::PaymentPathFailed { .. } => {},
2230 _ => panic!("Unexpected event"),
2232 match closed_chan_events[2] {
2233 Event::ChannelClosed { .. } => {},
2234 _ => panic!("Unexpected event"),
2236 match closed_chan_events[3] {
2237 Event::PaymentPathFailed { .. } => {},
2238 _ => panic!("Unexpected event"),
2241 // Pass the first part of the payment along the path.
2242 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
2243 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2245 // First message is the first update_add, remaining messages are broadcasting channel updates and
2246 // errors for the permfailed channels
2247 assert_eq!(msg_events.len(), 5);
2248 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2250 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2251 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2252 check_added_monitors!(nodes[1], 1);
2253 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2255 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2256 check_added_monitors!(nodes[0], 1);
2257 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2259 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2260 check_added_monitors!(nodes[0], 1);
2261 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2263 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2264 check_added_monitors!(nodes[1], 1);
2266 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2267 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2268 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2269 check_added_monitors!(nodes[1], 1);
2270 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2272 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2273 check_added_monitors!(nodes[0], 1);
2275 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2276 check_added_monitors!(nodes[0], 1);
2277 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2279 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2280 check_added_monitors!(nodes[1], 1);
2282 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2283 nodes[1].node.process_pending_htlc_forwards();
2284 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2285 nodes[1].node.claim_funds(payment_preimage);
2286 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2287 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2288 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2290 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2291 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2292 check_added_monitors!(nodes[0], 1);
2293 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2295 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2296 check_added_monitors!(nodes[1], 4);
2297 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2299 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2300 check_added_monitors!(nodes[1], 1);
2301 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2303 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2304 check_added_monitors!(nodes[0], 1);
2306 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2307 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2308 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2309 check_added_monitors!(nodes[0], 1);
2310 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2312 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2313 check_added_monitors!(nodes[1], 1);
2315 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2316 check_added_monitors!(nodes[1], 1);
2317 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2319 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2320 check_added_monitors!(nodes[0], 1);
2321 expect_payment_sent!(nodes[0], payment_preimage);
2325 fn auto_retry_zero_attempts_send_error() {
2326 let chanmon_cfgs = create_chanmon_cfgs(2);
2327 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2328 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2329 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2331 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2332 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2334 // Marshall data to send the payment
2335 let amt_msat = 20_000;
2336 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2337 #[cfg(feature = "std")]
2338 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2339 #[cfg(not(feature = "std"))]
2340 let payment_expiry_secs = 60 * 60;
2341 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2342 invoice_features.set_variable_length_onion_required();
2343 invoice_features.set_payment_secret_required();
2344 invoice_features.set_basic_mpp_optional();
2345 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2346 .with_expiry_time(payment_expiry_secs as u64)
2347 .with_bolt11_features(invoice_features).unwrap();
2348 let route_params = RouteParameters {
2350 final_value_msat: amt_msat,
2353 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2354 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2355 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2356 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2357 let events = nodes[0].node.get_and_clear_pending_events();
2358 assert_eq!(events.len(), 3);
2359 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2360 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2361 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2362 check_added_monitors!(nodes[0], 2);
2366 fn fails_paying_after_rejected_by_payee() {
2367 let chanmon_cfgs = create_chanmon_cfgs(2);
2368 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2369 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2370 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2372 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2374 // Marshall data to send the payment
2375 let amt_msat = 20_000;
2376 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2377 #[cfg(feature = "std")]
2378 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2379 #[cfg(not(feature = "std"))]
2380 let payment_expiry_secs = 60 * 60;
2381 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2382 invoice_features.set_variable_length_onion_required();
2383 invoice_features.set_payment_secret_required();
2384 invoice_features.set_basic_mpp_optional();
2385 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2386 .with_expiry_time(payment_expiry_secs as u64)
2387 .with_bolt11_features(invoice_features).unwrap();
2388 let route_params = RouteParameters {
2390 final_value_msat: amt_msat,
2393 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2394 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2395 check_added_monitors!(nodes[0], 1);
2396 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2397 assert_eq!(events.len(), 1);
2398 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2399 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2400 check_added_monitors!(nodes[1], 0);
2401 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2402 expect_pending_htlcs_forwardable!(nodes[1]);
2403 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2405 nodes[1].node.fail_htlc_backwards(&payment_hash);
2406 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2407 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2411 fn retry_multi_path_single_failed_payment() {
2412 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2413 let chanmon_cfgs = create_chanmon_cfgs(2);
2414 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2415 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2416 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2418 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2419 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2421 let amt_msat = 100_010_000;
2423 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2424 #[cfg(feature = "std")]
2425 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2426 #[cfg(not(feature = "std"))]
2427 let payment_expiry_secs = 60 * 60;
2428 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2429 invoice_features.set_variable_length_onion_required();
2430 invoice_features.set_payment_secret_required();
2431 invoice_features.set_basic_mpp_optional();
2432 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2433 .with_expiry_time(payment_expiry_secs as u64)
2434 .with_bolt11_features(invoice_features).unwrap();
2435 let route_params = RouteParameters {
2436 payment_params: payment_params.clone(),
2437 final_value_msat: amt_msat,
2440 let chans = nodes[0].node.list_usable_channels();
2441 let mut route = Route {
2443 Path { hops: vec![RouteHop {
2444 pubkey: nodes[1].node.get_our_node_id(),
2445 node_features: nodes[1].node.node_features(),
2446 short_channel_id: chans[0].short_channel_id.unwrap(),
2447 channel_features: nodes[1].node.channel_features(),
2449 cltv_expiry_delta: 100,
2450 }], blinded_tail: None },
2451 Path { hops: vec![RouteHop {
2452 pubkey: nodes[1].node.get_our_node_id(),
2453 node_features: nodes[1].node.node_features(),
2454 short_channel_id: chans[1].short_channel_id.unwrap(),
2455 channel_features: nodes[1].node.channel_features(),
2456 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2457 cltv_expiry_delta: 100,
2458 }], blinded_tail: None },
2460 payment_params: Some(payment_params),
2462 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2463 // On retry, split the payment across both channels.
2464 route.paths[0].hops[0].fee_msat = 50_000_001;
2465 route.paths[1].hops[0].fee_msat = 50_000_000;
2466 let mut pay_params = route.payment_params.clone().unwrap();
2467 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2468 nodes[0].router.expect_find_route(RouteParameters {
2469 payment_params: pay_params,
2470 // Note that the second request here requests the amount we originally failed to send,
2471 // not the amount remaining on the full payment, which should be changed.
2472 final_value_msat: 100_000_001,
2473 }, Ok(route.clone()));
2476 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2477 // The initial send attempt, 2 paths
2478 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2479 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2480 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2481 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2482 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2485 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2486 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2487 let events = nodes[0].node.get_and_clear_pending_events();
2488 assert_eq!(events.len(), 1);
2490 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2491 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2492 short_channel_id: Some(expected_scid), .. } =>
2494 assert_eq!(payment_hash, ev_payment_hash);
2495 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2497 _ => panic!("Unexpected event"),
2499 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2500 assert_eq!(htlc_msgs.len(), 2);
2501 check_added_monitors!(nodes[0], 2);
2505 fn immediate_retry_on_failure() {
2506 // Tests that we can/will retry immediately after a failure
2507 let chanmon_cfgs = create_chanmon_cfgs(2);
2508 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2509 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2510 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2512 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2513 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2515 let amt_msat = 100_000_001;
2516 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2517 #[cfg(feature = "std")]
2518 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2519 #[cfg(not(feature = "std"))]
2520 let payment_expiry_secs = 60 * 60;
2521 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2522 invoice_features.set_variable_length_onion_required();
2523 invoice_features.set_payment_secret_required();
2524 invoice_features.set_basic_mpp_optional();
2525 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2526 .with_expiry_time(payment_expiry_secs as u64)
2527 .with_bolt11_features(invoice_features).unwrap();
2528 let route_params = RouteParameters {
2530 final_value_msat: amt_msat,
2533 let chans = nodes[0].node.list_usable_channels();
2534 let mut route = Route {
2536 Path { hops: vec![RouteHop {
2537 pubkey: nodes[1].node.get_our_node_id(),
2538 node_features: nodes[1].node.node_features(),
2539 short_channel_id: chans[0].short_channel_id.unwrap(),
2540 channel_features: nodes[1].node.channel_features(),
2541 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2542 cltv_expiry_delta: 100,
2543 }], blinded_tail: None },
2545 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2547 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2548 // On retry, split the payment across both channels.
2549 route.paths.push(route.paths[0].clone());
2550 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2551 route.paths[0].hops[0].fee_msat = 50_000_000;
2552 route.paths[1].hops[0].fee_msat = 50_000_001;
2553 let mut pay_params = route_params.payment_params.clone();
2554 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2555 nodes[0].router.expect_find_route(RouteParameters {
2556 payment_params: pay_params, final_value_msat: amt_msat,
2557 }, Ok(route.clone()));
2559 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2560 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2561 let events = nodes[0].node.get_and_clear_pending_events();
2562 assert_eq!(events.len(), 1);
2564 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2565 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2566 short_channel_id: Some(expected_scid), .. } =>
2568 assert_eq!(payment_hash, ev_payment_hash);
2569 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2571 _ => panic!("Unexpected event"),
2573 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2574 assert_eq!(htlc_msgs.len(), 2);
2575 check_added_monitors!(nodes[0], 2);
2579 fn no_extra_retries_on_back_to_back_fail() {
2580 // In a previous release, we had a race where we may exceed the payment retry count if we
2581 // get two failures in a row with the second indicating that all paths had failed (this field,
2582 // `all_paths_failed`, has since been removed).
2583 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2584 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2585 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2586 // pending which we will see later. Thus, when we previously removed the retry tracking map
2587 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2588 // retry entry even though more events for the same payment were still pending. This led to
2589 // us retrying a payment again even though we'd already given up on it.
2591 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2592 // is used to remove the payment retry counter entries instead. This tests for the specific
2593 // excess-retry case while also testing `PaymentFailed` generation.
2595 let chanmon_cfgs = create_chanmon_cfgs(3);
2596 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2597 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2598 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2600 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2601 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2603 let amt_msat = 200_000_000;
2604 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2605 #[cfg(feature = "std")]
2606 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2607 #[cfg(not(feature = "std"))]
2608 let payment_expiry_secs = 60 * 60;
2609 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2610 invoice_features.set_variable_length_onion_required();
2611 invoice_features.set_payment_secret_required();
2612 invoice_features.set_basic_mpp_optional();
2613 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2614 .with_expiry_time(payment_expiry_secs as u64)
2615 .with_bolt11_features(invoice_features).unwrap();
2616 let route_params = RouteParameters {
2618 final_value_msat: amt_msat,
2621 let mut route = Route {
2623 Path { hops: vec![RouteHop {
2624 pubkey: nodes[1].node.get_our_node_id(),
2625 node_features: nodes[1].node.node_features(),
2626 short_channel_id: chan_1_scid,
2627 channel_features: nodes[1].node.channel_features(),
2628 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2629 cltv_expiry_delta: 100,
2631 pubkey: nodes[2].node.get_our_node_id(),
2632 node_features: nodes[2].node.node_features(),
2633 short_channel_id: chan_2_scid,
2634 channel_features: nodes[2].node.channel_features(),
2635 fee_msat: 100_000_000,
2636 cltv_expiry_delta: 100,
2637 }], blinded_tail: None },
2638 Path { hops: vec![RouteHop {
2639 pubkey: nodes[1].node.get_our_node_id(),
2640 node_features: nodes[1].node.node_features(),
2641 short_channel_id: chan_1_scid,
2642 channel_features: nodes[1].node.channel_features(),
2643 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2644 cltv_expiry_delta: 100,
2646 pubkey: nodes[2].node.get_our_node_id(),
2647 node_features: nodes[2].node.node_features(),
2648 short_channel_id: chan_2_scid,
2649 channel_features: nodes[2].node.channel_features(),
2650 fee_msat: 100_000_000,
2651 cltv_expiry_delta: 100,
2652 }], blinded_tail: None }
2654 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2656 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2657 let mut second_payment_params = route_params.payment_params.clone();
2658 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2659 // On retry, we'll only return one path
2660 route.paths.remove(1);
2661 route.paths[0].hops[1].fee_msat = amt_msat;
2662 nodes[0].router.expect_find_route(RouteParameters {
2663 payment_params: second_payment_params,
2664 final_value_msat: amt_msat,
2665 }, Ok(route.clone()));
2667 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2668 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2669 let htlc_updates = SendEvent::from_node(&nodes[0]);
2670 check_added_monitors!(nodes[0], 1);
2671 assert_eq!(htlc_updates.msgs.len(), 1);
2673 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2674 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2675 check_added_monitors!(nodes[1], 1);
2676 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2678 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2679 check_added_monitors!(nodes[0], 1);
2680 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2682 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2683 check_added_monitors!(nodes[0], 1);
2684 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2686 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2687 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2688 check_added_monitors!(nodes[1], 1);
2689 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2691 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2692 check_added_monitors!(nodes[1], 1);
2693 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2695 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2696 check_added_monitors!(nodes[0], 1);
2698 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2699 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2700 check_added_monitors!(nodes[0], 1);
2701 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2703 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2704 check_added_monitors!(nodes[1], 1);
2705 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2707 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2708 check_added_monitors!(nodes[1], 1);
2709 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2711 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2712 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2713 check_added_monitors!(nodes[0], 1);
2715 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2716 check_added_monitors!(nodes[0], 1);
2717 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2719 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2720 check_added_monitors!(nodes[1], 1);
2721 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2722 check_added_monitors!(nodes[1], 1);
2723 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2725 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2726 check_added_monitors!(nodes[0], 1);
2728 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2729 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2732 // Previously, we retried payments in an event consumer, which would retry each
2733 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2734 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2735 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2736 // by adding the `PaymentFailed` event.
2738 // Because we now retry payments as a batch, we simply return a single-path route in the
2739 // second, batched, request, have that fail, ensure the payment was abandoned.
2740 let mut events = nodes[0].node.get_and_clear_pending_events();
2741 assert_eq!(events.len(), 3);
2743 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2744 assert_eq!(payment_hash, ev_payment_hash);
2745 assert_eq!(payment_failed_permanently, false);
2747 _ => panic!("Unexpected event"),
2750 Event::PendingHTLCsForwardable { .. } => {},
2751 _ => panic!("Unexpected event"),
2754 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2755 assert_eq!(payment_hash, ev_payment_hash);
2756 assert_eq!(payment_failed_permanently, false);
2758 _ => panic!("Unexpected event"),
2761 nodes[0].node.process_pending_htlc_forwards();
2762 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2763 check_added_monitors!(nodes[0], 1);
2765 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2766 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2767 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2768 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2769 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2771 let mut events = nodes[0].node.get_and_clear_pending_events();
2772 assert_eq!(events.len(), 2);
2774 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2775 assert_eq!(payment_hash, ev_payment_hash);
2776 assert_eq!(payment_failed_permanently, false);
2778 _ => panic!("Unexpected event"),
2781 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2782 assert_eq!(payment_hash, *ev_payment_hash);
2783 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2784 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2786 _ => panic!("Unexpected event"),
2791 fn test_simple_partial_retry() {
2792 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2793 // full amount of the payment, rather than only the missing amount. Here we simply test for
2794 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2795 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2797 let chanmon_cfgs = create_chanmon_cfgs(3);
2798 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2799 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2800 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2802 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2803 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2805 let amt_msat = 200_000_000;
2806 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2807 #[cfg(feature = "std")]
2808 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2809 #[cfg(not(feature = "std"))]
2810 let payment_expiry_secs = 60 * 60;
2811 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2812 invoice_features.set_variable_length_onion_required();
2813 invoice_features.set_payment_secret_required();
2814 invoice_features.set_basic_mpp_optional();
2815 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2816 .with_expiry_time(payment_expiry_secs as u64)
2817 .with_bolt11_features(invoice_features).unwrap();
2818 let route_params = RouteParameters {
2820 final_value_msat: amt_msat,
2823 let mut route = Route {
2825 Path { hops: vec![RouteHop {
2826 pubkey: nodes[1].node.get_our_node_id(),
2827 node_features: nodes[1].node.node_features(),
2828 short_channel_id: chan_1_scid,
2829 channel_features: nodes[1].node.channel_features(),
2830 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2831 cltv_expiry_delta: 100,
2833 pubkey: nodes[2].node.get_our_node_id(),
2834 node_features: nodes[2].node.node_features(),
2835 short_channel_id: chan_2_scid,
2836 channel_features: nodes[2].node.channel_features(),
2837 fee_msat: 100_000_000,
2838 cltv_expiry_delta: 100,
2839 }], blinded_tail: None },
2840 Path { hops: vec![RouteHop {
2841 pubkey: nodes[1].node.get_our_node_id(),
2842 node_features: nodes[1].node.node_features(),
2843 short_channel_id: chan_1_scid,
2844 channel_features: nodes[1].node.channel_features(),
2846 cltv_expiry_delta: 100,
2848 pubkey: nodes[2].node.get_our_node_id(),
2849 node_features: nodes[2].node.node_features(),
2850 short_channel_id: chan_2_scid,
2851 channel_features: nodes[2].node.channel_features(),
2852 fee_msat: 100_000_000,
2853 cltv_expiry_delta: 100,
2854 }], blinded_tail: None }
2856 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2858 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2859 let mut second_payment_params = route_params.payment_params.clone();
2860 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2861 // On retry, we'll only be asked for one path (or 100k sats)
2862 route.paths.remove(0);
2863 nodes[0].router.expect_find_route(RouteParameters {
2864 payment_params: second_payment_params,
2865 final_value_msat: amt_msat / 2,
2866 }, Ok(route.clone()));
2868 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2869 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2870 let htlc_updates = SendEvent::from_node(&nodes[0]);
2871 check_added_monitors!(nodes[0], 1);
2872 assert_eq!(htlc_updates.msgs.len(), 1);
2874 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2875 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2876 check_added_monitors!(nodes[1], 1);
2877 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2879 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2880 check_added_monitors!(nodes[0], 1);
2881 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2883 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2884 check_added_monitors!(nodes[0], 1);
2885 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2887 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2888 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2889 check_added_monitors!(nodes[1], 1);
2890 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2892 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2893 check_added_monitors!(nodes[1], 1);
2894 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2896 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2897 check_added_monitors!(nodes[0], 1);
2899 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2900 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2901 check_added_monitors!(nodes[0], 1);
2902 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2904 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2905 check_added_monitors!(nodes[1], 1);
2907 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2908 check_added_monitors!(nodes[1], 1);
2910 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2912 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2913 check_added_monitors!(nodes[0], 1);
2915 let mut events = nodes[0].node.get_and_clear_pending_events();
2916 assert_eq!(events.len(), 2);
2918 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2919 assert_eq!(payment_hash, ev_payment_hash);
2920 assert_eq!(payment_failed_permanently, false);
2922 _ => panic!("Unexpected event"),
2925 Event::PendingHTLCsForwardable { .. } => {},
2926 _ => panic!("Unexpected event"),
2929 nodes[0].node.process_pending_htlc_forwards();
2930 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2931 check_added_monitors!(nodes[0], 1);
2933 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2934 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2936 expect_pending_htlcs_forwardable!(nodes[1]);
2937 check_added_monitors!(nodes[1], 1);
2939 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2940 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2941 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2942 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2944 expect_pending_htlcs_forwardable!(nodes[2]);
2945 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2949 #[cfg(feature = "std")]
2950 fn test_threaded_payment_retries() {
2951 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2952 // a single thread and would happily let multiple threads run retries at the same time. Because
2953 // retries are done by first calculating the amount we need to retry, then dropping the
2954 // relevant lock, then actually sending, we would happily let multiple threads retry the same
2955 // amount at the same time, overpaying our original HTLC!
2956 let chanmon_cfgs = create_chanmon_cfgs(4);
2957 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2958 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2959 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2961 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2962 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2963 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2964 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2966 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2967 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2968 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2969 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2971 let amt_msat = 100_000_000;
2972 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2973 #[cfg(feature = "std")]
2974 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2975 #[cfg(not(feature = "std"))]
2976 let payment_expiry_secs = 60 * 60;
2977 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2978 invoice_features.set_variable_length_onion_required();
2979 invoice_features.set_payment_secret_required();
2980 invoice_features.set_basic_mpp_optional();
2981 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2982 .with_expiry_time(payment_expiry_secs as u64)
2983 .with_bolt11_features(invoice_features).unwrap();
2984 let mut route_params = RouteParameters {
2986 final_value_msat: amt_msat,
2989 let mut route = Route {
2991 Path { hops: vec![RouteHop {
2992 pubkey: nodes[1].node.get_our_node_id(),
2993 node_features: nodes[1].node.node_features(),
2994 short_channel_id: chan_1_scid,
2995 channel_features: nodes[1].node.channel_features(),
2997 cltv_expiry_delta: 100,
2999 pubkey: nodes[3].node.get_our_node_id(),
3000 node_features: nodes[2].node.node_features(),
3001 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3002 channel_features: nodes[2].node.channel_features(),
3003 fee_msat: amt_msat / 1000,
3004 cltv_expiry_delta: 100,
3005 }], blinded_tail: None },
3006 Path { hops: vec![RouteHop {
3007 pubkey: nodes[2].node.get_our_node_id(),
3008 node_features: nodes[2].node.node_features(),
3009 short_channel_id: chan_3_scid,
3010 channel_features: nodes[2].node.channel_features(),
3012 cltv_expiry_delta: 100,
3014 pubkey: nodes[3].node.get_our_node_id(),
3015 node_features: nodes[3].node.node_features(),
3016 short_channel_id: chan_4_scid,
3017 channel_features: nodes[3].node.channel_features(),
3018 fee_msat: amt_msat - amt_msat / 1000,
3019 cltv_expiry_delta: 100,
3020 }], blinded_tail: None }
3022 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
3024 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3026 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3027 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3028 check_added_monitors!(nodes[0], 2);
3029 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3030 assert_eq!(send_msg_events.len(), 2);
3031 send_msg_events.retain(|msg|
3032 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3033 // Drop the commitment update for nodes[2], we can just let that one sit pending
3035 *node_id == nodes[1].node.get_our_node_id()
3036 } else { panic!(); }
3039 // from here on out, the retry `RouteParameters` amount will be amt/1000
3040 route_params.final_value_msat /= 1000;
3043 let end_time = Instant::now() + Duration::from_secs(1);
3044 macro_rules! thread_body { () => { {
3045 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3046 let node_ref = NodePtr::from_node(&nodes[0]);
3048 let node_a = unsafe { &*node_ref.0 };
3049 while Instant::now() < end_time {
3050 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3051 // Ignore if we have any pending events, just always pretend we just got a
3052 // PendingHTLCsForwardable
3053 node_a.node.process_pending_htlc_forwards();
3057 let mut threads = Vec::new();
3058 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3060 // Back in the main thread, poll pending messages and make sure that we never have more than
3061 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3062 // there are HTLC messages shoved in while its running. This allows us to test that we never
3063 // generate an additional update_add_htlc until we've fully failed the first.
3064 let mut previously_failed_channels = Vec::new();
3066 assert_eq!(send_msg_events.len(), 1);
3067 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3068 assert_eq!(send_event.msgs.len(), 1);
3070 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3071 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3073 // Note that we only push one route into `expect_find_route` at a time, because that's all
3074 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3075 // we should still ultimately fail for the same reason - because we're trying to send too
3076 // many HTLCs at once.
3077 let mut new_route_params = route_params.clone();
3078 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3079 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3080 route.paths[0].hops[1].short_channel_id += 1;
3081 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3083 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3084 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3085 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3086 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3087 // This races with our other threads which may generate an add-HTLCs commitment update via
3088 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3089 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3090 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3091 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3093 let cur_time = Instant::now();
3094 if cur_time > end_time {
3095 for thread in threads.drain(..) { thread.join().unwrap(); }
3098 // Make sure we have some events to handle when we go around...
3099 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3100 nodes[0].node.process_pending_htlc_forwards();
3101 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3102 check_added_monitors!(nodes[0], 2);
3104 if cur_time > end_time {
3110 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
3111 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3112 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3113 // it was last persisted.
3114 let chanmon_cfgs = create_chanmon_cfgs(2);
3115 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3116 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3117 let (persister_a, persister_b, persister_c);
3118 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3119 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3120 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3122 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3124 let mut nodes_0_serialized = Vec::new();
3125 if !persist_manager_with_payment {
3126 nodes_0_serialized = nodes[0].node.encode();
3129 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3131 if persist_manager_with_payment {
3132 nodes_0_serialized = nodes[0].node.encode();
3135 nodes[1].node.claim_funds(our_payment_preimage);
3136 check_added_monitors!(nodes[1], 1);
3137 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3139 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3140 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3141 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3142 check_added_monitors!(nodes[0], 1);
3144 // The ChannelMonitor should always be the latest version, as we're required to persist it
3145 // during the commitment signed handling.
3146 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3147 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3149 let events = nodes[0].node.get_and_clear_pending_events();
3150 assert_eq!(events.len(), 2);
3151 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3152 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3153 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3154 // the double-claim that would otherwise appear at the end of this test.
3155 nodes[0].node.timer_tick_occurred();
3156 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3157 assert_eq!(as_broadcasted_txn.len(), 1);
3159 // Ensure that, even after some time, if we restart we still include *something* in the current
3160 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3161 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3162 // A naive implementation of the fix here would wipe the pending payments set, causing a
3163 // failure event when we restart.
3164 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3166 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3167 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);
3168 let events = nodes[0].node.get_and_clear_pending_events();
3169 assert!(events.is_empty());
3171 // Ensure that we don't generate any further events even after the channel-closing commitment
3172 // transaction is confirmed on-chain.
3173 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3174 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3176 let events = nodes[0].node.get_and_clear_pending_events();
3177 assert!(events.is_empty());
3179 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3180 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);
3181 let events = nodes[0].node.get_and_clear_pending_events();
3182 assert!(events.is_empty());
3183 check_added_monitors(&nodes[0], 1);
3187 fn no_missing_sent_on_midpoint_reload() {
3188 do_no_missing_sent_on_midpoint_reload(false);
3189 do_no_missing_sent_on_midpoint_reload(true);
3192 fn do_claim_from_closed_chan(fail_payment: bool) {
3193 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3194 // received had been closed between when the HTLC was received and when we went to claim it.
3195 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3196 // presumably the sender may retry later. Long ago it also reduced total code in the claim
3199 // However, this doesn't make sense if you're trying to do an atomic swap or some other
3200 // protocol that requires atomicity with some other action - if your money got claimed
3201 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3202 // is an over-optimization - there should be a very, very low likelihood that a channel closes
3203 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3204 // Since we now have code to handle this anyway we should allow it.
3206 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3207 // CLTVs on the paths to different value resulting in a different claim deadline.
3208 let chanmon_cfgs = create_chanmon_cfgs(4);
3209 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3210 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3211 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3213 create_announced_chan_between_nodes(&nodes, 0, 1);
3214 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3215 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3216 create_announced_chan_between_nodes(&nodes, 2, 3);
3218 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3219 let mut route_params = RouteParameters {
3220 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3221 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
3222 final_value_msat: 10_000_000,
3224 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3225 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3226 // Make sure the route is ordered as the B->D path before C->D
3227 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3228 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3230 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3231 // the HTLC is being relayed.
3232 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3233 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3234 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3236 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3237 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3238 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3239 check_added_monitors(&nodes[0], 2);
3240 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3241 send_msgs.sort_by(|a, _| {
3243 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3244 let node_b_id = nodes[1].node.get_our_node_id();
3245 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3248 assert_eq!(send_msgs.len(), 2);
3249 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3250 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3251 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3252 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3254 match receive_event.unwrap() {
3255 Event::PaymentClaimable { claim_deadline, .. } => {
3256 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3261 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3263 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3264 - if fail_payment { 0 } else { 2 });
3266 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3267 // and expire both immediately, though, by connecting another 4 blocks.
3268 let reason = HTLCDestination::FailedPayment { payment_hash };
3269 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3270 connect_blocks(&nodes[3], 4);
3271 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3272 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3274 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3275 check_closed_event!(&nodes[1], 1, ClosureReason::HolderForceClosed, false,
3276 [nodes[3].node.get_our_node_id()], 1000000);
3277 check_closed_broadcast(&nodes[1], 1, true);
3278 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3279 assert_eq!(bs_tx.len(), 1);
3281 mine_transaction(&nodes[3], &bs_tx[0]);
3282 check_added_monitors(&nodes[3], 1);
3283 check_closed_broadcast(&nodes[3], 1, true);
3284 check_closed_event!(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false,
3285 [nodes[1].node.get_our_node_id()], 1000000);
3287 nodes[3].node.claim_funds(payment_preimage);
3288 check_added_monitors(&nodes[3], 2);
3289 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3291 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3292 assert_eq!(ds_tx.len(), 1);
3293 check_spends!(&ds_tx[0], &bs_tx[0]);
3295 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3296 check_added_monitors(&nodes[1], 1);
3297 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3299 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3300 check_added_monitors(&nodes[1], 1);
3301 assert_eq!(bs_claims.len(), 1);
3302 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3303 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3304 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3305 } else { panic!(); }
3307 expect_payment_sent!(nodes[0], payment_preimage);
3309 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3310 assert_eq!(ds_claim_msgs.len(), 1);
3311 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3312 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3313 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3314 check_added_monitors(&nodes[2], 1);
3315 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3316 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3318 } else { panic!(); };
3320 assert_eq!(cs_claim_msgs.len(), 1);
3321 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3322 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3323 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3324 } else { panic!(); }
3326 expect_payment_path_successful!(nodes[0]);
3331 fn claim_from_closed_chan() {
3332 do_claim_from_closed_chan(true);
3333 do_claim_from_closed_chan(false);
3336 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3337 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3338 // another results in the HTLC being rejected.
3340 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3341 // first of which we'll deliver and the second of which we'll fail and then re-send with
3342 // modified payment metadata, which will in turn result in it being failed by the recipient.
3343 let chanmon_cfgs = create_chanmon_cfgs(4);
3344 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3345 let mut config = test_default_channel_config();
3346 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3347 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3350 let new_chain_monitor;
3351 let nodes_0_deserialized;
3353 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3355 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3356 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3357 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3358 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3360 // Pay more than half of each channel's max, requiring MPP
3361 let amt_msat = 750_000_000;
3362 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3363 let payment_id = PaymentId(payment_hash.0);
3364 let payment_metadata = vec![44, 49, 52, 142];
3366 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3367 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3368 let mut route_params = RouteParameters {
3370 final_value_msat: amt_msat,
3373 // Send the MPP payment, delivering the updated commitment state to nodes[1].
3374 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3375 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata),
3376 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3377 check_added_monitors!(nodes[0], 2);
3379 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3380 assert_eq!(send_events.len(), 2);
3381 let first_send = SendEvent::from_event(send_events.pop().unwrap());
3382 let second_send = SendEvent::from_event(send_events.pop().unwrap());
3384 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3385 (&first_send, &second_send)
3387 (&second_send, &first_send)
3389 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3390 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3392 expect_pending_htlcs_forwardable!(nodes[1]);
3393 check_added_monitors(&nodes[1], 1);
3394 let b_forward_ev = SendEvent::from_node(&nodes[1]);
3395 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3396 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3398 expect_pending_htlcs_forwardable!(nodes[3]);
3400 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3401 // will result in nodes[2] failing the HTLC back.
3402 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3403 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3405 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3406 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3408 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3409 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3410 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3412 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3413 assert_eq!(payment_fail_retryable_evs.len(), 2);
3414 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3415 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3417 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3418 // stored for our payment.
3420 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3423 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3424 // the payment state.
3426 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3427 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3428 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3429 persister, new_chain_monitor, nodes_0_deserialized);
3430 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3431 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
3433 let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
3434 reconnect_args.send_channel_ready = (true, true);
3435 reconnect_nodes(reconnect_args);
3437 // Create a new channel between C and D as A will refuse to retry on the existing one because
3439 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3441 // Now retry the failed HTLC.
3442 nodes[0].node.process_pending_htlc_forwards();
3443 check_added_monitors(&nodes[0], 1);
3444 let as_resend = SendEvent::from_node(&nodes[0]);
3445 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3446 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3448 expect_pending_htlcs_forwardable!(nodes[2]);
3449 check_added_monitors(&nodes[2], 1);
3450 let cs_forward = SendEvent::from_node(&nodes[2]);
3451 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3452 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3454 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3455 // the payment metadata was modified, failing only the one modified HTLC and retaining the
3458 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3459 nodes[3].node.process_pending_htlc_forwards();
3460 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3461 &[HTLCDestination::FailedPayment {payment_hash}]);
3462 nodes[3].node.process_pending_htlc_forwards();
3464 check_added_monitors(&nodes[3], 1);
3465 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3467 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3468 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3469 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3470 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3472 expect_pending_htlcs_forwardable!(nodes[3]);
3473 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3474 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3479 fn test_payment_metadata_consistency() {
3480 do_test_payment_metadata_consistency(true, true);
3481 do_test_payment_metadata_consistency(true, false);
3482 do_test_payment_metadata_consistency(false, true);
3483 do_test_payment_metadata_consistency(false, false);