1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test the payment retry logic in ChannelManager, including various edge-cases around
11 //! serialization ordering between ChannelManager/ChannelMonitors and ensuring we can still retry
12 //! payments thereafter.
14 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
15 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::sign::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason, PaymentPurpose};
19 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
20 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, 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_keysend_payments() {
241 do_test_keysend_payments(false, false);
242 do_test_keysend_payments(false, true);
243 do_test_keysend_payments(true, false);
244 do_test_keysend_payments(true, true);
247 fn do_test_keysend_payments(public_node: bool, with_retry: bool) {
248 let chanmon_cfgs = create_chanmon_cfgs(2);
249 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
250 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
251 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
254 create_announced_chan_between_nodes(&nodes, 0, 1);
256 create_chan_between_nodes(&nodes[0], &nodes[1]);
258 let payer_pubkey = nodes[0].node.get_our_node_id();
259 let payee_pubkey = nodes[1].node.get_our_node_id();
260 let route_params = RouteParameters {
261 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
262 final_value_msat: 10000,
265 let network_graph = nodes[0].network_graph.clone();
266 let channels = nodes[0].node.list_usable_channels();
267 let first_hops = channels.iter().collect::<Vec<_>>();
268 let first_hops = if public_node { None } else { Some(first_hops.as_slice()) };
270 let scorer = test_utils::TestScorer::new();
271 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
272 let route = find_route(
273 &payer_pubkey, &route_params, &network_graph, first_hops,
274 nodes[0].logger, &scorer, &(), &random_seed_bytes
278 let test_preimage = PaymentPreimage([42; 32]);
280 nodes[0].node.send_spontaneous_payment_with_retry(Some(test_preimage),
281 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0),
282 route_params, Retry::Attempts(1)).unwrap()
284 nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
285 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap()
288 check_added_monitors!(nodes[0], 1);
289 let send_event = SendEvent::from_node(&nodes[0]);
290 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
291 do_commitment_signed_dance(&nodes[1], &nodes[0], &send_event.commitment_msg, false, false);
292 expect_pending_htlcs_forwardable!(nodes[1]);
293 // Previously, a refactor caused us to stop including the payment preimage in the onion which
294 // is sent as a part of keysend payments. Thus, to be extra careful here, we scope the preimage
295 // above to demonstrate that we have no way to get the preimage at this point except by
296 // extracting it from the onion nodes[1] received.
297 let event = nodes[1].node.get_and_clear_pending_events();
298 assert_eq!(event.len(), 1);
299 if let Event::PaymentClaimable { purpose: PaymentPurpose::SpontaneousPayment(preimage), .. } = event[0] {
300 claim_payment(&nodes[0], &[&nodes[1]], preimage);
305 fn test_mpp_keysend() {
306 let mut mpp_keysend_config = test_default_channel_config();
307 mpp_keysend_config.accept_mpp_keysend = true;
308 let chanmon_cfgs = create_chanmon_cfgs(4);
309 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
310 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
311 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
313 create_announced_chan_between_nodes(&nodes, 0, 1);
314 create_announced_chan_between_nodes(&nodes, 0, 2);
315 create_announced_chan_between_nodes(&nodes, 1, 3);
316 create_announced_chan_between_nodes(&nodes, 2, 3);
317 let network_graph = nodes[0].network_graph.clone();
319 let payer_pubkey = nodes[0].node.get_our_node_id();
320 let payee_pubkey = nodes[3].node.get_our_node_id();
321 let recv_value = 15_000_000;
322 let route_params = RouteParameters {
323 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, true),
324 final_value_msat: recv_value,
326 let scorer = test_utils::TestScorer::new();
327 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
328 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger,
329 &scorer, &(), &random_seed_bytes).unwrap();
331 let payment_preimage = PaymentPreimage([42; 32]);
332 let payment_secret = PaymentSecret(payment_preimage.0);
333 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
334 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_preimage.0)).unwrap();
335 check_added_monitors!(nodes[0], 2);
337 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
338 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
339 assert_eq!(events.len(), 2);
341 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
342 pass_along_path(&nodes[0], expected_route[0], recv_value, payment_hash.clone(),
343 Some(payment_secret), ev.clone(), false, Some(payment_preimage));
345 let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
346 pass_along_path(&nodes[0], expected_route[1], recv_value, payment_hash.clone(),
347 Some(payment_secret), ev.clone(), true, Some(payment_preimage));
348 claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
352 fn test_reject_mpp_keysend_htlc() {
353 // This test enforces that we reject MPP keysend HTLCs if our config states we don't support
354 // MPP keysend. When receiving a payment, if we don't support MPP keysend we'll reject the
355 // payment if it's keysend and has a payment secret, never reaching our payment validation
356 // logic. To check that we enforce rejecting MPP keysends in our payment logic, here we send
357 // keysend payments without payment secrets, then modify them by adding payment secrets in the
358 // final node in between receiving the HTLCs and actually processing them.
359 let mut reject_mpp_keysend_cfg = test_default_channel_config();
360 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
362 let chanmon_cfgs = create_chanmon_cfgs(4);
363 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
364 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(reject_mpp_keysend_cfg)]);
365 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
366 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
367 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
368 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
369 let (update_a, _, chan_4_channel_id, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
370 let chan_4_id = update_a.contents.short_channel_id;
372 let (mut route, payment_hash, payment_preimage, _) = get_route_and_payment_hash!(nodes[0], nodes[3], amount);
374 // Pay along nodes[1]
375 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
376 route.paths[0].hops[0].short_channel_id = chan_1_id;
377 route.paths[0].hops[1].short_channel_id = chan_3_id;
379 let payment_id_0 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
380 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_0).unwrap();
381 check_added_monitors!(nodes[0], 1);
383 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
384 let update_add_0 = update_0.update_add_htlcs[0].clone();
385 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
386 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
387 expect_pending_htlcs_forwardable!(nodes[1]);
389 check_added_monitors!(&nodes[1], 1);
390 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[3].node.get_our_node_id());
391 let update_add_1 = update_1.update_add_htlcs[0].clone();
392 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
393 commitment_signed_dance!(nodes[3], nodes[1], update_1.commitment_signed, false, true);
395 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
396 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
397 for f in pending_forwards.iter_mut() {
399 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
400 match forward_info.routing {
401 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
402 *payment_data = Some(msgs::FinalOnionHopData {
403 payment_secret: PaymentSecret([42; 32]),
404 total_msat: amount * 2,
407 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
414 expect_pending_htlcs_forwardable!(nodes[3]);
416 // Pay along nodes[2]
417 route.paths[0].hops[0].pubkey = nodes[2].node.get_our_node_id();
418 route.paths[0].hops[0].short_channel_id = chan_2_id;
419 route.paths[0].hops[1].short_channel_id = chan_4_id;
421 let payment_id_1 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
422 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
423 check_added_monitors!(nodes[0], 1);
425 let update_2 = get_htlc_update_msgs!(nodes[0], nodes[2].node.get_our_node_id());
426 let update_add_2 = update_2.update_add_htlcs[0].clone();
427 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_2);
428 commitment_signed_dance!(nodes[2], nodes[0], &update_2.commitment_signed, false, true);
429 expect_pending_htlcs_forwardable!(nodes[2]);
431 check_added_monitors!(&nodes[2], 1);
432 let update_3 = get_htlc_update_msgs!(nodes[2], nodes[3].node.get_our_node_id());
433 let update_add_3 = update_3.update_add_htlcs[0].clone();
434 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &update_add_3);
435 commitment_signed_dance!(nodes[3], nodes[2], update_3.commitment_signed, false, true);
437 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
438 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
439 for f in pending_forwards.iter_mut() {
441 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
442 match forward_info.routing {
443 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
444 *payment_data = Some(msgs::FinalOnionHopData {
445 payment_secret: PaymentSecret([42; 32]),
446 total_msat: amount * 2,
449 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
456 expect_pending_htlcs_forwardable!(nodes[3]);
457 check_added_monitors!(nodes[3], 1);
459 // Fail back along nodes[2]
460 let update_fail_0 = get_htlc_update_msgs!(&nodes[3], &nodes[2].node.get_our_node_id());
461 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &update_fail_0.update_fail_htlcs[0]);
462 commitment_signed_dance!(nodes[2], nodes[3], update_fail_0.commitment_signed, false);
463 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 }]);
464 check_added_monitors!(nodes[2], 1);
466 let update_fail_1 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
467 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_1.update_fail_htlcs[0]);
468 commitment_signed_dance!(nodes[0], nodes[2], update_fail_1.commitment_signed, false);
470 expect_payment_failed_conditions(&nodes[0], payment_hash, true, PaymentFailedConditions::new());
471 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
476 fn no_pending_leak_on_initial_send_failure() {
477 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
478 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
479 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
480 // pending payment forever and never time it out.
481 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
482 // try, and then check that no pending payment is being tracked.
483 let chanmon_cfgs = create_chanmon_cfgs(2);
484 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
485 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
486 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
488 create_announced_chan_between_nodes(&nodes, 0, 1);
490 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
492 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
493 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
495 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
496 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
497 ), true, APIError::ChannelUnavailable { ref err },
498 assert_eq!(err, "Peer for first hop currently disconnected"));
500 assert!(!nodes[0].node.has_pending_payments());
503 fn do_retry_with_no_persist(confirm_before_reload: bool) {
504 // If we send a pending payment and `send_payment` returns success, we should always either
505 // return a payment failure event or a payment success event, and on failure the payment should
508 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
509 // always persisted asynchronously), the ChannelManager has to reload some payment data from
510 // ChannelMonitor(s) in some cases. This tests that reloading.
512 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
513 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
514 // which has separate codepaths for "commitment transaction already confirmed" and not.
515 let chanmon_cfgs = create_chanmon_cfgs(3);
516 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
518 let new_chain_monitor;
519 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
520 let nodes_0_deserialized;
521 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
523 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
524 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
526 // Serialize the ChannelManager prior to sending payments
527 let nodes_0_serialized = nodes[0].node.encode();
529 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
531 let amt_msat = 1_000_000;
532 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
533 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
534 let route_params = RouteParameters {
535 payment_params: route.payment_params.clone().unwrap(),
536 final_value_msat: amt_msat,
538 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
539 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
540 check_added_monitors!(nodes[0], 1);
542 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
543 assert_eq!(events.len(), 1);
544 let payment_event = SendEvent::from_event(events.pop().unwrap());
545 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
547 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
548 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
549 // which would prevent retry.
550 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
551 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
553 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
554 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
555 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
556 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
558 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
560 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
561 if confirm_before_reload {
562 mine_transaction(&nodes[0], &as_commitment_tx);
563 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
566 // The ChannelMonitor should always be the latest version, as we're required to persist it
567 // during the `commitment_signed_dance!()`.
568 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
569 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
571 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
572 // force-close the channel.
573 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
574 assert!(nodes[0].node.list_channels().is_empty());
575 assert!(nodes[0].node.has_pending_payments());
576 nodes[0].node.timer_tick_occurred();
577 if !confirm_before_reload {
578 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
579 assert_eq!(as_broadcasted_txn.len(), 1);
580 assert_eq!(as_broadcasted_txn[0].txid(), as_commitment_tx.txid());
582 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
584 check_added_monitors!(nodes[0], 1);
586 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
587 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
588 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
590 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
592 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
593 // error, as the channel has hit the chain.
594 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
595 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
597 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
598 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
599 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
600 assert_eq!(as_err.len(), 1);
602 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
603 assert_eq!(node_id, nodes[1].node.get_our_node_id());
604 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
605 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 {}",
606 &nodes[1].node.get_our_node_id())) }, [nodes[0].node.get_our_node_id()], 100000);
607 check_added_monitors!(nodes[1], 1);
608 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
610 _ => panic!("Unexpected event"),
612 check_closed_broadcast!(nodes[1], false);
614 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
615 // we close in a moment.
616 nodes[2].node.claim_funds(payment_preimage_1);
617 check_added_monitors!(nodes[2], 1);
618 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
620 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
621 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
622 check_added_monitors!(nodes[1], 1);
623 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
624 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
626 if confirm_before_reload {
627 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
628 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
631 // Create a new channel on which to retry the payment before we fail the payment via the
632 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
633 // connecting several blocks while creating the channel (implying time has passed).
634 create_announced_chan_between_nodes(&nodes, 0, 1);
635 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
637 mine_transaction(&nodes[1], &as_commitment_tx);
638 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
639 assert_eq!(bs_htlc_claim_txn.len(), 1);
640 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
642 if !confirm_before_reload {
643 mine_transaction(&nodes[0], &as_commitment_tx);
645 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
646 expect_payment_sent(&nodes[0], payment_preimage_1, None, true, false);
647 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
648 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
649 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
650 assert_eq!(txn.len(), 2);
651 (txn.remove(0), txn.remove(0))
653 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
654 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
655 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
656 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
658 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
660 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
661 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
663 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
664 // reloaded) via a route over the new channel, which work without issue and eventually be
665 // received and claimed at the recipient just like any other payment.
666 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
668 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
669 // and not the original fee. We also update node[1]'s relevant config as
670 // do_claim_payment_along_route expects us to never overpay.
672 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
673 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
674 .unwrap().lock().unwrap();
675 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
676 let mut new_config = channel.context.config();
677 new_config.forwarding_fee_base_msat += 100_000;
678 channel.context.update_config(&new_config);
679 new_route.paths[0].hops[0].fee_msat += 100_000;
682 // Force expiration of the channel's previous config.
683 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
684 nodes[1].node.timer_tick_occurred();
687 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
688 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
689 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
690 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
691 check_added_monitors!(nodes[0], 1);
692 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
693 assert_eq!(events.len(), 1);
694 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
695 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
696 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
700 fn retry_with_no_persist() {
701 do_retry_with_no_persist(true);
702 do_retry_with_no_persist(false);
705 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
706 // Test that an off-chain completed payment is not retryable on restart. This was previously
707 // broken for dust payments, but we test for both dust and non-dust payments.
709 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
711 let chanmon_cfgs = create_chanmon_cfgs(3);
712 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
714 let mut manually_accept_config = test_default_channel_config();
715 manually_accept_config.manually_accept_inbound_channels = true;
718 let first_new_chain_monitor;
719 let second_persister;
720 let second_new_chain_monitor;
722 let third_new_chain_monitor;
724 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
725 let first_nodes_0_deserialized;
726 let second_nodes_0_deserialized;
727 let third_nodes_0_deserialized;
729 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
731 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
732 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
733 confirm_transaction(&nodes[0], &funding_tx);
734 confirm_transaction(&nodes[1], &funding_tx);
735 // Ignore the announcement_signatures messages
736 nodes[0].node.get_and_clear_pending_msg_events();
737 nodes[1].node.get_and_clear_pending_msg_events();
738 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
740 // Serialize the ChannelManager prior to sending payments
741 let mut nodes_0_serialized = nodes[0].node.encode();
743 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
744 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 });
746 // The ChannelMonitor should always be the latest version, as we're required to persist it
747 // during the `commitment_signed_dance!()`.
748 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
750 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);
751 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
753 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
754 // force-close the channel.
755 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
756 nodes[0].node.timer_tick_occurred();
757 assert!(nodes[0].node.list_channels().is_empty());
758 assert!(nodes[0].node.has_pending_payments());
759 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
760 check_added_monitors!(nodes[0], 1);
762 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
763 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
765 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
767 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
768 // error, as the channel has hit the chain.
769 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
770 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
772 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
773 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
774 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
775 assert_eq!(as_err.len(), 1);
776 let bs_commitment_tx;
778 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
779 assert_eq!(node_id, nodes[1].node.get_our_node_id());
780 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
781 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())) }
782 , [nodes[0].node.get_our_node_id()], 100000);
783 check_added_monitors!(nodes[1], 1);
784 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
786 _ => panic!("Unexpected event"),
788 check_closed_broadcast!(nodes[1], false);
790 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
791 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
792 // incoming HTLCs with the same payment hash later.
793 nodes[2].node.fail_htlc_backwards(&payment_hash);
794 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
795 check_added_monitors!(nodes[2], 1);
797 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
798 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
799 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
800 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
801 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
803 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
804 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
805 // after the commitment transaction, so always connect the commitment transaction.
806 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
807 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
809 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
810 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
811 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
812 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
813 assert_eq!(as_htlc_timeout.len(), 1);
815 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
816 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
817 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
818 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
821 // Create a new channel on which to retry the payment before we fail the payment via the
822 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
823 // connecting several blocks while creating the channel (implying time has passed).
824 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
825 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
826 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
828 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
829 // confirming, we will fail as it's considered still-pending...
830 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
831 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
832 Err(PaymentSendFailure::DuplicatePayment) => {},
833 _ => panic!("Unexpected error")
835 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
837 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
838 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
839 // (which should also still work).
840 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
841 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
842 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
844 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
845 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
846 nodes_0_serialized = nodes[0].node.encode();
848 // After the payment failed, we're free to send it again.
849 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
850 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
851 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
853 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);
854 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
856 nodes[0].node.test_process_background_events();
857 check_added_monitors(&nodes[0], 1);
859 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
860 reconnect_args.send_channel_ready = (true, true);
861 reconnect_nodes(reconnect_args);
863 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
864 // the payment is not (spuriously) listed as still pending.
865 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
866 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
867 check_added_monitors!(nodes[0], 1);
868 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
869 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
871 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
872 Err(PaymentSendFailure::DuplicatePayment) => {},
873 _ => panic!("Unexpected error")
875 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
877 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
878 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
879 nodes_0_serialized = nodes[0].node.encode();
881 // Check that after reload we can send the payment again (though we shouldn't, since it was
882 // claimed previously).
883 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);
884 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
886 nodes[0].node.test_process_background_events();
887 check_added_monitors(&nodes[0], 1);
889 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
891 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
892 Err(PaymentSendFailure::DuplicatePayment) => {},
893 _ => panic!("Unexpected error")
895 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
899 fn test_completed_payment_not_retryable_on_reload() {
900 do_test_completed_payment_not_retryable_on_reload(true);
901 do_test_completed_payment_not_retryable_on_reload(false);
905 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
906 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
907 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
908 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
909 // the ChannelMonitor tells it to.
911 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
912 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
913 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
914 let chanmon_cfgs = create_chanmon_cfgs(2);
915 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
917 let new_chain_monitor;
918 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
919 let nodes_0_deserialized;
920 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
922 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
924 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
926 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
927 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
928 check_closed_broadcast!(nodes[0], true);
929 check_added_monitors!(nodes[0], 1);
930 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
932 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
933 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
935 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
936 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
937 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
938 assert_eq!(node_txn.len(), 3);
939 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
940 check_spends!(node_txn[1], funding_tx);
941 check_spends!(node_txn[2], node_txn[1]);
942 let timeout_txn = vec![node_txn[2].clone()];
944 nodes[1].node.claim_funds(payment_preimage);
945 check_added_monitors!(nodes[1], 1);
946 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
948 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[1].clone()]));
949 check_closed_broadcast!(nodes[1], true);
950 check_added_monitors!(nodes[1], 1);
951 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
952 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
953 assert_eq!(claim_txn.len(), 1);
954 check_spends!(claim_txn[0], node_txn[1]);
956 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[1].clone()]));
958 if confirm_commitment_tx {
959 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
962 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] });
965 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
966 connect_block(&nodes[0], &claim_block);
967 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
970 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
971 // returning InProgress. This should cause the claim event to never make its way to the
973 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
974 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
977 connect_blocks(&nodes[0], 1);
979 connect_block(&nodes[0], &claim_block);
982 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
983 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
984 .get_mut(&funding_txo).unwrap().drain().collect();
985 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
986 // If we're testing connection idempotency we may get substantially more.
987 assert!(mon_updates.len() >= 1);
988 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
989 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
991 // If we persist the ChannelManager here, we should get the PaymentSent event after
993 let mut chan_manager_serialized = Vec::new();
994 if !persist_manager_post_event {
995 chan_manager_serialized = nodes[0].node.encode();
998 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
999 // payment sent event.
1000 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1001 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1002 for update in mon_updates {
1003 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
1005 if payment_timeout {
1006 expect_payment_failed!(nodes[0], payment_hash, false);
1008 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1011 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
1013 if persist_manager_post_event {
1014 chan_manager_serialized = nodes[0].node.encode();
1017 // Now reload nodes[0]...
1018 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
1020 if persist_manager_post_event {
1021 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1022 } else if payment_timeout {
1023 expect_payment_failed!(nodes[0], payment_hash, false);
1025 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1028 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
1029 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
1030 // payment events should kick in, leaving us with no pending events here.
1031 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
1032 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
1033 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1034 check_added_monitors(&nodes[0], 1);
1038 fn test_dup_htlc_onchain_fails_on_reload() {
1039 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
1040 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
1041 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
1042 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
1043 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
1044 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
1048 fn test_fulfill_restart_failure() {
1049 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
1050 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
1051 // again, or fail it, giving us free money.
1053 // Of course probably they won't fail it and give us free money, but because we have code to
1054 // handle it, we should test the logic for it anyway. We do that here.
1055 let chanmon_cfgs = create_chanmon_cfgs(2);
1056 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1058 let new_chain_monitor;
1059 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1060 let nodes_1_deserialized;
1061 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1063 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1064 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
1066 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
1067 // pre-fulfill, which we do by serializing it here.
1068 let chan_manager_serialized = nodes[1].node.encode();
1069 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1071 nodes[1].node.claim_funds(payment_preimage);
1072 check_added_monitors!(nodes[1], 1);
1073 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1075 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1076 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1077 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
1079 // Now reload nodes[1]...
1080 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1082 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1083 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1085 nodes[1].node.fail_htlc_backwards(&payment_hash);
1086 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1087 check_added_monitors!(nodes[1], 1);
1088 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1089 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1090 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1091 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1092 // it had already considered the payment fulfilled, and now they just got free money.
1093 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1097 fn get_ldk_payment_preimage() {
1098 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1099 let chanmon_cfgs = create_chanmon_cfgs(2);
1100 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1101 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1102 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1103 create_announced_chan_between_nodes(&nodes, 0, 1);
1105 let amt_msat = 60_000;
1106 let expiry_secs = 60 * 60;
1107 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1109 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1110 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
1111 let scorer = test_utils::TestScorer::new();
1112 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1113 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1114 let route = get_route(
1115 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
1116 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
1117 amt_msat, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
1118 nodes[0].node.send_payment_with_route(&route, payment_hash,
1119 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1120 check_added_monitors!(nodes[0], 1);
1122 // Make sure to use `get_payment_preimage`
1123 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1124 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1125 assert_eq!(events.len(), 1);
1126 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1127 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1131 fn sent_probe_is_probe_of_sending_node() {
1132 let chanmon_cfgs = create_chanmon_cfgs(3);
1133 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1134 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1135 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1137 create_announced_chan_between_nodes(&nodes, 0, 1);
1138 create_announced_chan_between_nodes(&nodes, 1, 2);
1140 // First check we refuse to build a single-hop probe
1141 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1142 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1144 // Then build an actual two-hop probing path
1145 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1147 match nodes[0].node.send_probe(route.paths[0].clone()) {
1148 Ok((payment_hash, payment_id)) => {
1149 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1150 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1151 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1156 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1157 check_added_monitors!(nodes[0], 1);
1161 fn successful_probe_yields_event() {
1162 let chanmon_cfgs = create_chanmon_cfgs(3);
1163 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1164 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1165 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1167 create_announced_chan_between_nodes(&nodes, 0, 1);
1168 create_announced_chan_between_nodes(&nodes, 1, 2);
1170 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1172 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1174 // node[0] -- update_add_htlcs -> node[1]
1175 check_added_monitors!(nodes[0], 1);
1176 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1177 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1178 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1179 check_added_monitors!(nodes[1], 0);
1180 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1181 expect_pending_htlcs_forwardable!(nodes[1]);
1183 // node[1] -- update_add_htlcs -> node[2]
1184 check_added_monitors!(nodes[1], 1);
1185 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1186 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1187 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1188 check_added_monitors!(nodes[2], 0);
1189 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
1191 // node[1] <- update_fail_htlcs -- node[2]
1192 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1193 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1194 check_added_monitors!(nodes[1], 0);
1195 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1197 // node[0] <- update_fail_htlcs -- node[1]
1198 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1199 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1200 check_added_monitors!(nodes[0], 0);
1201 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1203 let mut events = nodes[0].node.get_and_clear_pending_events();
1204 assert_eq!(events.len(), 1);
1205 match events.drain(..).next().unwrap() {
1206 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1207 assert_eq!(payment_id, ev_pid);
1208 assert_eq!(payment_hash, ev_ph);
1212 assert!(!nodes[0].node.has_pending_payments());
1216 fn failed_probe_yields_event() {
1217 let chanmon_cfgs = create_chanmon_cfgs(3);
1218 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1219 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1220 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1222 create_announced_chan_between_nodes(&nodes, 0, 1);
1223 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1225 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1227 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000);
1229 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1231 // node[0] -- update_add_htlcs -> node[1]
1232 check_added_monitors!(nodes[0], 1);
1233 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1234 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1235 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1236 check_added_monitors!(nodes[1], 0);
1237 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1238 expect_pending_htlcs_forwardable!(nodes[1]);
1240 // node[0] <- update_fail_htlcs -- node[1]
1241 check_added_monitors!(nodes[1], 1);
1242 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1243 // Skip the PendingHTLCsForwardable event
1244 let _events = nodes[1].node.get_and_clear_pending_events();
1245 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1246 check_added_monitors!(nodes[0], 0);
1247 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1249 let mut events = nodes[0].node.get_and_clear_pending_events();
1250 assert_eq!(events.len(), 1);
1251 match events.drain(..).next().unwrap() {
1252 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1253 assert_eq!(payment_id, ev_pid);
1254 assert_eq!(payment_hash, ev_ph);
1258 assert!(!nodes[0].node.has_pending_payments());
1262 fn onchain_failed_probe_yields_event() {
1263 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1265 let chanmon_cfgs = create_chanmon_cfgs(3);
1266 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1267 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1268 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1270 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1271 create_announced_chan_between_nodes(&nodes, 1, 2);
1273 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1275 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1276 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000);
1277 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1279 // node[0] -- update_add_htlcs -> node[1]
1280 check_added_monitors!(nodes[0], 1);
1281 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1282 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1283 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1284 check_added_monitors!(nodes[1], 0);
1285 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1286 expect_pending_htlcs_forwardable!(nodes[1]);
1288 check_added_monitors!(nodes[1], 1);
1289 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1291 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1292 // Node A, which after 6 confirmations should result in a probe failure event.
1293 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1294 confirm_transaction(&nodes[0], &bs_txn[0]);
1295 check_closed_broadcast!(&nodes[0], true);
1296 check_added_monitors!(nodes[0], 1);
1298 let mut events = nodes[0].node.get_and_clear_pending_events();
1299 assert_eq!(events.len(), 2);
1300 let mut found_probe_failed = false;
1301 for event in events.drain(..) {
1303 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1304 assert_eq!(payment_id, ev_pid);
1305 assert_eq!(payment_hash, ev_ph);
1306 found_probe_failed = true;
1308 Event::ChannelClosed { .. } => {},
1312 assert!(found_probe_failed);
1313 assert!(!nodes[0].node.has_pending_payments());
1317 fn claimed_send_payment_idempotent() {
1318 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1319 let chanmon_cfgs = create_chanmon_cfgs(2);
1320 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1321 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1322 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1324 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1326 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1327 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1329 macro_rules! check_send_rejected {
1331 // If we try to resend a new payment with a different payment_hash but with the same
1332 // payment_id, it should be rejected.
1333 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1334 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1336 Err(PaymentSendFailure::DuplicatePayment) => {},
1337 _ => panic!("Unexpected send result: {:?}", send_result),
1340 // Further, if we try to send a spontaneous payment with the same payment_id it should
1341 // also be rejected.
1342 let send_result = nodes[0].node.send_spontaneous_payment(
1343 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1345 Err(PaymentSendFailure::DuplicatePayment) => {},
1346 _ => panic!("Unexpected send result: {:?}", send_result),
1351 check_send_rejected!();
1353 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1354 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1355 // we must remain just as idempotent as we were before.
1356 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1358 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1359 nodes[0].node.timer_tick_occurred();
1362 check_send_rejected!();
1364 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1365 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1366 // the payment complete. However, they could have called `send_payment` while the event was
1367 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1368 // after the event is handled a duplicate payment should sitll be rejected.
1369 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1370 check_send_rejected!();
1372 // If relatively little time has passed, a duplicate payment should still fail.
1373 nodes[0].node.timer_tick_occurred();
1374 check_send_rejected!();
1376 // However, after some time has passed (at least more than the one timer tick above), a
1377 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1378 // references to the old payment data.
1379 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1380 nodes[0].node.timer_tick_occurred();
1383 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1384 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1385 check_added_monitors!(nodes[0], 1);
1386 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1387 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1391 fn abandoned_send_payment_idempotent() {
1392 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1394 let chanmon_cfgs = create_chanmon_cfgs(2);
1395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1396 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1397 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1399 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1401 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1402 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1404 macro_rules! check_send_rejected {
1406 // If we try to resend a new payment with a different payment_hash but with the same
1407 // payment_id, it should be rejected.
1408 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1409 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1411 Err(PaymentSendFailure::DuplicatePayment) => {},
1412 _ => panic!("Unexpected send result: {:?}", send_result),
1415 // Further, if we try to send a spontaneous payment with the same payment_id it should
1416 // also be rejected.
1417 let send_result = nodes[0].node.send_spontaneous_payment(
1418 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1420 Err(PaymentSendFailure::DuplicatePayment) => {},
1421 _ => panic!("Unexpected send result: {:?}", send_result),
1426 check_send_rejected!();
1428 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1429 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1431 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1433 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1434 nodes[0].node.timer_tick_occurred();
1436 check_send_rejected!();
1438 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1440 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1441 // failed payment back.
1442 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1443 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1444 check_added_monitors!(nodes[0], 1);
1445 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1446 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1449 #[derive(PartialEq)]
1450 enum InterceptTest {
1457 fn test_trivial_inflight_htlc_tracking(){
1458 // In this test, we test three scenarios:
1459 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1460 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1461 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1462 let chanmon_cfgs = create_chanmon_cfgs(3);
1463 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1464 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1465 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1467 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1468 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1470 // Send and claim the payment. Inflight HTLCs should be empty.
1471 let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1472 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1474 let mut node_0_per_peer_lock;
1475 let mut node_0_peer_state_lock;
1476 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1478 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1479 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1480 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1481 channel_1.context.get_short_channel_id().unwrap()
1483 assert_eq!(chan_1_used_liquidity, None);
1486 let mut node_1_per_peer_lock;
1487 let mut node_1_peer_state_lock;
1488 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1490 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1491 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1492 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1493 channel_2.context.get_short_channel_id().unwrap()
1496 assert_eq!(chan_2_used_liquidity, None);
1498 let pending_payments = nodes[0].node.list_recent_payments();
1499 assert_eq!(pending_payments.len(), 1);
1500 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1502 // Remove fulfilled payment
1503 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1504 nodes[0].node.timer_tick_occurred();
1507 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1508 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1509 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1511 let mut node_0_per_peer_lock;
1512 let mut node_0_peer_state_lock;
1513 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1515 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1516 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1517 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1518 channel_1.context.get_short_channel_id().unwrap()
1520 // First hop accounts for expected 1000 msat fee
1521 assert_eq!(chan_1_used_liquidity, Some(501000));
1524 let mut node_1_per_peer_lock;
1525 let mut node_1_peer_state_lock;
1526 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1528 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1529 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1530 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1531 channel_2.context.get_short_channel_id().unwrap()
1534 assert_eq!(chan_2_used_liquidity, Some(500000));
1536 let pending_payments = nodes[0].node.list_recent_payments();
1537 assert_eq!(pending_payments.len(), 1);
1538 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1540 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1541 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1543 // Remove fulfilled payment
1544 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1545 nodes[0].node.timer_tick_occurred();
1548 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1550 let mut node_0_per_peer_lock;
1551 let mut node_0_peer_state_lock;
1552 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1554 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1555 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1556 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1557 channel_1.context.get_short_channel_id().unwrap()
1559 assert_eq!(chan_1_used_liquidity, None);
1562 let mut node_1_per_peer_lock;
1563 let mut node_1_peer_state_lock;
1564 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1566 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1567 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1568 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1569 channel_2.context.get_short_channel_id().unwrap()
1571 assert_eq!(chan_2_used_liquidity, None);
1574 let pending_payments = nodes[0].node.list_recent_payments();
1575 assert_eq!(pending_payments.len(), 0);
1579 fn test_holding_cell_inflight_htlcs() {
1580 let chanmon_cfgs = create_chanmon_cfgs(2);
1581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1583 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1584 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1586 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1587 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1589 // Queue up two payments - one will be delivered right away, one immediately goes into the
1590 // holding cell as nodes[0] is AwaitingRAA.
1592 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1593 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1594 check_added_monitors!(nodes[0], 1);
1595 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1596 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1597 check_added_monitors!(nodes[0], 0);
1600 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1603 let mut node_0_per_peer_lock;
1604 let mut node_0_peer_state_lock;
1605 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1607 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1608 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1609 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1610 channel.context.get_short_channel_id().unwrap()
1613 assert_eq!(used_liquidity, Some(2000000));
1616 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1617 nodes[0].node.get_and_clear_pending_msg_events();
1621 fn intercepted_payment() {
1622 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1623 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1624 // payment or (b) fail the payment.
1625 do_test_intercepted_payment(InterceptTest::Forward);
1626 do_test_intercepted_payment(InterceptTest::Fail);
1627 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1628 do_test_intercepted_payment(InterceptTest::Timeout);
1631 fn do_test_intercepted_payment(test: InterceptTest) {
1632 let chanmon_cfgs = create_chanmon_cfgs(3);
1633 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1635 let mut zero_conf_chan_config = test_default_channel_config();
1636 zero_conf_chan_config.manually_accept_inbound_channels = true;
1637 let mut intercept_forwards_config = test_default_channel_config();
1638 intercept_forwards_config.accept_intercept_htlcs = true;
1639 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1641 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1642 let scorer = test_utils::TestScorer::new();
1643 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1645 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1647 let amt_msat = 100_000;
1648 let intercept_scid = nodes[1].node.get_intercept_scid();
1649 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1650 .with_route_hints(vec![
1651 RouteHint(vec![RouteHintHop {
1652 src_node_id: nodes[1].node.get_our_node_id(),
1653 short_channel_id: intercept_scid,
1656 proportional_millionths: 0,
1658 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1659 htlc_minimum_msat: None,
1660 htlc_maximum_msat: None,
1663 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1664 let route_params = RouteParameters {
1666 final_value_msat: amt_msat,
1668 let route = get_route(
1669 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1670 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1671 nodes[0].logger, &scorer, &(), &random_seed_bytes,
1674 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1675 nodes[0].node.send_payment_with_route(&route, payment_hash,
1676 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1677 let payment_event = {
1679 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1680 assert_eq!(added_monitors.len(), 1);
1681 added_monitors.clear();
1683 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1684 assert_eq!(events.len(), 1);
1685 SendEvent::from_event(events.remove(0))
1687 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1688 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1690 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1691 let events = nodes[1].node.get_and_clear_pending_events();
1692 assert_eq!(events.len(), 1);
1693 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1694 crate::events::Event::HTLCIntercepted {
1695 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1697 assert_eq!(pmt_hash, payment_hash);
1698 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1699 assert_eq!(short_channel_id, intercept_scid);
1700 (intercept_id, expected_outbound_amount_msat)
1705 // Check for unknown channel id error.
1706 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();
1707 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable {
1708 err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1709 log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1711 if test == InterceptTest::Fail {
1712 // Ensure we can fail the intercepted payment back.
1713 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1714 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1715 nodes[1].node.process_pending_htlc_forwards();
1716 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1717 check_added_monitors!(&nodes[1], 1);
1718 assert!(update_fail.update_fail_htlcs.len() == 1);
1719 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1720 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1721 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1723 // Ensure the payment fails with the expected error.
1724 let fail_conditions = PaymentFailedConditions::new()
1725 .blamed_scid(intercept_scid)
1726 .blamed_chan_closed(true)
1727 .expected_htlc_error_data(0x4000 | 10, &[]);
1728 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1729 } else if test == InterceptTest::Forward {
1730 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1731 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1732 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();
1733 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1734 err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1735 log_bytes!(temp_chan_id), nodes[2].node.get_our_node_id()) });
1736 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1738 // Open the just-in-time channel so the payment can then be forwarded.
1739 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1741 // Finally, forward the intercepted payment through and claim it.
1742 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1743 expect_pending_htlcs_forwardable!(nodes[1]);
1745 let payment_event = {
1747 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1748 assert_eq!(added_monitors.len(), 1);
1749 added_monitors.clear();
1751 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1752 assert_eq!(events.len(), 1);
1753 SendEvent::from_event(events.remove(0))
1755 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1756 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1757 expect_pending_htlcs_forwardable!(nodes[2]);
1759 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1760 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1761 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1762 let events = nodes[0].node.get_and_clear_pending_events();
1763 assert_eq!(events.len(), 2);
1765 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1766 assert_eq!(payment_preimage, *ev_preimage);
1767 assert_eq!(payment_hash, *ev_hash);
1768 assert_eq!(fee_paid_msat, &Some(1000));
1770 _ => panic!("Unexpected event")
1773 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1774 assert_eq!(hash, Some(payment_hash));
1776 _ => panic!("Unexpected event")
1778 check_added_monitors(&nodes[0], 1);
1779 } else if test == InterceptTest::Timeout {
1780 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
1781 connect_block(&nodes[0], &block);
1782 connect_block(&nodes[1], &block);
1783 for _ in 0..TEST_FINAL_CLTV {
1784 block.header.prev_blockhash = block.block_hash();
1785 connect_block(&nodes[0], &block);
1786 connect_block(&nodes[1], &block);
1788 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1789 check_added_monitors!(nodes[1], 1);
1790 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1791 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1792 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1793 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1794 assert!(htlc_timeout_updates.update_fee.is_none());
1796 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1797 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1798 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1800 // Check for unknown intercept id error.
1801 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1802 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();
1803 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1804 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1805 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1810 fn accept_underpaying_htlcs_config() {
1811 do_accept_underpaying_htlcs_config(1);
1812 do_accept_underpaying_htlcs_config(2);
1813 do_accept_underpaying_htlcs_config(3);
1816 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
1817 let chanmon_cfgs = create_chanmon_cfgs(3);
1818 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1819 let mut intercept_forwards_config = test_default_channel_config();
1820 intercept_forwards_config.accept_intercept_htlcs = true;
1821 let mut underpay_config = test_default_channel_config();
1822 underpay_config.channel_config.accept_underpaying_htlcs = true;
1823 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
1824 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1826 let mut chan_ids = Vec::new();
1827 for _ in 0..num_mpp_parts {
1828 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000, 0);
1829 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 2_000_000, 0).0.channel_id;
1830 chan_ids.push(channel_id);
1833 // Send the initial payment.
1834 let amt_msat = 900_000;
1835 let skimmed_fee_msat = 20;
1836 let mut route_hints = Vec::new();
1837 for _ in 0..num_mpp_parts {
1838 route_hints.push(RouteHint(vec![RouteHintHop {
1839 src_node_id: nodes[1].node.get_our_node_id(),
1840 short_channel_id: nodes[1].node.get_intercept_scid(),
1843 proportional_millionths: 0,
1845 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1846 htlc_minimum_msat: None,
1847 htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
1850 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1851 .with_route_hints(route_hints).unwrap()
1852 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1853 let route_params = RouteParameters {
1855 final_value_msat: amt_msat,
1857 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1858 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1859 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
1860 check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
1861 let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
1862 assert_eq!(events.len(), num_mpp_parts);
1864 // Forward the intercepted payments.
1865 for (idx, ev) in events.into_iter().enumerate() {
1866 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
1867 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
1869 let events = nodes[1].node.get_and_clear_pending_events();
1870 assert_eq!(events.len(), 1);
1871 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
1872 crate::events::Event::HTLCIntercepted {
1873 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
1875 assert_eq!(pmt_hash, payment_hash);
1876 (intercept_id, expected_outbound_amount_msat)
1880 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
1881 nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
1882 expect_pending_htlcs_forwardable!(nodes[1]);
1883 let payment_event = {
1885 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1886 assert_eq!(added_monitors.len(), 1);
1887 added_monitors.clear();
1889 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1890 assert_eq!(events.len(), 1);
1891 SendEvent::from_event(events.remove(0))
1893 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1894 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
1895 if idx == num_mpp_parts - 1 {
1896 expect_pending_htlcs_forwardable!(nodes[2]);
1900 // Claim the payment and check that the skimmed fee is as expected.
1901 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1902 let events = nodes[2].node.get_and_clear_pending_events();
1903 assert_eq!(events.len(), 1);
1905 crate::events::Event::PaymentClaimable {
1906 ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
1908 assert_eq!(payment_hash, payment_hash);
1909 assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
1910 assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
1911 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1913 crate::events::PaymentPurpose::InvoicePayment { payment_preimage: ev_payment_preimage,
1914 payment_secret: ev_payment_secret, .. } =>
1916 assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
1917 assert_eq!(payment_secret, *ev_payment_secret);
1922 _ => panic!("Unexpected event"),
1924 let mut expected_paths_vecs = Vec::new();
1925 let mut expected_paths = Vec::new();
1926 for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
1927 for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
1928 let total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
1929 &nodes[0], &expected_paths[..], &vec![skimmed_fee_msat as u32; num_mpp_parts][..], false,
1931 // The sender doesn't know that the penultimate hop took an extra fee.
1932 expect_payment_sent(&nodes[0], payment_preimage,
1933 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true, true);
1936 #[derive(PartialEq)]
1947 fn automatic_retries() {
1948 do_automatic_retries(AutoRetry::Success);
1949 do_automatic_retries(AutoRetry::Spontaneous);
1950 do_automatic_retries(AutoRetry::FailAttempts);
1951 do_automatic_retries(AutoRetry::FailTimeout);
1952 do_automatic_retries(AutoRetry::FailOnRestart);
1953 do_automatic_retries(AutoRetry::FailOnRetry);
1955 fn do_automatic_retries(test: AutoRetry) {
1956 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1958 let chanmon_cfgs = create_chanmon_cfgs(3);
1959 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1961 let new_chain_monitor;
1963 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1964 let node_0_deserialized;
1966 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1967 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1968 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1970 // Marshall data to send the payment
1971 #[cfg(feature = "std")]
1972 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1973 #[cfg(not(feature = "std"))]
1974 let payment_expiry_secs = 60 * 60;
1975 let amt_msat = 1000;
1976 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1977 invoice_features.set_variable_length_onion_required();
1978 invoice_features.set_payment_secret_required();
1979 invoice_features.set_basic_mpp_optional();
1980 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1981 .with_expiry_time(payment_expiry_secs as u64)
1982 .with_bolt11_features(invoice_features).unwrap();
1983 let route_params = RouteParameters {
1985 final_value_msat: amt_msat,
1987 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1989 macro_rules! pass_failed_attempt_with_retry_along_path {
1990 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1991 // Send a payment attempt that fails due to lack of liquidity on the second hop
1992 check_added_monitors!(nodes[0], 1);
1993 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1994 let mut update_add = update_0.update_add_htlcs[0].clone();
1995 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1996 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1997 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1998 nodes[1].node.process_pending_htlc_forwards();
1999 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
2000 vec![HTLCDestination::NextHopChannel {
2001 node_id: Some(nodes[2].node.get_our_node_id()),
2002 channel_id: $failing_channel_id,
2004 nodes[1].node.process_pending_htlc_forwards();
2005 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2006 check_added_monitors!(&nodes[1], 1);
2007 assert!(update_1.update_fail_htlcs.len() == 1);
2008 let fail_msg = update_1.update_fail_htlcs[0].clone();
2009 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
2010 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
2012 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
2013 let mut events = nodes[0].node.get_and_clear_pending_events();
2014 assert_eq!(events.len(), 2);
2016 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2017 assert_eq!(payment_hash, ev_payment_hash);
2018 assert_eq!(payment_failed_permanently, false);
2020 _ => panic!("Unexpected event"),
2022 if $expect_pending_htlcs_forwardable {
2024 Event::PendingHTLCsForwardable { .. } => {},
2025 _ => panic!("Unexpected event"),
2029 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
2030 assert_eq!(payment_hash, ev_payment_hash);
2032 _ => panic!("Unexpected event"),
2038 if test == AutoRetry::Success {
2039 // Test that we can succeed on the first retry.
2040 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2041 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2042 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2044 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2045 // attempt, since the initial second hop channel will be excluded from pathfinding
2046 create_announced_chan_between_nodes(&nodes, 1, 2);
2048 // We retry payments in `process_pending_htlc_forwards`
2049 nodes[0].node.process_pending_htlc_forwards();
2050 check_added_monitors!(nodes[0], 1);
2051 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2052 assert_eq!(msg_events.len(), 1);
2053 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
2054 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2055 } else if test == AutoRetry::Spontaneous {
2056 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
2057 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
2058 Retry::Attempts(1)).unwrap();
2059 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2061 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2062 // attempt, since the initial second hop channel will be excluded from pathfinding
2063 create_announced_chan_between_nodes(&nodes, 1, 2);
2065 // We retry payments in `process_pending_htlc_forwards`
2066 nodes[0].node.process_pending_htlc_forwards();
2067 check_added_monitors!(nodes[0], 1);
2068 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2069 assert_eq!(msg_events.len(), 1);
2070 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2071 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2072 } else if test == AutoRetry::FailAttempts {
2073 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2074 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2075 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2076 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2078 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2079 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2080 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2082 // We retry payments in `process_pending_htlc_forwards`
2083 nodes[0].node.process_pending_htlc_forwards();
2084 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2086 // Ensure we won't retry a second time.
2087 nodes[0].node.process_pending_htlc_forwards();
2088 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2089 assert_eq!(msg_events.len(), 0);
2090 } else if test == AutoRetry::FailTimeout {
2091 #[cfg(not(feature = "no-std"))] {
2092 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2093 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2094 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2095 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2097 // Advance the time so the second attempt fails due to timeout.
2098 SinceEpoch::advance(Duration::from_secs(61));
2100 // Make sure we don't retry again.
2101 nodes[0].node.process_pending_htlc_forwards();
2102 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2103 assert_eq!(msg_events.len(), 0);
2105 let mut events = nodes[0].node.get_and_clear_pending_events();
2106 assert_eq!(events.len(), 1);
2108 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2109 assert_eq!(payment_hash, *ev_payment_hash);
2110 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2111 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2113 _ => panic!("Unexpected event"),
2116 } else if test == AutoRetry::FailOnRestart {
2117 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2118 // attempts remaining prior to restart.
2119 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2120 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2121 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2123 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2124 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2125 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2127 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2128 nodes[0].node.process_pending_htlc_forwards();
2129 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2131 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2132 let node_encoded = nodes[0].node.encode();
2133 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2134 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2136 let mut events = nodes[0].node.get_and_clear_pending_events();
2137 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2138 // Make sure we don't retry again.
2139 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2140 assert_eq!(msg_events.len(), 0);
2142 let mut events = nodes[0].node.get_and_clear_pending_events();
2143 assert_eq!(events.len(), 1);
2145 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2146 assert_eq!(payment_hash, *ev_payment_hash);
2147 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2148 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2150 _ => panic!("Unexpected event"),
2152 } else if test == AutoRetry::FailOnRetry {
2153 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2154 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2155 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2157 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2158 // fail to find a route.
2159 nodes[0].node.process_pending_htlc_forwards();
2160 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2161 assert_eq!(msg_events.len(), 0);
2163 let mut events = nodes[0].node.get_and_clear_pending_events();
2164 assert_eq!(events.len(), 1);
2166 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2167 assert_eq!(payment_hash, *ev_payment_hash);
2168 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2169 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2171 _ => panic!("Unexpected event"),
2177 fn auto_retry_partial_failure() {
2178 // Test that we'll retry appropriately on send partial failure and retry partial failure.
2179 let chanmon_cfgs = create_chanmon_cfgs(2);
2180 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2181 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2182 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2184 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2185 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2186 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2188 // Marshall data to send the payment
2189 let amt_msat = 20_000;
2190 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2191 #[cfg(feature = "std")]
2192 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2193 #[cfg(not(feature = "std"))]
2194 let payment_expiry_secs = 60 * 60;
2195 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2196 invoice_features.set_variable_length_onion_required();
2197 invoice_features.set_payment_secret_required();
2198 invoice_features.set_basic_mpp_optional();
2199 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2200 .with_expiry_time(payment_expiry_secs as u64)
2201 .with_bolt11_features(invoice_features).unwrap();
2202 let route_params = RouteParameters {
2204 final_value_msat: amt_msat,
2207 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
2208 // second (for the initial send path2 over chan_2) fails.
2209 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2210 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2211 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
2212 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
2213 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2214 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2215 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2217 // Configure the initial send, retry1 and retry2's paths.
2218 let send_route = Route {
2220 Path { hops: vec![RouteHop {
2221 pubkey: nodes[1].node.get_our_node_id(),
2222 node_features: nodes[1].node.node_features(),
2223 short_channel_id: chan_1_id,
2224 channel_features: nodes[1].node.channel_features(),
2225 fee_msat: amt_msat / 2,
2226 cltv_expiry_delta: 100,
2227 }], blinded_tail: None },
2228 Path { hops: vec![RouteHop {
2229 pubkey: nodes[1].node.get_our_node_id(),
2230 node_features: nodes[1].node.node_features(),
2231 short_channel_id: chan_2_id,
2232 channel_features: nodes[1].node.channel_features(),
2233 fee_msat: amt_msat / 2,
2234 cltv_expiry_delta: 100,
2235 }], blinded_tail: None },
2237 payment_params: Some(route_params.payment_params.clone()),
2239 let retry_1_route = Route {
2241 Path { hops: vec![RouteHop {
2242 pubkey: nodes[1].node.get_our_node_id(),
2243 node_features: nodes[1].node.node_features(),
2244 short_channel_id: chan_1_id,
2245 channel_features: nodes[1].node.channel_features(),
2246 fee_msat: amt_msat / 4,
2247 cltv_expiry_delta: 100,
2248 }], blinded_tail: None },
2249 Path { hops: vec![RouteHop {
2250 pubkey: nodes[1].node.get_our_node_id(),
2251 node_features: nodes[1].node.node_features(),
2252 short_channel_id: chan_3_id,
2253 channel_features: nodes[1].node.channel_features(),
2254 fee_msat: amt_msat / 4,
2255 cltv_expiry_delta: 100,
2256 }], blinded_tail: None },
2258 payment_params: Some(route_params.payment_params.clone()),
2260 let retry_2_route = Route {
2262 Path { hops: vec![RouteHop {
2263 pubkey: nodes[1].node.get_our_node_id(),
2264 node_features: nodes[1].node.node_features(),
2265 short_channel_id: chan_1_id,
2266 channel_features: nodes[1].node.channel_features(),
2267 fee_msat: amt_msat / 4,
2268 cltv_expiry_delta: 100,
2269 }], blinded_tail: None },
2271 payment_params: Some(route_params.payment_params.clone()),
2273 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2274 let mut payment_params = route_params.payment_params.clone();
2275 payment_params.previously_failed_channels.push(chan_2_id);
2276 nodes[0].router.expect_find_route(RouteParameters {
2277 payment_params, final_value_msat: amt_msat / 2,
2278 }, Ok(retry_1_route));
2279 let mut payment_params = route_params.payment_params.clone();
2280 payment_params.previously_failed_channels.push(chan_3_id);
2281 nodes[0].router.expect_find_route(RouteParameters {
2282 payment_params, final_value_msat: amt_msat / 4,
2283 }, Ok(retry_2_route));
2285 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2286 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2287 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2288 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
2289 assert_eq!(closed_chan_events.len(), 4);
2290 match closed_chan_events[0] {
2291 Event::ChannelClosed { .. } => {},
2292 _ => panic!("Unexpected event"),
2294 match closed_chan_events[1] {
2295 Event::PaymentPathFailed { .. } => {},
2296 _ => panic!("Unexpected event"),
2298 match closed_chan_events[2] {
2299 Event::ChannelClosed { .. } => {},
2300 _ => panic!("Unexpected event"),
2302 match closed_chan_events[3] {
2303 Event::PaymentPathFailed { .. } => {},
2304 _ => panic!("Unexpected event"),
2307 // Pass the first part of the payment along the path.
2308 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
2309 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2311 // First message is the first update_add, remaining messages are broadcasting channel updates and
2312 // errors for the permfailed channels
2313 assert_eq!(msg_events.len(), 5);
2314 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2316 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2317 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2318 check_added_monitors!(nodes[1], 1);
2319 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2321 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2322 check_added_monitors!(nodes[0], 1);
2323 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2325 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2326 check_added_monitors!(nodes[0], 1);
2327 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2329 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2330 check_added_monitors!(nodes[1], 1);
2332 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2333 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2334 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2335 check_added_monitors!(nodes[1], 1);
2336 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2338 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2339 check_added_monitors!(nodes[0], 1);
2341 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2342 check_added_monitors!(nodes[0], 1);
2343 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2345 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2346 check_added_monitors!(nodes[1], 1);
2348 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2349 nodes[1].node.process_pending_htlc_forwards();
2350 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2351 nodes[1].node.claim_funds(payment_preimage);
2352 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2353 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2354 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2356 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2357 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
2358 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2359 check_added_monitors!(nodes[0], 1);
2360 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2362 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2363 check_added_monitors!(nodes[1], 4);
2364 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2366 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2367 check_added_monitors!(nodes[1], 1);
2368 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2370 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2371 check_added_monitors!(nodes[0], 1);
2372 expect_payment_path_successful!(nodes[0]);
2374 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2375 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2376 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2377 check_added_monitors!(nodes[0], 1);
2378 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2380 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2381 check_added_monitors!(nodes[1], 1);
2383 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2384 check_added_monitors!(nodes[1], 1);
2385 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2387 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2388 check_added_monitors!(nodes[0], 1);
2389 let events = nodes[0].node.get_and_clear_pending_events();
2390 assert_eq!(events.len(), 2);
2391 if let Event::PaymentPathSuccessful { .. } = events[0] {} else { panic!(); }
2392 if let Event::PaymentPathSuccessful { .. } = events[1] {} else { panic!(); }
2396 fn auto_retry_zero_attempts_send_error() {
2397 let chanmon_cfgs = create_chanmon_cfgs(2);
2398 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2399 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2400 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2402 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2403 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2405 // Marshall data to send the payment
2406 let amt_msat = 20_000;
2407 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2408 #[cfg(feature = "std")]
2409 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2410 #[cfg(not(feature = "std"))]
2411 let payment_expiry_secs = 60 * 60;
2412 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2413 invoice_features.set_variable_length_onion_required();
2414 invoice_features.set_payment_secret_required();
2415 invoice_features.set_basic_mpp_optional();
2416 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2417 .with_expiry_time(payment_expiry_secs as u64)
2418 .with_bolt11_features(invoice_features).unwrap();
2419 let route_params = RouteParameters {
2421 final_value_msat: amt_msat,
2424 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2425 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2426 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2427 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2428 let events = nodes[0].node.get_and_clear_pending_events();
2429 assert_eq!(events.len(), 3);
2430 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2431 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2432 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2433 check_added_monitors!(nodes[0], 2);
2437 fn fails_paying_after_rejected_by_payee() {
2438 let chanmon_cfgs = create_chanmon_cfgs(2);
2439 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2440 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2441 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2443 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2445 // Marshall data to send the payment
2446 let amt_msat = 20_000;
2447 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2448 #[cfg(feature = "std")]
2449 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2450 #[cfg(not(feature = "std"))]
2451 let payment_expiry_secs = 60 * 60;
2452 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2453 invoice_features.set_variable_length_onion_required();
2454 invoice_features.set_payment_secret_required();
2455 invoice_features.set_basic_mpp_optional();
2456 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2457 .with_expiry_time(payment_expiry_secs as u64)
2458 .with_bolt11_features(invoice_features).unwrap();
2459 let route_params = RouteParameters {
2461 final_value_msat: amt_msat,
2464 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2465 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2466 check_added_monitors!(nodes[0], 1);
2467 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2468 assert_eq!(events.len(), 1);
2469 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2470 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2471 check_added_monitors!(nodes[1], 0);
2472 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2473 expect_pending_htlcs_forwardable!(nodes[1]);
2474 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2476 nodes[1].node.fail_htlc_backwards(&payment_hash);
2477 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2478 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2482 fn retry_multi_path_single_failed_payment() {
2483 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2484 let chanmon_cfgs = create_chanmon_cfgs(2);
2485 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2486 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2487 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2489 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2490 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2492 let amt_msat = 100_010_000;
2494 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2495 #[cfg(feature = "std")]
2496 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2497 #[cfg(not(feature = "std"))]
2498 let payment_expiry_secs = 60 * 60;
2499 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2500 invoice_features.set_variable_length_onion_required();
2501 invoice_features.set_payment_secret_required();
2502 invoice_features.set_basic_mpp_optional();
2503 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2504 .with_expiry_time(payment_expiry_secs as u64)
2505 .with_bolt11_features(invoice_features).unwrap();
2506 let route_params = RouteParameters {
2507 payment_params: payment_params.clone(),
2508 final_value_msat: amt_msat,
2511 let chans = nodes[0].node.list_usable_channels();
2512 let mut route = Route {
2514 Path { hops: vec![RouteHop {
2515 pubkey: nodes[1].node.get_our_node_id(),
2516 node_features: nodes[1].node.node_features(),
2517 short_channel_id: chans[0].short_channel_id.unwrap(),
2518 channel_features: nodes[1].node.channel_features(),
2520 cltv_expiry_delta: 100,
2521 }], blinded_tail: None },
2522 Path { hops: vec![RouteHop {
2523 pubkey: nodes[1].node.get_our_node_id(),
2524 node_features: nodes[1].node.node_features(),
2525 short_channel_id: chans[1].short_channel_id.unwrap(),
2526 channel_features: nodes[1].node.channel_features(),
2527 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2528 cltv_expiry_delta: 100,
2529 }], blinded_tail: None },
2531 payment_params: Some(payment_params),
2533 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2534 // On retry, split the payment across both channels.
2535 route.paths[0].hops[0].fee_msat = 50_000_001;
2536 route.paths[1].hops[0].fee_msat = 50_000_000;
2537 let mut pay_params = route.payment_params.clone().unwrap();
2538 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2539 nodes[0].router.expect_find_route(RouteParameters {
2540 payment_params: pay_params,
2541 // Note that the second request here requests the amount we originally failed to send,
2542 // not the amount remaining on the full payment, which should be changed.
2543 final_value_msat: 100_000_001,
2544 }, Ok(route.clone()));
2547 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2548 // The initial send attempt, 2 paths
2549 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2550 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2551 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2552 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2553 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2556 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2557 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2558 let events = nodes[0].node.get_and_clear_pending_events();
2559 assert_eq!(events.len(), 1);
2561 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2562 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2563 short_channel_id: Some(expected_scid), .. } =>
2565 assert_eq!(payment_hash, ev_payment_hash);
2566 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2568 _ => panic!("Unexpected event"),
2570 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2571 assert_eq!(htlc_msgs.len(), 2);
2572 check_added_monitors!(nodes[0], 2);
2576 fn immediate_retry_on_failure() {
2577 // Tests that we can/will retry immediately after a failure
2578 let chanmon_cfgs = create_chanmon_cfgs(2);
2579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2581 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2583 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2584 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2586 let amt_msat = 100_000_001;
2587 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2588 #[cfg(feature = "std")]
2589 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2590 #[cfg(not(feature = "std"))]
2591 let payment_expiry_secs = 60 * 60;
2592 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2593 invoice_features.set_variable_length_onion_required();
2594 invoice_features.set_payment_secret_required();
2595 invoice_features.set_basic_mpp_optional();
2596 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2597 .with_expiry_time(payment_expiry_secs as u64)
2598 .with_bolt11_features(invoice_features).unwrap();
2599 let route_params = RouteParameters {
2601 final_value_msat: amt_msat,
2604 let chans = nodes[0].node.list_usable_channels();
2605 let mut route = Route {
2607 Path { hops: vec![RouteHop {
2608 pubkey: nodes[1].node.get_our_node_id(),
2609 node_features: nodes[1].node.node_features(),
2610 short_channel_id: chans[0].short_channel_id.unwrap(),
2611 channel_features: nodes[1].node.channel_features(),
2612 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2613 cltv_expiry_delta: 100,
2614 }], blinded_tail: None },
2616 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2618 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2619 // On retry, split the payment across both channels.
2620 route.paths.push(route.paths[0].clone());
2621 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2622 route.paths[0].hops[0].fee_msat = 50_000_000;
2623 route.paths[1].hops[0].fee_msat = 50_000_001;
2624 let mut pay_params = route_params.payment_params.clone();
2625 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2626 nodes[0].router.expect_find_route(RouteParameters {
2627 payment_params: pay_params, final_value_msat: amt_msat,
2628 }, Ok(route.clone()));
2630 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2631 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2632 let events = nodes[0].node.get_and_clear_pending_events();
2633 assert_eq!(events.len(), 1);
2635 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2636 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2637 short_channel_id: Some(expected_scid), .. } =>
2639 assert_eq!(payment_hash, ev_payment_hash);
2640 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2642 _ => panic!("Unexpected event"),
2644 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2645 assert_eq!(htlc_msgs.len(), 2);
2646 check_added_monitors!(nodes[0], 2);
2650 fn no_extra_retries_on_back_to_back_fail() {
2651 // In a previous release, we had a race where we may exceed the payment retry count if we
2652 // get two failures in a row with the second indicating that all paths had failed (this field,
2653 // `all_paths_failed`, has since been removed).
2654 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2655 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2656 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2657 // pending which we will see later. Thus, when we previously removed the retry tracking map
2658 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2659 // retry entry even though more events for the same payment were still pending. This led to
2660 // us retrying a payment again even though we'd already given up on it.
2662 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2663 // is used to remove the payment retry counter entries instead. This tests for the specific
2664 // excess-retry case while also testing `PaymentFailed` generation.
2666 let chanmon_cfgs = create_chanmon_cfgs(3);
2667 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2668 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2669 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2671 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2672 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2674 let amt_msat = 200_000_000;
2675 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2676 #[cfg(feature = "std")]
2677 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2678 #[cfg(not(feature = "std"))]
2679 let payment_expiry_secs = 60 * 60;
2680 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2681 invoice_features.set_variable_length_onion_required();
2682 invoice_features.set_payment_secret_required();
2683 invoice_features.set_basic_mpp_optional();
2684 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2685 .with_expiry_time(payment_expiry_secs as u64)
2686 .with_bolt11_features(invoice_features).unwrap();
2687 let route_params = RouteParameters {
2689 final_value_msat: amt_msat,
2692 let mut route = Route {
2694 Path { hops: vec![RouteHop {
2695 pubkey: nodes[1].node.get_our_node_id(),
2696 node_features: nodes[1].node.node_features(),
2697 short_channel_id: chan_1_scid,
2698 channel_features: nodes[1].node.channel_features(),
2699 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2700 cltv_expiry_delta: 100,
2702 pubkey: nodes[2].node.get_our_node_id(),
2703 node_features: nodes[2].node.node_features(),
2704 short_channel_id: chan_2_scid,
2705 channel_features: nodes[2].node.channel_features(),
2706 fee_msat: 100_000_000,
2707 cltv_expiry_delta: 100,
2708 }], blinded_tail: None },
2709 Path { hops: vec![RouteHop {
2710 pubkey: nodes[1].node.get_our_node_id(),
2711 node_features: nodes[1].node.node_features(),
2712 short_channel_id: chan_1_scid,
2713 channel_features: nodes[1].node.channel_features(),
2714 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2715 cltv_expiry_delta: 100,
2717 pubkey: nodes[2].node.get_our_node_id(),
2718 node_features: nodes[2].node.node_features(),
2719 short_channel_id: chan_2_scid,
2720 channel_features: nodes[2].node.channel_features(),
2721 fee_msat: 100_000_000,
2722 cltv_expiry_delta: 100,
2723 }], blinded_tail: None }
2725 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2727 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2728 let mut second_payment_params = route_params.payment_params.clone();
2729 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2730 // On retry, we'll only return one path
2731 route.paths.remove(1);
2732 route.paths[0].hops[1].fee_msat = amt_msat;
2733 nodes[0].router.expect_find_route(RouteParameters {
2734 payment_params: second_payment_params,
2735 final_value_msat: amt_msat,
2736 }, Ok(route.clone()));
2738 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2739 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2740 let htlc_updates = SendEvent::from_node(&nodes[0]);
2741 check_added_monitors!(nodes[0], 1);
2742 assert_eq!(htlc_updates.msgs.len(), 1);
2744 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2745 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2746 check_added_monitors!(nodes[1], 1);
2747 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2749 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2750 check_added_monitors!(nodes[0], 1);
2751 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2753 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2754 check_added_monitors!(nodes[0], 1);
2755 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2757 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2758 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2759 check_added_monitors!(nodes[1], 1);
2760 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2762 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2763 check_added_monitors!(nodes[1], 1);
2764 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2766 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2767 check_added_monitors!(nodes[0], 1);
2769 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2770 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2771 check_added_monitors!(nodes[0], 1);
2772 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2774 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2775 check_added_monitors!(nodes[1], 1);
2776 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2778 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2779 check_added_monitors!(nodes[1], 1);
2780 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2782 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2783 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2784 check_added_monitors!(nodes[0], 1);
2786 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2787 check_added_monitors!(nodes[0], 1);
2788 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2790 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2791 check_added_monitors!(nodes[1], 1);
2792 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2793 check_added_monitors!(nodes[1], 1);
2794 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2796 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2797 check_added_monitors!(nodes[0], 1);
2799 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2800 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2803 // Previously, we retried payments in an event consumer, which would retry each
2804 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2805 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2806 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2807 // by adding the `PaymentFailed` event.
2809 // Because we now retry payments as a batch, we simply return a single-path route in the
2810 // second, batched, request, have that fail, ensure the payment was abandoned.
2811 let mut events = nodes[0].node.get_and_clear_pending_events();
2812 assert_eq!(events.len(), 3);
2814 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2815 assert_eq!(payment_hash, ev_payment_hash);
2816 assert_eq!(payment_failed_permanently, false);
2818 _ => panic!("Unexpected event"),
2821 Event::PendingHTLCsForwardable { .. } => {},
2822 _ => panic!("Unexpected event"),
2825 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2826 assert_eq!(payment_hash, ev_payment_hash);
2827 assert_eq!(payment_failed_permanently, false);
2829 _ => panic!("Unexpected event"),
2832 nodes[0].node.process_pending_htlc_forwards();
2833 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2834 check_added_monitors!(nodes[0], 1);
2836 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2837 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2838 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2839 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2840 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2842 let mut events = nodes[0].node.get_and_clear_pending_events();
2843 assert_eq!(events.len(), 2);
2845 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2846 assert_eq!(payment_hash, ev_payment_hash);
2847 assert_eq!(payment_failed_permanently, false);
2849 _ => panic!("Unexpected event"),
2852 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2853 assert_eq!(payment_hash, *ev_payment_hash);
2854 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2855 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2857 _ => panic!("Unexpected event"),
2862 fn test_simple_partial_retry() {
2863 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2864 // full amount of the payment, rather than only the missing amount. Here we simply test for
2865 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2866 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2868 let chanmon_cfgs = create_chanmon_cfgs(3);
2869 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2870 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2871 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2873 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2874 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2876 let amt_msat = 200_000_000;
2877 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2878 #[cfg(feature = "std")]
2879 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2880 #[cfg(not(feature = "std"))]
2881 let payment_expiry_secs = 60 * 60;
2882 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2883 invoice_features.set_variable_length_onion_required();
2884 invoice_features.set_payment_secret_required();
2885 invoice_features.set_basic_mpp_optional();
2886 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2887 .with_expiry_time(payment_expiry_secs as u64)
2888 .with_bolt11_features(invoice_features).unwrap();
2889 let route_params = RouteParameters {
2891 final_value_msat: amt_msat,
2894 let mut route = Route {
2896 Path { hops: vec![RouteHop {
2897 pubkey: nodes[1].node.get_our_node_id(),
2898 node_features: nodes[1].node.node_features(),
2899 short_channel_id: chan_1_scid,
2900 channel_features: nodes[1].node.channel_features(),
2901 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2902 cltv_expiry_delta: 100,
2904 pubkey: nodes[2].node.get_our_node_id(),
2905 node_features: nodes[2].node.node_features(),
2906 short_channel_id: chan_2_scid,
2907 channel_features: nodes[2].node.channel_features(),
2908 fee_msat: 100_000_000,
2909 cltv_expiry_delta: 100,
2910 }], blinded_tail: None },
2911 Path { hops: vec![RouteHop {
2912 pubkey: nodes[1].node.get_our_node_id(),
2913 node_features: nodes[1].node.node_features(),
2914 short_channel_id: chan_1_scid,
2915 channel_features: nodes[1].node.channel_features(),
2917 cltv_expiry_delta: 100,
2919 pubkey: nodes[2].node.get_our_node_id(),
2920 node_features: nodes[2].node.node_features(),
2921 short_channel_id: chan_2_scid,
2922 channel_features: nodes[2].node.channel_features(),
2923 fee_msat: 100_000_000,
2924 cltv_expiry_delta: 100,
2925 }], blinded_tail: None }
2927 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2929 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2930 let mut second_payment_params = route_params.payment_params.clone();
2931 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2932 // On retry, we'll only be asked for one path (or 100k sats)
2933 route.paths.remove(0);
2934 nodes[0].router.expect_find_route(RouteParameters {
2935 payment_params: second_payment_params,
2936 final_value_msat: amt_msat / 2,
2937 }, Ok(route.clone()));
2939 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2940 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2941 let htlc_updates = SendEvent::from_node(&nodes[0]);
2942 check_added_monitors!(nodes[0], 1);
2943 assert_eq!(htlc_updates.msgs.len(), 1);
2945 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2946 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2947 check_added_monitors!(nodes[1], 1);
2948 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2950 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2951 check_added_monitors!(nodes[0], 1);
2952 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2954 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2955 check_added_monitors!(nodes[0], 1);
2956 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2958 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2959 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2960 check_added_monitors!(nodes[1], 1);
2961 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2963 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2964 check_added_monitors!(nodes[1], 1);
2965 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2967 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2968 check_added_monitors!(nodes[0], 1);
2970 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2971 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2972 check_added_monitors!(nodes[0], 1);
2973 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2975 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2976 check_added_monitors!(nodes[1], 1);
2978 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2979 check_added_monitors!(nodes[1], 1);
2981 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2983 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2984 check_added_monitors!(nodes[0], 1);
2986 let mut events = nodes[0].node.get_and_clear_pending_events();
2987 assert_eq!(events.len(), 2);
2989 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2990 assert_eq!(payment_hash, ev_payment_hash);
2991 assert_eq!(payment_failed_permanently, false);
2993 _ => panic!("Unexpected event"),
2996 Event::PendingHTLCsForwardable { .. } => {},
2997 _ => panic!("Unexpected event"),
3000 nodes[0].node.process_pending_htlc_forwards();
3001 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3002 check_added_monitors!(nodes[0], 1);
3004 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3005 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3007 expect_pending_htlcs_forwardable!(nodes[1]);
3008 check_added_monitors!(nodes[1], 1);
3010 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3011 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
3012 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
3013 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
3015 expect_pending_htlcs_forwardable!(nodes[2]);
3016 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
3020 #[cfg(feature = "std")]
3021 fn test_threaded_payment_retries() {
3022 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
3023 // a single thread and would happily let multiple threads run retries at the same time. Because
3024 // retries are done by first calculating the amount we need to retry, then dropping the
3025 // relevant lock, then actually sending, we would happily let multiple threads retry the same
3026 // amount at the same time, overpaying our original HTLC!
3027 let chanmon_cfgs = create_chanmon_cfgs(4);
3028 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3029 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3030 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3032 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
3033 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
3034 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
3035 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
3037 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3038 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
3039 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
3040 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
3042 let amt_msat = 100_000_000;
3043 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3044 #[cfg(feature = "std")]
3045 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3046 #[cfg(not(feature = "std"))]
3047 let payment_expiry_secs = 60 * 60;
3048 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3049 invoice_features.set_variable_length_onion_required();
3050 invoice_features.set_payment_secret_required();
3051 invoice_features.set_basic_mpp_optional();
3052 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3053 .with_expiry_time(payment_expiry_secs as u64)
3054 .with_bolt11_features(invoice_features).unwrap();
3055 let mut route_params = RouteParameters {
3057 final_value_msat: amt_msat,
3060 let mut route = Route {
3062 Path { hops: vec![RouteHop {
3063 pubkey: nodes[1].node.get_our_node_id(),
3064 node_features: nodes[1].node.node_features(),
3065 short_channel_id: chan_1_scid,
3066 channel_features: nodes[1].node.channel_features(),
3068 cltv_expiry_delta: 100,
3070 pubkey: nodes[3].node.get_our_node_id(),
3071 node_features: nodes[2].node.node_features(),
3072 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3073 channel_features: nodes[2].node.channel_features(),
3074 fee_msat: amt_msat / 1000,
3075 cltv_expiry_delta: 100,
3076 }], blinded_tail: None },
3077 Path { hops: vec![RouteHop {
3078 pubkey: nodes[2].node.get_our_node_id(),
3079 node_features: nodes[2].node.node_features(),
3080 short_channel_id: chan_3_scid,
3081 channel_features: nodes[2].node.channel_features(),
3083 cltv_expiry_delta: 100,
3085 pubkey: nodes[3].node.get_our_node_id(),
3086 node_features: nodes[3].node.node_features(),
3087 short_channel_id: chan_4_scid,
3088 channel_features: nodes[3].node.channel_features(),
3089 fee_msat: amt_msat - amt_msat / 1000,
3090 cltv_expiry_delta: 100,
3091 }], blinded_tail: None }
3093 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
3095 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3097 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3098 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3099 check_added_monitors!(nodes[0], 2);
3100 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3101 assert_eq!(send_msg_events.len(), 2);
3102 send_msg_events.retain(|msg|
3103 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3104 // Drop the commitment update for nodes[2], we can just let that one sit pending
3106 *node_id == nodes[1].node.get_our_node_id()
3107 } else { panic!(); }
3110 // from here on out, the retry `RouteParameters` amount will be amt/1000
3111 route_params.final_value_msat /= 1000;
3114 let end_time = Instant::now() + Duration::from_secs(1);
3115 macro_rules! thread_body { () => { {
3116 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3117 let node_ref = NodePtr::from_node(&nodes[0]);
3119 let node_a = unsafe { &*node_ref.0 };
3120 while Instant::now() < end_time {
3121 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3122 // Ignore if we have any pending events, just always pretend we just got a
3123 // PendingHTLCsForwardable
3124 node_a.node.process_pending_htlc_forwards();
3128 let mut threads = Vec::new();
3129 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3131 // Back in the main thread, poll pending messages and make sure that we never have more than
3132 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3133 // there are HTLC messages shoved in while its running. This allows us to test that we never
3134 // generate an additional update_add_htlc until we've fully failed the first.
3135 let mut previously_failed_channels = Vec::new();
3137 assert_eq!(send_msg_events.len(), 1);
3138 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3139 assert_eq!(send_event.msgs.len(), 1);
3141 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3142 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3144 // Note that we only push one route into `expect_find_route` at a time, because that's all
3145 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3146 // we should still ultimately fail for the same reason - because we're trying to send too
3147 // many HTLCs at once.
3148 let mut new_route_params = route_params.clone();
3149 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3150 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3151 route.paths[0].hops[1].short_channel_id += 1;
3152 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3154 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3155 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3156 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3157 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3158 // This races with our other threads which may generate an add-HTLCs commitment update via
3159 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3160 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3161 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3162 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3164 let cur_time = Instant::now();
3165 if cur_time > end_time {
3166 for thread in threads.drain(..) { thread.join().unwrap(); }
3169 // Make sure we have some events to handle when we go around...
3170 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3171 nodes[0].node.process_pending_htlc_forwards();
3172 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3173 check_added_monitors!(nodes[0], 2);
3175 if cur_time > end_time {
3181 fn do_no_missing_sent_on_reload(persist_manager_with_payment: bool, at_midpoint: bool) {
3182 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3183 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3184 // it was last persisted.
3185 let chanmon_cfgs = create_chanmon_cfgs(2);
3186 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3187 let (persister_a, persister_b, persister_c);
3188 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3189 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3190 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3191 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3193 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3195 let mut nodes_0_serialized = Vec::new();
3196 if !persist_manager_with_payment {
3197 nodes_0_serialized = nodes[0].node.encode();
3200 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3202 if persist_manager_with_payment {
3203 nodes_0_serialized = nodes[0].node.encode();
3206 nodes[1].node.claim_funds(our_payment_preimage);
3207 check_added_monitors!(nodes[1], 1);
3208 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3211 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3212 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3213 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3214 check_added_monitors!(nodes[0], 1);
3216 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3217 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
3218 commitment_signed_dance!(nodes[0], nodes[1], htlc_fulfill_updates.commitment_signed, false);
3219 // Ignore the PaymentSent event which is now pending on nodes[0] - if we were to handle it we'd
3220 // be expected to ignore the eventual conflicting PaymentFailed, but by not looking at it we
3221 // expect to get the PaymentSent again later.
3222 check_added_monitors(&nodes[0], 0);
3225 // The ChannelMonitor should always be the latest version, as we're required to persist it
3226 // during the commitment signed handling.
3227 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3228 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3230 let events = nodes[0].node.get_and_clear_pending_events();
3231 assert_eq!(events.len(), 2);
3232 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3233 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3234 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3235 // the double-claim that would otherwise appear at the end of this test.
3236 nodes[0].node.timer_tick_occurred();
3237 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3238 assert_eq!(as_broadcasted_txn.len(), 1);
3240 // Ensure that, even after some time, if we restart we still include *something* in the current
3241 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3242 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3243 // A naive implementation of the fix here would wipe the pending payments set, causing a
3244 // failure event when we restart.
3245 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3247 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3248 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);
3249 let events = nodes[0].node.get_and_clear_pending_events();
3250 assert!(events.is_empty());
3252 // Ensure that we don't generate any further events even after the channel-closing commitment
3253 // transaction is confirmed on-chain.
3254 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3255 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3257 let events = nodes[0].node.get_and_clear_pending_events();
3258 assert!(events.is_empty());
3260 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3261 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);
3262 let events = nodes[0].node.get_and_clear_pending_events();
3263 assert!(events.is_empty());
3264 check_added_monitors(&nodes[0], 1);
3268 fn no_missing_sent_on_midpoint_reload() {
3269 do_no_missing_sent_on_reload(false, true);
3270 do_no_missing_sent_on_reload(true, true);
3274 fn no_missing_sent_on_reload() {
3275 do_no_missing_sent_on_reload(false, false);
3276 do_no_missing_sent_on_reload(true, false);
3279 fn do_claim_from_closed_chan(fail_payment: bool) {
3280 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3281 // received had been closed between when the HTLC was received and when we went to claim it.
3282 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3283 // presumably the sender may retry later. Long ago it also reduced total code in the claim
3286 // However, this doesn't make sense if you're trying to do an atomic swap or some other
3287 // protocol that requires atomicity with some other action - if your money got claimed
3288 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3289 // is an over-optimization - there should be a very, very low likelihood that a channel closes
3290 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3291 // Since we now have code to handle this anyway we should allow it.
3293 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3294 // CLTVs on the paths to different value resulting in a different claim deadline.
3295 let chanmon_cfgs = create_chanmon_cfgs(4);
3296 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3297 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3298 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3300 create_announced_chan_between_nodes(&nodes, 0, 1);
3301 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3302 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3303 create_announced_chan_between_nodes(&nodes, 2, 3);
3305 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3306 let mut route_params = RouteParameters {
3307 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3308 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
3309 final_value_msat: 10_000_000,
3311 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3312 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3313 // Make sure the route is ordered as the B->D path before C->D
3314 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3315 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3317 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3318 // the HTLC is being relayed.
3319 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3320 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3321 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3323 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3324 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3325 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3326 check_added_monitors(&nodes[0], 2);
3327 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3328 send_msgs.sort_by(|a, _| {
3330 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3331 let node_b_id = nodes[1].node.get_our_node_id();
3332 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3335 assert_eq!(send_msgs.len(), 2);
3336 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3337 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3338 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3339 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3341 match receive_event.unwrap() {
3342 Event::PaymentClaimable { claim_deadline, .. } => {
3343 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3348 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3350 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3351 - if fail_payment { 0 } else { 2 });
3353 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3354 // and expire both immediately, though, by connecting another 4 blocks.
3355 let reason = HTLCDestination::FailedPayment { payment_hash };
3356 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3357 connect_blocks(&nodes[3], 4);
3358 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3359 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3361 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3362 check_closed_event!(&nodes[1], 1, ClosureReason::HolderForceClosed, false,
3363 [nodes[3].node.get_our_node_id()], 1000000);
3364 check_closed_broadcast(&nodes[1], 1, true);
3365 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3366 assert_eq!(bs_tx.len(), 1);
3368 mine_transaction(&nodes[3], &bs_tx[0]);
3369 check_added_monitors(&nodes[3], 1);
3370 check_closed_broadcast(&nodes[3], 1, true);
3371 check_closed_event!(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false,
3372 [nodes[1].node.get_our_node_id()], 1000000);
3374 nodes[3].node.claim_funds(payment_preimage);
3375 check_added_monitors(&nodes[3], 2);
3376 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3378 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3379 assert_eq!(ds_tx.len(), 1);
3380 check_spends!(&ds_tx[0], &bs_tx[0]);
3382 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3383 check_added_monitors(&nodes[1], 1);
3384 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3386 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3387 check_added_monitors(&nodes[1], 1);
3388 assert_eq!(bs_claims.len(), 1);
3389 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3390 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3391 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3392 } else { panic!(); }
3394 expect_payment_sent!(nodes[0], payment_preimage);
3396 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3397 assert_eq!(ds_claim_msgs.len(), 1);
3398 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3399 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3400 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3401 check_added_monitors(&nodes[2], 1);
3402 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3403 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3405 } else { panic!(); };
3407 assert_eq!(cs_claim_msgs.len(), 1);
3408 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3409 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3410 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3411 } else { panic!(); }
3413 expect_payment_path_successful!(nodes[0]);
3418 fn claim_from_closed_chan() {
3419 do_claim_from_closed_chan(true);
3420 do_claim_from_closed_chan(false);
3424 fn test_custom_tlvs_basic() {
3425 do_test_custom_tlvs(false, false, false);
3426 do_test_custom_tlvs(true, false, false);
3430 fn test_custom_tlvs_explicit_claim() {
3431 // Test that when receiving even custom TLVs the user must explicitly accept in case they
3433 do_test_custom_tlvs(false, true, false);
3434 do_test_custom_tlvs(false, true, true);
3437 fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) {
3438 let chanmon_cfgs = create_chanmon_cfgs(2);
3439 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3440 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None; 2]);
3441 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3443 create_announced_chan_between_nodes(&nodes, 0, 1);
3445 let amt_msat = 100_000;
3446 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat);
3447 let payment_id = PaymentId(our_payment_hash.0);
3448 let custom_tlvs = vec![
3449 (if even_tlvs { 5482373482 } else { 5482373483 }, vec![1, 2, 3, 4]),
3450 (5482373487, vec![0x42u8; 16]),
3452 let onion_fields = RecipientOnionFields {
3453 payment_secret: if spontaneous { None } else { Some(our_payment_secret) },
3454 payment_metadata: None,
3455 custom_tlvs: custom_tlvs.clone()
3458 nodes[0].node.send_spontaneous_payment(&route, Some(our_payment_preimage), onion_fields, payment_id).unwrap();
3460 nodes[0].node.send_payment_with_route(&route, our_payment_hash, onion_fields, payment_id).unwrap();
3462 check_added_monitors(&nodes[0], 1);
3464 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3465 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
3466 let mut payment_event = SendEvent::from_event(ev);
3468 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3469 check_added_monitors!(&nodes[1], 0);
3470 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3471 expect_pending_htlcs_forwardable!(nodes[1]);
3473 let events = nodes[1].node.get_and_clear_pending_events();
3474 assert_eq!(events.len(), 1);
3476 Event::PaymentClaimable { ref onion_fields, .. } => {
3477 assert_eq!(onion_fields.clone().unwrap().custom_tlvs().clone(), custom_tlvs);
3479 _ => panic!("Unexpected event"),
3482 match (known_tlvs, even_tlvs) {
3484 nodes[1].node.claim_funds_with_known_custom_tlvs(our_payment_preimage);
3485 let expected_total_fee_msat = pass_claimed_payment_along_route(&nodes[0], &[&[&nodes[1]]], &[0; 1], false, our_payment_preimage);
3486 expect_payment_sent!(&nodes[0], our_payment_preimage, Some(expected_total_fee_msat));
3489 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3492 nodes[1].node.claim_funds(our_payment_preimage);
3493 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3494 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], expected_destinations);
3495 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, our_payment_hash, PaymentFailureReason::RecipientRejected);
3501 fn test_retry_custom_tlvs() {
3502 // Test that custom TLVs are successfully sent on retries
3503 let chanmon_cfgs = create_chanmon_cfgs(3);
3504 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3505 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3506 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3508 create_announced_chan_between_nodes(&nodes, 0, 1);
3509 let (chan_2_update, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 2, 1);
3512 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3514 let amt_msat = 1_000_000;
3515 let (route, payment_hash, payment_preimage, payment_secret) =
3516 get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
3518 // Initiate the payment
3519 let payment_id = PaymentId(payment_hash.0);
3520 let mut route_params = RouteParameters {
3521 payment_params: route.payment_params.clone().unwrap(),
3522 final_value_msat: amt_msat,
3525 let custom_tlvs = vec![((1 << 16) + 1, vec![0x42u8; 16])];
3526 let onion_fields = RecipientOnionFields::secret_only(payment_secret);
3527 let onion_fields = onion_fields.with_custom_tlvs(custom_tlvs.clone()).unwrap();
3529 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3530 nodes[0].node.send_payment(payment_hash, onion_fields,
3531 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3532 check_added_monitors!(nodes[0], 1); // one monitor per path
3534 // Add the HTLC along the first hop.
3535 let htlc_updates = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
3536 let msgs::CommitmentUpdate { update_add_htlcs, commitment_signed, .. } = htlc_updates;
3537 assert_eq!(update_add_htlcs.len(), 1);
3538 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_htlcs[0]);
3539 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
3541 // Attempt to forward the payment and complete the path's failure.
3542 expect_pending_htlcs_forwardable!(&nodes[1]);
3543 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1],
3544 vec![HTLCDestination::NextHopChannel {
3545 node_id: Some(nodes[2].node.get_our_node_id()),
3546 channel_id: chan_2_id
3548 check_added_monitors!(nodes[1], 1);
3550 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3551 let msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } = htlc_updates;
3552 assert_eq!(update_fail_htlcs.len(), 1);
3553 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3554 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
3556 let mut events = nodes[0].node.get_and_clear_pending_events();
3558 Event::PendingHTLCsForwardable { .. } => {},
3559 _ => panic!("Unexpected event")
3562 expect_payment_failed_conditions_event(events, payment_hash, false,
3563 PaymentFailedConditions::new().mpp_parts_remain());
3565 // Rebalance the channel so the retry of the payment can succeed.
3566 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3568 // Retry the payment and make sure it succeeds
3569 route_params.payment_params.previously_failed_channels.push(chan_2_update.contents.short_channel_id);
3570 nodes[0].router.expect_find_route(route_params, Ok(route));
3571 nodes[0].node.process_pending_htlc_forwards();
3572 check_added_monitors!(nodes[0], 1);
3573 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3574 assert_eq!(events.len(), 1);
3575 let payment_claimable = pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000,
3576 payment_hash, Some(payment_secret), events.pop().unwrap(), true, None).unwrap();
3577 match payment_claimable {
3578 Event::PaymentClaimable { onion_fields, .. } => {
3579 assert_eq!(onion_fields.unwrap().custom_tlvs(), &custom_tlvs);
3581 _ => panic!("Unexpected event"),
3583 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
3587 fn test_custom_tlvs_consistency() {
3588 let even_type_1 = 1 << 16;
3589 let odd_type_1 = (1 << 16)+ 1;
3590 let even_type_2 = (1 << 16) + 2;
3591 let odd_type_2 = (1 << 16) + 3;
3592 let value_1 = || vec![1, 2, 3, 4];
3593 let differing_value_1 = || vec![1, 2, 3, 5];
3594 let value_2 = || vec![42u8; 16];
3596 // Drop missing odd tlvs
3597 do_test_custom_tlvs_consistency(
3598 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3599 vec![(odd_type_1, value_1())],
3600 Some(vec![(odd_type_1, value_1())]),
3602 // Drop non-matching odd tlvs
3603 do_test_custom_tlvs_consistency(
3604 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3605 vec![(odd_type_1, differing_value_1()), (odd_type_2, value_2())],
3606 Some(vec![(odd_type_2, value_2())]),
3608 // Fail missing even tlvs
3609 do_test_custom_tlvs_consistency(
3610 vec![(odd_type_1, value_1()), (even_type_2, value_2())],
3611 vec![(odd_type_1, value_1())],
3614 // Fail non-matching even tlvs
3615 do_test_custom_tlvs_consistency(
3616 vec![(even_type_1, value_1()), (odd_type_2, value_2())],
3617 vec![(even_type_1, differing_value_1()), (odd_type_2, value_2())],
3622 fn do_test_custom_tlvs_consistency(first_tlvs: Vec<(u64, Vec<u8>)>, second_tlvs: Vec<(u64, Vec<u8>)>,
3623 expected_receive_tlvs: Option<Vec<(u64, Vec<u8>)>>) {
3625 let chanmon_cfgs = create_chanmon_cfgs(4);
3626 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3627 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3628 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3630 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
3631 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
3632 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
3633 let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
3635 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3636 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
3637 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
3638 assert_eq!(route.paths.len(), 2);
3639 route.paths.sort_by(|path_a, _| {
3640 // Sort the path so that the path through nodes[1] comes first
3641 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3642 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
3645 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
3646 let payment_id = PaymentId([42; 32]);
3647 let amt_msat = 15_000_000;
3650 let onion_fields = RecipientOnionFields {
3651 payment_secret: Some(our_payment_secret),
3652 payment_metadata: None,
3653 custom_tlvs: first_tlvs
3655 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
3656 onion_fields.clone(), payment_id, &route).unwrap();
3657 let cur_height = nodes[0].best_block_info().1;
3658 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
3659 onion_fields.clone(), amt_msat, cur_height, payment_id,
3660 &None, session_privs[0]).unwrap();
3661 check_added_monitors!(nodes[0], 1);
3664 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3665 assert_eq!(events.len(), 1);
3666 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, our_payment_hash,
3667 Some(our_payment_secret), events.pop().unwrap(), false, None);
3669 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
3672 let onion_fields = RecipientOnionFields {
3673 payment_secret: Some(our_payment_secret),
3674 payment_metadata: None,
3675 custom_tlvs: second_tlvs
3677 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
3678 onion_fields.clone(), amt_msat, cur_height, payment_id, &None, session_privs[1]).unwrap();
3679 check_added_monitors!(nodes[0], 1);
3682 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3683 assert_eq!(events.len(), 1);
3684 let payment_event = SendEvent::from_event(events.pop().unwrap());
3686 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3687 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
3689 expect_pending_htlcs_forwardable!(nodes[2]);
3690 check_added_monitors!(nodes[2], 1);
3692 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
3693 assert_eq!(events.len(), 1);
3694 let payment_event = SendEvent::from_event(events.pop().unwrap());
3696 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
3697 check_added_monitors!(nodes[3], 0);
3698 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
3700 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3701 nodes[3].node.process_pending_htlc_forwards();
3703 if let Some(expected_tlvs) = expected_receive_tlvs {
3704 // Claim and match expected
3705 let events = nodes[3].node.get_and_clear_pending_events();
3706 assert_eq!(events.len(), 1);
3708 Event::PaymentClaimable { ref onion_fields, .. } => {
3709 assert_eq!(onion_fields.clone().unwrap().custom_tlvs, expected_tlvs);
3711 _ => panic!("Unexpected event"),
3714 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]],
3715 false, our_payment_preimage);
3716 expect_payment_sent(&nodes[0], our_payment_preimage, Some(Some(2000)), true, true);
3719 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3720 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], expected_destinations);
3721 check_added_monitors!(nodes[3], 1);
3723 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
3724 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
3725 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
3727 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![
3728 HTLCDestination::NextHopChannel {
3729 node_id: Some(nodes[3].node.get_our_node_id()),
3730 channel_id: chan_2_3.2
3732 check_added_monitors!(nodes[2], 1);
3734 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
3735 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
3736 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
3738 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true,
3739 PaymentFailedConditions::new().mpp_parts_remain());
3743 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3744 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3745 // another results in the HTLC being rejected.
3747 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3748 // first of which we'll deliver and the second of which we'll fail and then re-send with
3749 // modified payment metadata, which will in turn result in it being failed by the recipient.
3750 let chanmon_cfgs = create_chanmon_cfgs(4);
3751 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3753 let new_chain_monitor;
3755 let mut config = test_default_channel_config();
3756 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3757 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3758 let nodes_0_deserialized;
3760 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3762 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3763 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3764 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3765 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3767 // Pay more than half of each channel's max, requiring MPP
3768 let amt_msat = 750_000_000;
3769 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3770 let payment_id = PaymentId(payment_hash.0);
3771 let payment_metadata = vec![44, 49, 52, 142];
3773 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3774 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3775 let mut route_params = RouteParameters {
3777 final_value_msat: amt_msat,
3780 // Send the MPP payment, delivering the updated commitment state to nodes[1].
3781 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3782 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata), custom_tlvs: vec![],
3783 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3784 check_added_monitors!(nodes[0], 2);
3786 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3787 assert_eq!(send_events.len(), 2);
3788 let first_send = SendEvent::from_event(send_events.pop().unwrap());
3789 let second_send = SendEvent::from_event(send_events.pop().unwrap());
3791 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3792 (&first_send, &second_send)
3794 (&second_send, &first_send)
3796 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3797 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3799 expect_pending_htlcs_forwardable!(nodes[1]);
3800 check_added_monitors(&nodes[1], 1);
3801 let b_forward_ev = SendEvent::from_node(&nodes[1]);
3802 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3803 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3805 expect_pending_htlcs_forwardable!(nodes[3]);
3807 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3808 // will result in nodes[2] failing the HTLC back.
3809 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3810 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3812 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3813 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3815 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3816 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3817 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3819 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3820 assert_eq!(payment_fail_retryable_evs.len(), 2);
3821 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3822 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3824 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3825 // stored for our payment.
3827 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3830 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3831 // the payment state.
3833 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3834 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3835 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3836 persister, new_chain_monitor, nodes_0_deserialized);
3837 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3838 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
3840 let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
3841 reconnect_args.send_channel_ready = (true, true);
3842 reconnect_nodes(reconnect_args);
3844 // Create a new channel between C and D as A will refuse to retry on the existing one because
3846 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3848 // Now retry the failed HTLC.
3849 nodes[0].node.process_pending_htlc_forwards();
3850 check_added_monitors(&nodes[0], 1);
3851 let as_resend = SendEvent::from_node(&nodes[0]);
3852 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3853 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3855 expect_pending_htlcs_forwardable!(nodes[2]);
3856 check_added_monitors(&nodes[2], 1);
3857 let cs_forward = SendEvent::from_node(&nodes[2]);
3858 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3859 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3861 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3862 // the payment metadata was modified, failing only the one modified HTLC and retaining the
3865 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3866 nodes[3].node.process_pending_htlc_forwards();
3867 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3868 &[HTLCDestination::FailedPayment {payment_hash}]);
3869 nodes[3].node.process_pending_htlc_forwards();
3871 check_added_monitors(&nodes[3], 1);
3872 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3874 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3875 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3876 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3877 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3879 expect_pending_htlcs_forwardable!(nodes[3]);
3880 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3881 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3886 fn test_payment_metadata_consistency() {
3887 do_test_payment_metadata_consistency(true, true);
3888 do_test_payment_metadata_consistency(true, false);
3889 do_test_payment_metadata_consistency(false, true);
3890 do_test_payment_metadata_consistency(false, false);