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, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails, RecipientOnionFields, HTLCForwardInfo, PendingHTLCRouting, PendingAddHTLCInfo};
21 use crate::ln::features::Bolt11InvoiceFeatures;
22 use crate::ln::{msgs, PaymentSecret, PaymentPreimage};
23 use crate::ln::msgs::ChannelMessageHandler;
24 use crate::ln::outbound_payment::Retry;
25 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
26 use crate::routing::router::{get_route, Path, PaymentParameters, Route, Router, RouteHint, RouteHintHop, RouteHop, RouteParameters, find_route};
27 use crate::routing::scoring::ChannelUsage;
28 use crate::util::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
31 use crate::util::string::UntrustedString;
33 use bitcoin::network::constants::Network;
35 use crate::prelude::*;
37 use crate::ln::functional_test_utils::*;
38 use crate::routing::gossip::NodeId;
39 #[cfg(feature = "std")]
41 crate::util::time::tests::SinceEpoch,
42 std::time::{SystemTime, Instant, Duration}
47 let chanmon_cfgs = create_chanmon_cfgs(4);
48 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
49 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
50 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
52 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
53 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
54 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
55 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
57 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
58 let path = route.paths[0].clone();
59 route.paths.push(path);
60 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
61 route.paths[0].hops[0].short_channel_id = chan_1_id;
62 route.paths[0].hops[1].short_channel_id = chan_3_id;
63 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
64 route.paths[1].hops[0].short_channel_id = chan_2_id;
65 route.paths[1].hops[1].short_channel_id = chan_4_id;
66 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
67 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
72 let chanmon_cfgs = create_chanmon_cfgs(4);
73 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
74 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
75 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
77 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
78 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
79 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
80 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
82 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
84 let amt_msat = 1_000_000;
85 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
86 let path = route.paths[0].clone();
87 route.paths.push(path);
88 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
89 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
90 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
91 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
92 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
93 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
95 // Initiate the MPP payment.
96 let payment_id = PaymentId(payment_hash.0);
97 let mut route_params = RouteParameters {
98 payment_params: route.payment_params.clone().unwrap(),
99 final_value_msat: amt_msat,
102 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
103 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
104 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
105 check_added_monitors!(nodes[0], 2); // one monitor per path
106 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
107 assert_eq!(events.len(), 2);
109 // Pass half of the payment along the success path.
110 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
111 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
113 // Add the HTLC along the first hop.
114 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
115 let (update_add, commitment_signed) = match fail_path_msgs_1 {
116 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
117 assert_eq!(update_add_htlcs.len(), 1);
118 assert!(update_fail_htlcs.is_empty());
119 assert!(update_fulfill_htlcs.is_empty());
120 assert!(update_fail_malformed_htlcs.is_empty());
121 assert!(update_fee.is_none());
122 (update_add_htlcs[0].clone(), commitment_signed.clone())
124 _ => panic!("Unexpected event"),
126 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
127 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
129 // Attempt to forward the payment and complete the 2nd path's failure.
130 expect_pending_htlcs_forwardable!(&nodes[2]);
131 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_4_id }]);
132 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
133 assert!(htlc_updates.update_add_htlcs.is_empty());
134 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
135 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
136 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
137 check_added_monitors!(nodes[2], 1);
138 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
139 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
140 let mut events = nodes[0].node.get_and_clear_pending_events();
142 Event::PendingHTLCsForwardable { .. } => {},
143 _ => panic!("Unexpected event")
146 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
148 // Rebalance the channel so the second half of the payment can succeed.
149 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
151 // Retry the second half of the payment and make sure it succeeds.
152 route.paths.remove(0);
153 route_params.final_value_msat = 1_000_000;
154 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
155 nodes[0].router.expect_find_route(route_params, Ok(route));
156 nodes[0].node.process_pending_htlc_forwards();
157 check_added_monitors!(nodes[0], 1);
158 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
159 assert_eq!(events.len(), 1);
160 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
161 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
164 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
165 let chanmon_cfgs = create_chanmon_cfgs(4);
166 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
167 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
168 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
170 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
171 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
172 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
173 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
175 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
176 let path = route.paths[0].clone();
177 route.paths.push(path);
178 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
179 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
180 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
181 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
182 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
183 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
185 // Initiate the MPP payment.
186 nodes[0].node.send_payment_with_route(&route, payment_hash,
187 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
188 check_added_monitors!(nodes[0], 2); // one monitor per path
189 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
190 assert_eq!(events.len(), 2);
192 // Pass half of the payment along the first path.
193 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
194 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
196 if send_partial_mpp {
197 // Time out the partial MPP
198 for _ in 0..MPP_TIMEOUT_TICKS {
199 nodes[3].node.timer_tick_occurred();
202 // Failed HTLC from node 3 -> 1
203 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
204 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
205 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
206 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
207 check_added_monitors!(nodes[3], 1);
208 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
210 // Failed HTLC from node 1 -> 0
211 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_3_id }]);
212 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
213 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
214 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
215 check_added_monitors!(nodes[1], 1);
216 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
218 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
220 // Pass half of the payment along the second path.
221 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
222 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
224 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
225 for _ in 0..MPP_TIMEOUT_TICKS {
226 nodes[3].node.timer_tick_occurred();
229 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
234 fn mpp_receive_timeout() {
235 do_mpp_receive_timeout(true);
236 do_mpp_receive_timeout(false);
240 fn test_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);
517 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
518 let persister: test_utils::TestPersister;
519 let new_chain_monitor: test_utils::TestChainMonitor;
520 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
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);
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 {}", &nodes[1].node.get_our_node_id())) });
606 check_added_monitors!(nodes[1], 1);
607 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
609 _ => panic!("Unexpected event"),
611 check_closed_broadcast!(nodes[1], false);
613 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
614 // we close in a moment.
615 nodes[2].node.claim_funds(payment_preimage_1);
616 check_added_monitors!(nodes[2], 1);
617 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
619 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
620 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
621 check_added_monitors!(nodes[1], 1);
622 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
623 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
625 if confirm_before_reload {
626 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
627 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
630 // Create a new channel on which to retry the payment before we fail the payment via the
631 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
632 // connecting several blocks while creating the channel (implying time has passed).
633 create_announced_chan_between_nodes(&nodes, 0, 1);
634 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
636 mine_transaction(&nodes[1], &as_commitment_tx);
637 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
638 assert_eq!(bs_htlc_claim_txn.len(), 1);
639 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
641 if !confirm_before_reload {
642 mine_transaction(&nodes[0], &as_commitment_tx);
644 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
645 expect_payment_sent!(nodes[0], payment_preimage_1);
646 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
647 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
648 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
649 assert_eq!(txn.len(), 2);
650 (txn.remove(0), txn.remove(0))
652 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
653 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
654 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
655 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
657 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
659 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
660 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
662 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
663 // reloaded) via a route over the new channel, which work without issue and eventually be
664 // received and claimed at the recipient just like any other payment.
665 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
667 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
668 // and not the original fee. We also update node[1]'s relevant config as
669 // do_claim_payment_along_route expects us to never overpay.
671 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
672 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
673 .unwrap().lock().unwrap();
674 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
675 let mut new_config = channel.context.config();
676 new_config.forwarding_fee_base_msat += 100_000;
677 channel.context.update_config(&new_config);
678 new_route.paths[0].hops[0].fee_msat += 100_000;
681 // Force expiration of the channel's previous config.
682 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
683 nodes[1].node.timer_tick_occurred();
686 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
687 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
688 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
689 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
690 check_added_monitors!(nodes[0], 1);
691 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
692 assert_eq!(events.len(), 1);
693 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
694 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
695 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
699 fn retry_with_no_persist() {
700 do_retry_with_no_persist(true);
701 do_retry_with_no_persist(false);
704 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
705 // Test that an off-chain completed payment is not retryable on restart. This was previously
706 // broken for dust payments, but we test for both dust and non-dust payments.
708 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
710 let chanmon_cfgs = create_chanmon_cfgs(3);
711 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
713 let mut manually_accept_config = test_default_channel_config();
714 manually_accept_config.manually_accept_inbound_channels = true;
716 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
718 let first_persister: test_utils::TestPersister;
719 let first_new_chain_monitor: test_utils::TestChainMonitor;
720 let first_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
721 let second_persister: test_utils::TestPersister;
722 let second_new_chain_monitor: test_utils::TestChainMonitor;
723 let second_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
724 let third_persister: test_utils::TestPersister;
725 let third_new_chain_monitor: test_utils::TestChainMonitor;
726 let third_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
728 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
730 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
731 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
732 confirm_transaction(&nodes[0], &funding_tx);
733 confirm_transaction(&nodes[1], &funding_tx);
734 // Ignore the announcement_signatures messages
735 nodes[0].node.get_and_clear_pending_msg_events();
736 nodes[1].node.get_and_clear_pending_msg_events();
737 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
739 // Serialize the ChannelManager prior to sending payments
740 let mut nodes_0_serialized = nodes[0].node.encode();
742 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
743 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 });
745 // The ChannelMonitor should always be the latest version, as we're required to persist it
746 // during the `commitment_signed_dance!()`.
747 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
749 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);
750 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
752 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
753 // force-close the channel.
754 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
755 nodes[0].node.timer_tick_occurred();
756 assert!(nodes[0].node.list_channels().is_empty());
757 assert!(nodes[0].node.has_pending_payments());
758 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
759 check_added_monitors!(nodes[0], 1);
761 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
762 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
764 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
766 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
767 // error, as the channel has hit the chain.
768 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
769 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
771 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
772 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
773 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
774 assert_eq!(as_err.len(), 1);
775 let bs_commitment_tx;
777 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
778 assert_eq!(node_id, nodes[1].node.get_our_node_id());
779 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
780 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())) });
781 check_added_monitors!(nodes[1], 1);
782 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
784 _ => panic!("Unexpected event"),
786 check_closed_broadcast!(nodes[1], false);
788 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
789 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
790 // incoming HTLCs with the same payment hash later.
791 nodes[2].node.fail_htlc_backwards(&payment_hash);
792 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
793 check_added_monitors!(nodes[2], 1);
795 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
796 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
797 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
798 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
799 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
801 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
802 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
803 // after the commitment transaction, so always connect the commitment transaction.
804 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
805 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
807 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
808 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
809 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
810 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
811 assert_eq!(as_htlc_timeout.len(), 1);
813 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
814 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
815 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
816 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
819 // Create a new channel on which to retry the payment before we fail the payment via the
820 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
821 // connecting several blocks while creating the channel (implying time has passed).
822 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
823 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
824 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
826 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
827 // confirming, we will fail as it's considered still-pending...
828 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
829 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
830 Err(PaymentSendFailure::DuplicatePayment) => {},
831 _ => panic!("Unexpected error")
833 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
835 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
836 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
837 // (which should also still work).
838 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
839 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
840 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
842 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
843 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
844 nodes_0_serialized = nodes[0].node.encode();
846 // After the payment failed, we're free to send it again.
847 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
848 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
849 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
851 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);
852 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
854 nodes[0].node.test_process_background_events();
855 check_added_monitors(&nodes[0], 1);
857 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
858 reconnect_args.send_channel_ready = (true, true);
859 reconnect_nodes(reconnect_args);
861 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
862 // the payment is not (spuriously) listed as still pending.
863 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
864 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
865 check_added_monitors!(nodes[0], 1);
866 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
867 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
869 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
870 Err(PaymentSendFailure::DuplicatePayment) => {},
871 _ => panic!("Unexpected error")
873 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
875 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
876 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
877 nodes_0_serialized = nodes[0].node.encode();
879 // Check that after reload we can send the payment again (though we shouldn't, since it was
880 // claimed previously).
881 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);
882 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
884 nodes[0].node.test_process_background_events();
885 check_added_monitors(&nodes[0], 1);
887 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
889 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
890 Err(PaymentSendFailure::DuplicatePayment) => {},
891 _ => panic!("Unexpected error")
893 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
897 fn test_completed_payment_not_retryable_on_reload() {
898 do_test_completed_payment_not_retryable_on_reload(true);
899 do_test_completed_payment_not_retryable_on_reload(false);
903 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
904 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
905 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
906 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
907 // the ChannelMonitor tells it to.
909 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
910 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
911 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
912 let chanmon_cfgs = create_chanmon_cfgs(2);
913 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
914 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
915 let persister: test_utils::TestPersister;
916 let new_chain_monitor: test_utils::TestChainMonitor;
917 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
918 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
920 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
922 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
924 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
925 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
926 check_closed_broadcast!(nodes[0], true);
927 check_added_monitors!(nodes[0], 1);
928 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
930 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
931 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
933 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
934 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
935 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
936 assert_eq!(node_txn.len(), 3);
937 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
938 check_spends!(node_txn[1], funding_tx);
939 check_spends!(node_txn[2], node_txn[1]);
940 let timeout_txn = vec![node_txn[2].clone()];
942 nodes[1].node.claim_funds(payment_preimage);
943 check_added_monitors!(nodes[1], 1);
944 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
946 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[1].clone()]));
947 check_closed_broadcast!(nodes[1], true);
948 check_added_monitors!(nodes[1], 1);
949 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
950 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
951 assert_eq!(claim_txn.len(), 1);
952 check_spends!(claim_txn[0], node_txn[1]);
954 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[1].clone()]));
956 if confirm_commitment_tx {
957 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
960 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] });
963 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
964 connect_block(&nodes[0], &claim_block);
965 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
968 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
969 // returning InProgress. This should cause the claim event to never make its way to the
971 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
972 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
975 connect_blocks(&nodes[0], 1);
977 connect_block(&nodes[0], &claim_block);
980 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
981 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
982 .get_mut(&funding_txo).unwrap().drain().collect();
983 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
984 // If we're testing connection idempotency we may get substantially more.
985 assert!(mon_updates.len() >= 1);
986 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
987 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
989 // If we persist the ChannelManager here, we should get the PaymentSent event after
991 let mut chan_manager_serialized = Vec::new();
992 if !persist_manager_post_event {
993 chan_manager_serialized = nodes[0].node.encode();
996 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
997 // payment sent event.
998 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
999 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1000 for update in mon_updates {
1001 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
1003 if payment_timeout {
1004 expect_payment_failed!(nodes[0], payment_hash, false);
1006 expect_payment_sent!(nodes[0], payment_preimage);
1009 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
1011 if persist_manager_post_event {
1012 chan_manager_serialized = nodes[0].node.encode();
1015 // Now reload nodes[0]...
1016 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
1018 if persist_manager_post_event {
1019 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1020 } else if payment_timeout {
1021 expect_payment_failed!(nodes[0], payment_hash, false);
1023 expect_payment_sent!(nodes[0], payment_preimage);
1026 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
1027 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
1028 // payment events should kick in, leaving us with no pending events here.
1029 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
1030 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
1031 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1032 check_added_monitors(&nodes[0], 1);
1036 fn test_dup_htlc_onchain_fails_on_reload() {
1037 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
1038 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
1039 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
1040 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
1041 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
1042 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
1046 fn test_fulfill_restart_failure() {
1047 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
1048 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
1049 // again, or fail it, giving us free money.
1051 // Of course probably they won't fail it and give us free money, but because we have code to
1052 // handle it, we should test the logic for it anyway. We do that here.
1053 let chanmon_cfgs = create_chanmon_cfgs(2);
1054 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1055 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1056 let persister: test_utils::TestPersister;
1057 let new_chain_monitor: test_utils::TestChainMonitor;
1058 let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
1059 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1061 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1062 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
1064 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
1065 // pre-fulfill, which we do by serializing it here.
1066 let chan_manager_serialized = nodes[1].node.encode();
1067 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1069 nodes[1].node.claim_funds(payment_preimage);
1070 check_added_monitors!(nodes[1], 1);
1071 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1073 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1074 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1075 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
1077 // Now reload nodes[1]...
1078 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1080 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1081 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1083 nodes[1].node.fail_htlc_backwards(&payment_hash);
1084 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1085 check_added_monitors!(nodes[1], 1);
1086 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1087 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1088 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1089 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1090 // it had already considered the payment fulfilled, and now they just got free money.
1091 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1095 fn get_ldk_payment_preimage() {
1096 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1097 let chanmon_cfgs = create_chanmon_cfgs(2);
1098 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1099 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1100 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1101 create_announced_chan_between_nodes(&nodes, 0, 1);
1103 let amt_msat = 60_000;
1104 let expiry_secs = 60 * 60;
1105 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1107 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1108 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
1109 let scorer = test_utils::TestScorer::new();
1110 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1111 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1112 let route = get_route(
1113 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
1114 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
1115 amt_msat, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
1116 nodes[0].node.send_payment_with_route(&route, payment_hash,
1117 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1118 check_added_monitors!(nodes[0], 1);
1120 // Make sure to use `get_payment_preimage`
1121 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1122 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1123 assert_eq!(events.len(), 1);
1124 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1125 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1129 fn sent_probe_is_probe_of_sending_node() {
1130 let chanmon_cfgs = create_chanmon_cfgs(3);
1131 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1132 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1133 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1135 create_announced_chan_between_nodes(&nodes, 0, 1);
1136 create_announced_chan_between_nodes(&nodes, 1, 2);
1138 // First check we refuse to build a single-hop probe
1139 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1140 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1142 // Then build an actual two-hop probing path
1143 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1145 match nodes[0].node.send_probe(route.paths[0].clone()) {
1146 Ok((payment_hash, payment_id)) => {
1147 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1148 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1149 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1154 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1155 check_added_monitors!(nodes[0], 1);
1159 fn successful_probe_yields_event() {
1160 let chanmon_cfgs = create_chanmon_cfgs(3);
1161 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1162 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1163 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1165 create_announced_chan_between_nodes(&nodes, 0, 1);
1166 create_announced_chan_between_nodes(&nodes, 1, 2);
1168 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1170 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1172 // node[0] -- update_add_htlcs -> node[1]
1173 check_added_monitors!(nodes[0], 1);
1174 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1175 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1176 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1177 check_added_monitors!(nodes[1], 0);
1178 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1179 expect_pending_htlcs_forwardable!(nodes[1]);
1181 // node[1] -- update_add_htlcs -> node[2]
1182 check_added_monitors!(nodes[1], 1);
1183 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1184 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1185 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1186 check_added_monitors!(nodes[2], 0);
1187 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
1189 // node[1] <- update_fail_htlcs -- node[2]
1190 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1191 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1192 check_added_monitors!(nodes[1], 0);
1193 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1195 // node[0] <- update_fail_htlcs -- node[1]
1196 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1197 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1198 check_added_monitors!(nodes[0], 0);
1199 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1201 let mut events = nodes[0].node.get_and_clear_pending_events();
1202 assert_eq!(events.len(), 1);
1203 match events.drain(..).next().unwrap() {
1204 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1205 assert_eq!(payment_id, ev_pid);
1206 assert_eq!(payment_hash, ev_ph);
1210 assert!(!nodes[0].node.has_pending_payments());
1214 fn failed_probe_yields_event() {
1215 let chanmon_cfgs = create_chanmon_cfgs(3);
1216 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1217 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1218 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1220 create_announced_chan_between_nodes(&nodes, 0, 1);
1221 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1223 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1225 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000);
1227 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1229 // node[0] -- update_add_htlcs -> node[1]
1230 check_added_monitors!(nodes[0], 1);
1231 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1232 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1233 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1234 check_added_monitors!(nodes[1], 0);
1235 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1236 expect_pending_htlcs_forwardable!(nodes[1]);
1238 // node[0] <- update_fail_htlcs -- node[1]
1239 check_added_monitors!(nodes[1], 1);
1240 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1241 // Skip the PendingHTLCsForwardable event
1242 let _events = nodes[1].node.get_and_clear_pending_events();
1243 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1244 check_added_monitors!(nodes[0], 0);
1245 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1247 let mut events = nodes[0].node.get_and_clear_pending_events();
1248 assert_eq!(events.len(), 1);
1249 match events.drain(..).next().unwrap() {
1250 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1251 assert_eq!(payment_id, ev_pid);
1252 assert_eq!(payment_hash, ev_ph);
1256 assert!(!nodes[0].node.has_pending_payments());
1260 fn onchain_failed_probe_yields_event() {
1261 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1263 let chanmon_cfgs = create_chanmon_cfgs(3);
1264 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1265 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1266 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1268 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1269 create_announced_chan_between_nodes(&nodes, 1, 2);
1271 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1273 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1274 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000);
1275 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1277 // node[0] -- update_add_htlcs -> node[1]
1278 check_added_monitors!(nodes[0], 1);
1279 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1280 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1281 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1282 check_added_monitors!(nodes[1], 0);
1283 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1284 expect_pending_htlcs_forwardable!(nodes[1]);
1286 check_added_monitors!(nodes[1], 1);
1287 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1289 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1290 // Node A, which after 6 confirmations should result in a probe failure event.
1291 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1292 confirm_transaction(&nodes[0], &bs_txn[0]);
1293 check_closed_broadcast!(&nodes[0], true);
1294 check_added_monitors!(nodes[0], 1);
1296 let mut events = nodes[0].node.get_and_clear_pending_events();
1297 assert_eq!(events.len(), 2);
1298 let mut found_probe_failed = false;
1299 for event in events.drain(..) {
1301 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1302 assert_eq!(payment_id, ev_pid);
1303 assert_eq!(payment_hash, ev_ph);
1304 found_probe_failed = true;
1306 Event::ChannelClosed { .. } => {},
1310 assert!(found_probe_failed);
1311 assert!(!nodes[0].node.has_pending_payments());
1315 fn claimed_send_payment_idempotent() {
1316 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1317 let chanmon_cfgs = create_chanmon_cfgs(2);
1318 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1319 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1320 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1322 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1324 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1325 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1327 macro_rules! check_send_rejected {
1329 // If we try to resend a new payment with a different payment_hash but with the same
1330 // payment_id, it should be rejected.
1331 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1332 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1334 Err(PaymentSendFailure::DuplicatePayment) => {},
1335 _ => panic!("Unexpected send result: {:?}", send_result),
1338 // Further, if we try to send a spontaneous payment with the same payment_id it should
1339 // also be rejected.
1340 let send_result = nodes[0].node.send_spontaneous_payment(
1341 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1343 Err(PaymentSendFailure::DuplicatePayment) => {},
1344 _ => panic!("Unexpected send result: {:?}", send_result),
1349 check_send_rejected!();
1351 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1352 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1353 // we must remain just as idempotent as we were before.
1354 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1356 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1357 nodes[0].node.timer_tick_occurred();
1360 check_send_rejected!();
1362 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1363 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1364 // the payment complete. However, they could have called `send_payment` while the event was
1365 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1366 // after the event is handled a duplicate payment should sitll be rejected.
1367 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1368 check_send_rejected!();
1370 // If relatively little time has passed, a duplicate payment should still fail.
1371 nodes[0].node.timer_tick_occurred();
1372 check_send_rejected!();
1374 // However, after some time has passed (at least more than the one timer tick above), a
1375 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1376 // references to the old payment data.
1377 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1378 nodes[0].node.timer_tick_occurred();
1381 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1382 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1383 check_added_monitors!(nodes[0], 1);
1384 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1385 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1389 fn abandoned_send_payment_idempotent() {
1390 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1392 let chanmon_cfgs = create_chanmon_cfgs(2);
1393 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1394 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1395 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1397 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1399 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1400 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1402 macro_rules! check_send_rejected {
1404 // If we try to resend a new payment with a different payment_hash but with the same
1405 // payment_id, it should be rejected.
1406 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1407 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1409 Err(PaymentSendFailure::DuplicatePayment) => {},
1410 _ => panic!("Unexpected send result: {:?}", send_result),
1413 // Further, if we try to send a spontaneous payment with the same payment_id it should
1414 // also be rejected.
1415 let send_result = nodes[0].node.send_spontaneous_payment(
1416 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1418 Err(PaymentSendFailure::DuplicatePayment) => {},
1419 _ => panic!("Unexpected send result: {:?}", send_result),
1424 check_send_rejected!();
1426 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1427 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1429 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1431 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1432 nodes[0].node.timer_tick_occurred();
1434 check_send_rejected!();
1436 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1438 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1439 // failed payment back.
1440 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1441 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1442 check_added_monitors!(nodes[0], 1);
1443 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1444 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1447 #[derive(PartialEq)]
1448 enum InterceptTest {
1455 fn test_trivial_inflight_htlc_tracking(){
1456 // In this test, we test three scenarios:
1457 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1458 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1459 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1460 let chanmon_cfgs = create_chanmon_cfgs(3);
1461 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1462 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1463 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1465 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1466 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1468 // Send and claim the payment. Inflight HTLCs should be empty.
1469 let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1470 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1472 let mut node_0_per_peer_lock;
1473 let mut node_0_peer_state_lock;
1474 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1476 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1477 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1478 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1479 channel_1.context.get_short_channel_id().unwrap()
1481 assert_eq!(chan_1_used_liquidity, None);
1484 let mut node_1_per_peer_lock;
1485 let mut node_1_peer_state_lock;
1486 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1488 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1489 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1490 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1491 channel_2.context.get_short_channel_id().unwrap()
1494 assert_eq!(chan_2_used_liquidity, None);
1496 let pending_payments = nodes[0].node.list_recent_payments();
1497 assert_eq!(pending_payments.len(), 1);
1498 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1500 // Remove fulfilled payment
1501 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1502 nodes[0].node.timer_tick_occurred();
1505 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1506 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1507 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1509 let mut node_0_per_peer_lock;
1510 let mut node_0_peer_state_lock;
1511 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1513 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1514 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1515 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1516 channel_1.context.get_short_channel_id().unwrap()
1518 // First hop accounts for expected 1000 msat fee
1519 assert_eq!(chan_1_used_liquidity, Some(501000));
1522 let mut node_1_per_peer_lock;
1523 let mut node_1_peer_state_lock;
1524 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1526 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1527 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1528 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1529 channel_2.context.get_short_channel_id().unwrap()
1532 assert_eq!(chan_2_used_liquidity, Some(500000));
1534 let pending_payments = nodes[0].node.list_recent_payments();
1535 assert_eq!(pending_payments.len(), 1);
1536 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1538 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1539 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1541 // Remove fulfilled payment
1542 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1543 nodes[0].node.timer_tick_occurred();
1546 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1548 let mut node_0_per_peer_lock;
1549 let mut node_0_peer_state_lock;
1550 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1552 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1553 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1554 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1555 channel_1.context.get_short_channel_id().unwrap()
1557 assert_eq!(chan_1_used_liquidity, None);
1560 let mut node_1_per_peer_lock;
1561 let mut node_1_peer_state_lock;
1562 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1564 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1565 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1566 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1567 channel_2.context.get_short_channel_id().unwrap()
1569 assert_eq!(chan_2_used_liquidity, None);
1572 let pending_payments = nodes[0].node.list_recent_payments();
1573 assert_eq!(pending_payments.len(), 0);
1577 fn test_holding_cell_inflight_htlcs() {
1578 let chanmon_cfgs = create_chanmon_cfgs(2);
1579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1581 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1582 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1584 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1585 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1587 // Queue up two payments - one will be delivered right away, one immediately goes into the
1588 // holding cell as nodes[0] is AwaitingRAA.
1590 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1591 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1592 check_added_monitors!(nodes[0], 1);
1593 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1594 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1595 check_added_monitors!(nodes[0], 0);
1598 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1601 let mut node_0_per_peer_lock;
1602 let mut node_0_peer_state_lock;
1603 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1605 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1606 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1607 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1608 channel.context.get_short_channel_id().unwrap()
1611 assert_eq!(used_liquidity, Some(2000000));
1614 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1615 nodes[0].node.get_and_clear_pending_msg_events();
1619 fn intercepted_payment() {
1620 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1621 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1622 // payment or (b) fail the payment.
1623 do_test_intercepted_payment(InterceptTest::Forward);
1624 do_test_intercepted_payment(InterceptTest::Fail);
1625 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1626 do_test_intercepted_payment(InterceptTest::Timeout);
1629 fn do_test_intercepted_payment(test: InterceptTest) {
1630 let chanmon_cfgs = create_chanmon_cfgs(3);
1631 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1633 let mut zero_conf_chan_config = test_default_channel_config();
1634 zero_conf_chan_config.manually_accept_inbound_channels = true;
1635 let mut intercept_forwards_config = test_default_channel_config();
1636 intercept_forwards_config.accept_intercept_htlcs = true;
1637 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1639 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1640 let scorer = test_utils::TestScorer::new();
1641 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1643 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1645 let amt_msat = 100_000;
1646 let intercept_scid = nodes[1].node.get_intercept_scid();
1647 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1648 .with_route_hints(vec![
1649 RouteHint(vec![RouteHintHop {
1650 src_node_id: nodes[1].node.get_our_node_id(),
1651 short_channel_id: intercept_scid,
1654 proportional_millionths: 0,
1656 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1657 htlc_minimum_msat: None,
1658 htlc_maximum_msat: None,
1661 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1662 let route_params = RouteParameters {
1664 final_value_msat: amt_msat,
1666 let route = get_route(
1667 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1668 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1669 nodes[0].logger, &scorer, &(), &random_seed_bytes,
1672 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1673 nodes[0].node.send_payment_with_route(&route, payment_hash,
1674 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1675 let payment_event = {
1677 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1678 assert_eq!(added_monitors.len(), 1);
1679 added_monitors.clear();
1681 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1682 assert_eq!(events.len(), 1);
1683 SendEvent::from_event(events.remove(0))
1685 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1686 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1688 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1689 let events = nodes[1].node.get_and_clear_pending_events();
1690 assert_eq!(events.len(), 1);
1691 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1692 crate::events::Event::HTLCIntercepted {
1693 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1695 assert_eq!(pmt_hash, payment_hash);
1696 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1697 assert_eq!(short_channel_id, intercept_scid);
1698 (intercept_id, expected_outbound_amount_msat)
1703 // Check for unknown channel id error.
1704 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();
1705 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable {
1706 err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1707 log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1709 if test == InterceptTest::Fail {
1710 // Ensure we can fail the intercepted payment back.
1711 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1712 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1713 nodes[1].node.process_pending_htlc_forwards();
1714 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1715 check_added_monitors!(&nodes[1], 1);
1716 assert!(update_fail.update_fail_htlcs.len() == 1);
1717 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1718 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1719 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1721 // Ensure the payment fails with the expected error.
1722 let fail_conditions = PaymentFailedConditions::new()
1723 .blamed_scid(intercept_scid)
1724 .blamed_chan_closed(true)
1725 .expected_htlc_error_data(0x4000 | 10, &[]);
1726 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1727 } else if test == InterceptTest::Forward {
1728 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1729 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1730 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();
1731 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1732 err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1733 log_bytes!(temp_chan_id), nodes[2].node.get_our_node_id()) });
1734 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1736 // Open the just-in-time channel so the payment can then be forwarded.
1737 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1739 // Finally, forward the intercepted payment through and claim it.
1740 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1741 expect_pending_htlcs_forwardable!(nodes[1]);
1743 let payment_event = {
1745 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1746 assert_eq!(added_monitors.len(), 1);
1747 added_monitors.clear();
1749 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1750 assert_eq!(events.len(), 1);
1751 SendEvent::from_event(events.remove(0))
1753 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1754 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1755 expect_pending_htlcs_forwardable!(nodes[2]);
1757 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1758 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1759 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1760 let events = nodes[0].node.get_and_clear_pending_events();
1761 assert_eq!(events.len(), 2);
1763 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1764 assert_eq!(payment_preimage, *ev_preimage);
1765 assert_eq!(payment_hash, *ev_hash);
1766 assert_eq!(fee_paid_msat, &Some(1000));
1768 _ => panic!("Unexpected event")
1771 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1772 assert_eq!(hash, Some(payment_hash));
1774 _ => panic!("Unexpected event")
1776 } else if test == InterceptTest::Timeout {
1777 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
1778 connect_block(&nodes[0], &block);
1779 connect_block(&nodes[1], &block);
1780 for _ in 0..TEST_FINAL_CLTV {
1781 block.header.prev_blockhash = block.block_hash();
1782 connect_block(&nodes[0], &block);
1783 connect_block(&nodes[1], &block);
1785 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1786 check_added_monitors!(nodes[1], 1);
1787 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1788 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1789 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1790 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1791 assert!(htlc_timeout_updates.update_fee.is_none());
1793 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1794 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1795 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1797 // Check for unknown intercept id error.
1798 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1799 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();
1800 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1801 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1802 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1807 fn accept_underpaying_htlcs_config() {
1808 do_accept_underpaying_htlcs_config(1);
1809 do_accept_underpaying_htlcs_config(2);
1810 do_accept_underpaying_htlcs_config(3);
1813 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
1814 let chanmon_cfgs = create_chanmon_cfgs(3);
1815 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1816 let mut intercept_forwards_config = test_default_channel_config();
1817 intercept_forwards_config.accept_intercept_htlcs = true;
1818 let mut underpay_config = test_default_channel_config();
1819 underpay_config.channel_config.accept_underpaying_htlcs = true;
1820 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
1821 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1823 let mut chan_ids = Vec::new();
1824 for _ in 0..num_mpp_parts {
1825 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000, 0);
1826 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 2_000_000, 0).0.channel_id;
1827 chan_ids.push(channel_id);
1830 // Send the initial payment.
1831 let amt_msat = 900_000;
1832 let skimmed_fee_msat = 20;
1833 let mut route_hints = Vec::new();
1834 for _ in 0..num_mpp_parts {
1835 route_hints.push(RouteHint(vec![RouteHintHop {
1836 src_node_id: nodes[1].node.get_our_node_id(),
1837 short_channel_id: nodes[1].node.get_intercept_scid(),
1840 proportional_millionths: 0,
1842 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1843 htlc_minimum_msat: None,
1844 htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
1847 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1848 .with_route_hints(route_hints).unwrap()
1849 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1850 let route_params = RouteParameters {
1852 final_value_msat: amt_msat,
1854 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1855 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1856 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
1857 check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
1858 let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
1859 assert_eq!(events.len(), num_mpp_parts);
1861 // Forward the intercepted payments.
1862 for (idx, ev) in events.into_iter().enumerate() {
1863 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
1864 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
1866 let events = nodes[1].node.get_and_clear_pending_events();
1867 assert_eq!(events.len(), 1);
1868 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
1869 crate::events::Event::HTLCIntercepted {
1870 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
1872 assert_eq!(pmt_hash, payment_hash);
1873 (intercept_id, expected_outbound_amount_msat)
1877 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
1878 nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
1879 expect_pending_htlcs_forwardable!(nodes[1]);
1880 let payment_event = {
1882 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1883 assert_eq!(added_monitors.len(), 1);
1884 added_monitors.clear();
1886 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1887 assert_eq!(events.len(), 1);
1888 SendEvent::from_event(events.remove(0))
1890 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1891 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
1892 if idx == num_mpp_parts - 1 {
1893 expect_pending_htlcs_forwardable!(nodes[2]);
1897 // Claim the payment and check that the skimmed fee is as expected.
1898 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1899 let events = nodes[2].node.get_and_clear_pending_events();
1900 assert_eq!(events.len(), 1);
1902 crate::events::Event::PaymentClaimable {
1903 ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
1905 assert_eq!(payment_hash, payment_hash);
1906 assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
1907 assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
1908 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1910 crate::events::PaymentPurpose::InvoicePayment { payment_preimage: ev_payment_preimage,
1911 payment_secret: ev_payment_secret, .. } =>
1913 assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
1914 assert_eq!(payment_secret, *ev_payment_secret);
1919 _ => panic!("Unexpected event"),
1921 let mut expected_paths_vecs = Vec::new();
1922 let mut expected_paths = Vec::new();
1923 for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
1924 for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
1925 let total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
1926 &nodes[0], &expected_paths[..], &vec![skimmed_fee_msat as u32; num_mpp_parts][..], false,
1928 // The sender doesn't know that the penultimate hop took an extra fee.
1929 expect_payment_sent(&nodes[0], payment_preimage,
1930 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true);
1933 #[derive(PartialEq)]
1944 fn automatic_retries() {
1945 do_automatic_retries(AutoRetry::Success);
1946 do_automatic_retries(AutoRetry::Spontaneous);
1947 do_automatic_retries(AutoRetry::FailAttempts);
1948 do_automatic_retries(AutoRetry::FailTimeout);
1949 do_automatic_retries(AutoRetry::FailOnRestart);
1950 do_automatic_retries(AutoRetry::FailOnRetry);
1952 fn do_automatic_retries(test: AutoRetry) {
1953 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1955 let chanmon_cfgs = create_chanmon_cfgs(3);
1956 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1957 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1960 let new_chain_monitor;
1961 let node_0_deserialized;
1963 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1964 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1965 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1967 // Marshall data to send the payment
1968 #[cfg(feature = "std")]
1969 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1970 #[cfg(not(feature = "std"))]
1971 let payment_expiry_secs = 60 * 60;
1972 let amt_msat = 1000;
1973 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1974 invoice_features.set_variable_length_onion_required();
1975 invoice_features.set_payment_secret_required();
1976 invoice_features.set_basic_mpp_optional();
1977 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1978 .with_expiry_time(payment_expiry_secs as u64)
1979 .with_bolt11_features(invoice_features).unwrap();
1980 let route_params = RouteParameters {
1982 final_value_msat: amt_msat,
1984 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1986 macro_rules! pass_failed_attempt_with_retry_along_path {
1987 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1988 // Send a payment attempt that fails due to lack of liquidity on the second hop
1989 check_added_monitors!(nodes[0], 1);
1990 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1991 let mut update_add = update_0.update_add_htlcs[0].clone();
1992 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1993 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1994 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1995 nodes[1].node.process_pending_htlc_forwards();
1996 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1997 vec![HTLCDestination::NextHopChannel {
1998 node_id: Some(nodes[2].node.get_our_node_id()),
1999 channel_id: $failing_channel_id,
2001 nodes[1].node.process_pending_htlc_forwards();
2002 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2003 check_added_monitors!(&nodes[1], 1);
2004 assert!(update_1.update_fail_htlcs.len() == 1);
2005 let fail_msg = update_1.update_fail_htlcs[0].clone();
2006 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
2007 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
2009 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
2010 let mut events = nodes[0].node.get_and_clear_pending_events();
2011 assert_eq!(events.len(), 2);
2013 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2014 assert_eq!(payment_hash, ev_payment_hash);
2015 assert_eq!(payment_failed_permanently, false);
2017 _ => panic!("Unexpected event"),
2019 if $expect_pending_htlcs_forwardable {
2021 Event::PendingHTLCsForwardable { .. } => {},
2022 _ => panic!("Unexpected event"),
2026 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
2027 assert_eq!(payment_hash, ev_payment_hash);
2029 _ => panic!("Unexpected event"),
2035 if test == AutoRetry::Success {
2036 // Test that we can succeed on the first retry.
2037 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2038 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2039 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2041 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2042 // attempt, since the initial second hop channel will be excluded from pathfinding
2043 create_announced_chan_between_nodes(&nodes, 1, 2);
2045 // We retry payments in `process_pending_htlc_forwards`
2046 nodes[0].node.process_pending_htlc_forwards();
2047 check_added_monitors!(nodes[0], 1);
2048 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2049 assert_eq!(msg_events.len(), 1);
2050 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
2051 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2052 } else if test == AutoRetry::Spontaneous {
2053 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
2054 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
2055 Retry::Attempts(1)).unwrap();
2056 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2058 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2059 // attempt, since the initial second hop channel will be excluded from pathfinding
2060 create_announced_chan_between_nodes(&nodes, 1, 2);
2062 // We retry payments in `process_pending_htlc_forwards`
2063 nodes[0].node.process_pending_htlc_forwards();
2064 check_added_monitors!(nodes[0], 1);
2065 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2066 assert_eq!(msg_events.len(), 1);
2067 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2068 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2069 } else if test == AutoRetry::FailAttempts {
2070 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2071 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2072 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2073 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2075 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2076 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2077 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2079 // We retry payments in `process_pending_htlc_forwards`
2080 nodes[0].node.process_pending_htlc_forwards();
2081 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2083 // Ensure we won't retry a second time.
2084 nodes[0].node.process_pending_htlc_forwards();
2085 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2086 assert_eq!(msg_events.len(), 0);
2087 } else if test == AutoRetry::FailTimeout {
2088 #[cfg(not(feature = "no-std"))] {
2089 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2090 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2091 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2092 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2094 // Advance the time so the second attempt fails due to timeout.
2095 SinceEpoch::advance(Duration::from_secs(61));
2097 // Make sure we don't retry again.
2098 nodes[0].node.process_pending_htlc_forwards();
2099 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2100 assert_eq!(msg_events.len(), 0);
2102 let mut events = nodes[0].node.get_and_clear_pending_events();
2103 assert_eq!(events.len(), 1);
2105 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2106 assert_eq!(payment_hash, *ev_payment_hash);
2107 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2108 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2110 _ => panic!("Unexpected event"),
2113 } else if test == AutoRetry::FailOnRestart {
2114 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2115 // attempts remaining prior to restart.
2116 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2117 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2118 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2120 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2121 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2122 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2124 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2125 nodes[0].node.process_pending_htlc_forwards();
2126 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2128 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2129 let node_encoded = nodes[0].node.encode();
2130 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2131 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2133 let mut events = nodes[0].node.get_and_clear_pending_events();
2134 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2135 // Make sure we don't retry again.
2136 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2137 assert_eq!(msg_events.len(), 0);
2139 let mut events = nodes[0].node.get_and_clear_pending_events();
2140 assert_eq!(events.len(), 1);
2142 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2143 assert_eq!(payment_hash, *ev_payment_hash);
2144 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2145 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2147 _ => panic!("Unexpected event"),
2149 } else if test == AutoRetry::FailOnRetry {
2150 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2151 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2152 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2154 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2155 // fail to find a route.
2156 nodes[0].node.process_pending_htlc_forwards();
2157 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2158 assert_eq!(msg_events.len(), 0);
2160 let mut events = nodes[0].node.get_and_clear_pending_events();
2161 assert_eq!(events.len(), 1);
2163 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2164 assert_eq!(payment_hash, *ev_payment_hash);
2165 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2166 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2168 _ => panic!("Unexpected event"),
2174 fn auto_retry_partial_failure() {
2175 // Test that we'll retry appropriately on send partial failure and retry partial failure.
2176 let chanmon_cfgs = create_chanmon_cfgs(2);
2177 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2178 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2179 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2181 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2182 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2183 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2185 // Marshall data to send the payment
2186 let amt_msat = 20_000;
2187 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2188 #[cfg(feature = "std")]
2189 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2190 #[cfg(not(feature = "std"))]
2191 let payment_expiry_secs = 60 * 60;
2192 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2193 invoice_features.set_variable_length_onion_required();
2194 invoice_features.set_payment_secret_required();
2195 invoice_features.set_basic_mpp_optional();
2196 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2197 .with_expiry_time(payment_expiry_secs as u64)
2198 .with_bolt11_features(invoice_features).unwrap();
2199 let route_params = RouteParameters {
2201 final_value_msat: amt_msat,
2204 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
2205 // second (for the initial send path2 over chan_2) fails.
2206 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2207 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2208 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
2209 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
2210 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2211 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2212 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2214 // Configure the initial send, retry1 and retry2's paths.
2215 let send_route = Route {
2217 Path { hops: vec![RouteHop {
2218 pubkey: nodes[1].node.get_our_node_id(),
2219 node_features: nodes[1].node.node_features(),
2220 short_channel_id: chan_1_id,
2221 channel_features: nodes[1].node.channel_features(),
2222 fee_msat: amt_msat / 2,
2223 cltv_expiry_delta: 100,
2224 }], blinded_tail: None },
2225 Path { hops: vec![RouteHop {
2226 pubkey: nodes[1].node.get_our_node_id(),
2227 node_features: nodes[1].node.node_features(),
2228 short_channel_id: chan_2_id,
2229 channel_features: nodes[1].node.channel_features(),
2230 fee_msat: amt_msat / 2,
2231 cltv_expiry_delta: 100,
2232 }], blinded_tail: None },
2234 payment_params: Some(route_params.payment_params.clone()),
2236 let retry_1_route = Route {
2238 Path { hops: vec![RouteHop {
2239 pubkey: nodes[1].node.get_our_node_id(),
2240 node_features: nodes[1].node.node_features(),
2241 short_channel_id: chan_1_id,
2242 channel_features: nodes[1].node.channel_features(),
2243 fee_msat: amt_msat / 4,
2244 cltv_expiry_delta: 100,
2245 }], blinded_tail: None },
2246 Path { hops: vec![RouteHop {
2247 pubkey: nodes[1].node.get_our_node_id(),
2248 node_features: nodes[1].node.node_features(),
2249 short_channel_id: chan_3_id,
2250 channel_features: nodes[1].node.channel_features(),
2251 fee_msat: amt_msat / 4,
2252 cltv_expiry_delta: 100,
2253 }], blinded_tail: None },
2255 payment_params: Some(route_params.payment_params.clone()),
2257 let retry_2_route = Route {
2259 Path { hops: vec![RouteHop {
2260 pubkey: nodes[1].node.get_our_node_id(),
2261 node_features: nodes[1].node.node_features(),
2262 short_channel_id: chan_1_id,
2263 channel_features: nodes[1].node.channel_features(),
2264 fee_msat: amt_msat / 4,
2265 cltv_expiry_delta: 100,
2266 }], blinded_tail: None },
2268 payment_params: Some(route_params.payment_params.clone()),
2270 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2271 let mut payment_params = route_params.payment_params.clone();
2272 payment_params.previously_failed_channels.push(chan_2_id);
2273 nodes[0].router.expect_find_route(RouteParameters {
2274 payment_params, final_value_msat: amt_msat / 2,
2275 }, Ok(retry_1_route));
2276 let mut payment_params = route_params.payment_params.clone();
2277 payment_params.previously_failed_channels.push(chan_3_id);
2278 nodes[0].router.expect_find_route(RouteParameters {
2279 payment_params, final_value_msat: amt_msat / 4,
2280 }, Ok(retry_2_route));
2282 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2283 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2284 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2285 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
2286 assert_eq!(closed_chan_events.len(), 4);
2287 match closed_chan_events[0] {
2288 Event::ChannelClosed { .. } => {},
2289 _ => panic!("Unexpected event"),
2291 match closed_chan_events[1] {
2292 Event::PaymentPathFailed { .. } => {},
2293 _ => panic!("Unexpected event"),
2295 match closed_chan_events[2] {
2296 Event::ChannelClosed { .. } => {},
2297 _ => panic!("Unexpected event"),
2299 match closed_chan_events[3] {
2300 Event::PaymentPathFailed { .. } => {},
2301 _ => panic!("Unexpected event"),
2304 // Pass the first part of the payment along the path.
2305 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
2306 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2308 // First message is the first update_add, remaining messages are broadcasting channel updates and
2309 // errors for the permfailed channels
2310 assert_eq!(msg_events.len(), 5);
2311 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2313 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2314 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2315 check_added_monitors!(nodes[1], 1);
2316 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2318 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2319 check_added_monitors!(nodes[0], 1);
2320 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2322 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2323 check_added_monitors!(nodes[0], 1);
2324 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2326 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2327 check_added_monitors!(nodes[1], 1);
2329 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2330 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2331 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2332 check_added_monitors!(nodes[1], 1);
2333 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2335 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2336 check_added_monitors!(nodes[0], 1);
2338 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2339 check_added_monitors!(nodes[0], 1);
2340 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2342 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2343 check_added_monitors!(nodes[1], 1);
2345 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2346 nodes[1].node.process_pending_htlc_forwards();
2347 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2348 nodes[1].node.claim_funds(payment_preimage);
2349 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2350 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2351 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2353 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2354 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2355 check_added_monitors!(nodes[0], 1);
2356 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2358 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2359 check_added_monitors!(nodes[1], 4);
2360 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2362 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2363 check_added_monitors!(nodes[1], 1);
2364 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2366 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2367 check_added_monitors!(nodes[0], 1);
2369 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2370 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2371 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2372 check_added_monitors!(nodes[0], 1);
2373 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2375 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2376 check_added_monitors!(nodes[1], 1);
2378 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2379 check_added_monitors!(nodes[1], 1);
2380 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2382 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2383 check_added_monitors!(nodes[0], 1);
2384 expect_payment_sent!(nodes[0], payment_preimage);
2388 fn auto_retry_zero_attempts_send_error() {
2389 let chanmon_cfgs = create_chanmon_cfgs(2);
2390 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2391 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2392 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2394 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2395 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2397 // Marshall data to send the payment
2398 let amt_msat = 20_000;
2399 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2400 #[cfg(feature = "std")]
2401 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2402 #[cfg(not(feature = "std"))]
2403 let payment_expiry_secs = 60 * 60;
2404 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2405 invoice_features.set_variable_length_onion_required();
2406 invoice_features.set_payment_secret_required();
2407 invoice_features.set_basic_mpp_optional();
2408 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2409 .with_expiry_time(payment_expiry_secs as u64)
2410 .with_bolt11_features(invoice_features).unwrap();
2411 let route_params = RouteParameters {
2413 final_value_msat: amt_msat,
2416 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2417 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2418 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2419 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2420 let events = nodes[0].node.get_and_clear_pending_events();
2421 assert_eq!(events.len(), 3);
2422 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2423 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2424 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2425 check_added_monitors!(nodes[0], 2);
2429 fn fails_paying_after_rejected_by_payee() {
2430 let chanmon_cfgs = create_chanmon_cfgs(2);
2431 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2432 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2433 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2435 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2437 // Marshall data to send the payment
2438 let amt_msat = 20_000;
2439 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2440 #[cfg(feature = "std")]
2441 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2442 #[cfg(not(feature = "std"))]
2443 let payment_expiry_secs = 60 * 60;
2444 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2445 invoice_features.set_variable_length_onion_required();
2446 invoice_features.set_payment_secret_required();
2447 invoice_features.set_basic_mpp_optional();
2448 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2449 .with_expiry_time(payment_expiry_secs as u64)
2450 .with_bolt11_features(invoice_features).unwrap();
2451 let route_params = RouteParameters {
2453 final_value_msat: amt_msat,
2456 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2457 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2458 check_added_monitors!(nodes[0], 1);
2459 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2460 assert_eq!(events.len(), 1);
2461 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2462 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2463 check_added_monitors!(nodes[1], 0);
2464 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2465 expect_pending_htlcs_forwardable!(nodes[1]);
2466 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2468 nodes[1].node.fail_htlc_backwards(&payment_hash);
2469 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2470 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2474 fn retry_multi_path_single_failed_payment() {
2475 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2476 let chanmon_cfgs = create_chanmon_cfgs(2);
2477 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2478 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2479 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2481 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2482 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2484 let amt_msat = 100_010_000;
2486 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2487 #[cfg(feature = "std")]
2488 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2489 #[cfg(not(feature = "std"))]
2490 let payment_expiry_secs = 60 * 60;
2491 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2492 invoice_features.set_variable_length_onion_required();
2493 invoice_features.set_payment_secret_required();
2494 invoice_features.set_basic_mpp_optional();
2495 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2496 .with_expiry_time(payment_expiry_secs as u64)
2497 .with_bolt11_features(invoice_features).unwrap();
2498 let route_params = RouteParameters {
2499 payment_params: payment_params.clone(),
2500 final_value_msat: amt_msat,
2503 let chans = nodes[0].node.list_usable_channels();
2504 let mut route = Route {
2506 Path { hops: vec![RouteHop {
2507 pubkey: nodes[1].node.get_our_node_id(),
2508 node_features: nodes[1].node.node_features(),
2509 short_channel_id: chans[0].short_channel_id.unwrap(),
2510 channel_features: nodes[1].node.channel_features(),
2512 cltv_expiry_delta: 100,
2513 }], blinded_tail: None },
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[1].short_channel_id.unwrap(),
2518 channel_features: nodes[1].node.channel_features(),
2519 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2520 cltv_expiry_delta: 100,
2521 }], blinded_tail: None },
2523 payment_params: Some(payment_params),
2525 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2526 // On retry, split the payment across both channels.
2527 route.paths[0].hops[0].fee_msat = 50_000_001;
2528 route.paths[1].hops[0].fee_msat = 50_000_000;
2529 let mut pay_params = route.payment_params.clone().unwrap();
2530 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2531 nodes[0].router.expect_find_route(RouteParameters {
2532 payment_params: pay_params,
2533 // Note that the second request here requests the amount we originally failed to send,
2534 // not the amount remaining on the full payment, which should be changed.
2535 final_value_msat: 100_000_001,
2536 }, Ok(route.clone()));
2539 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2540 // The initial send attempt, 2 paths
2541 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2542 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2543 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2544 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2545 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2548 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2549 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2550 let events = nodes[0].node.get_and_clear_pending_events();
2551 assert_eq!(events.len(), 1);
2553 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2554 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2555 short_channel_id: Some(expected_scid), .. } =>
2557 assert_eq!(payment_hash, ev_payment_hash);
2558 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2560 _ => panic!("Unexpected event"),
2562 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2563 assert_eq!(htlc_msgs.len(), 2);
2564 check_added_monitors!(nodes[0], 2);
2568 fn immediate_retry_on_failure() {
2569 // Tests that we can/will retry immediately after a failure
2570 let chanmon_cfgs = create_chanmon_cfgs(2);
2571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2573 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2575 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2576 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2578 let amt_msat = 100_000_001;
2579 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2580 #[cfg(feature = "std")]
2581 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2582 #[cfg(not(feature = "std"))]
2583 let payment_expiry_secs = 60 * 60;
2584 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2585 invoice_features.set_variable_length_onion_required();
2586 invoice_features.set_payment_secret_required();
2587 invoice_features.set_basic_mpp_optional();
2588 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2589 .with_expiry_time(payment_expiry_secs as u64)
2590 .with_bolt11_features(invoice_features).unwrap();
2591 let route_params = RouteParameters {
2593 final_value_msat: amt_msat,
2596 let chans = nodes[0].node.list_usable_channels();
2597 let mut route = Route {
2599 Path { hops: vec![RouteHop {
2600 pubkey: nodes[1].node.get_our_node_id(),
2601 node_features: nodes[1].node.node_features(),
2602 short_channel_id: chans[0].short_channel_id.unwrap(),
2603 channel_features: nodes[1].node.channel_features(),
2604 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2605 cltv_expiry_delta: 100,
2606 }], blinded_tail: None },
2608 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2610 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2611 // On retry, split the payment across both channels.
2612 route.paths.push(route.paths[0].clone());
2613 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2614 route.paths[0].hops[0].fee_msat = 50_000_000;
2615 route.paths[1].hops[0].fee_msat = 50_000_001;
2616 let mut pay_params = route_params.payment_params.clone();
2617 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2618 nodes[0].router.expect_find_route(RouteParameters {
2619 payment_params: pay_params, final_value_msat: amt_msat,
2620 }, Ok(route.clone()));
2622 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2623 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2624 let events = nodes[0].node.get_and_clear_pending_events();
2625 assert_eq!(events.len(), 1);
2627 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2628 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2629 short_channel_id: Some(expected_scid), .. } =>
2631 assert_eq!(payment_hash, ev_payment_hash);
2632 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2634 _ => panic!("Unexpected event"),
2636 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2637 assert_eq!(htlc_msgs.len(), 2);
2638 check_added_monitors!(nodes[0], 2);
2642 fn no_extra_retries_on_back_to_back_fail() {
2643 // In a previous release, we had a race where we may exceed the payment retry count if we
2644 // get two failures in a row with the second indicating that all paths had failed (this field,
2645 // `all_paths_failed`, has since been removed).
2646 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2647 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2648 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2649 // pending which we will see later. Thus, when we previously removed the retry tracking map
2650 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2651 // retry entry even though more events for the same payment were still pending. This led to
2652 // us retrying a payment again even though we'd already given up on it.
2654 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2655 // is used to remove the payment retry counter entries instead. This tests for the specific
2656 // excess-retry case while also testing `PaymentFailed` generation.
2658 let chanmon_cfgs = create_chanmon_cfgs(3);
2659 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2660 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2661 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2663 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2664 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2666 let amt_msat = 200_000_000;
2667 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2668 #[cfg(feature = "std")]
2669 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2670 #[cfg(not(feature = "std"))]
2671 let payment_expiry_secs = 60 * 60;
2672 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2673 invoice_features.set_variable_length_onion_required();
2674 invoice_features.set_payment_secret_required();
2675 invoice_features.set_basic_mpp_optional();
2676 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2677 .with_expiry_time(payment_expiry_secs as u64)
2678 .with_bolt11_features(invoice_features).unwrap();
2679 let route_params = RouteParameters {
2681 final_value_msat: amt_msat,
2684 let mut route = Route {
2686 Path { hops: vec![RouteHop {
2687 pubkey: nodes[1].node.get_our_node_id(),
2688 node_features: nodes[1].node.node_features(),
2689 short_channel_id: chan_1_scid,
2690 channel_features: nodes[1].node.channel_features(),
2691 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2692 cltv_expiry_delta: 100,
2694 pubkey: nodes[2].node.get_our_node_id(),
2695 node_features: nodes[2].node.node_features(),
2696 short_channel_id: chan_2_scid,
2697 channel_features: nodes[2].node.channel_features(),
2698 fee_msat: 100_000_000,
2699 cltv_expiry_delta: 100,
2700 }], blinded_tail: None },
2701 Path { hops: vec![RouteHop {
2702 pubkey: nodes[1].node.get_our_node_id(),
2703 node_features: nodes[1].node.node_features(),
2704 short_channel_id: chan_1_scid,
2705 channel_features: nodes[1].node.channel_features(),
2706 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2707 cltv_expiry_delta: 100,
2709 pubkey: nodes[2].node.get_our_node_id(),
2710 node_features: nodes[2].node.node_features(),
2711 short_channel_id: chan_2_scid,
2712 channel_features: nodes[2].node.channel_features(),
2713 fee_msat: 100_000_000,
2714 cltv_expiry_delta: 100,
2715 }], blinded_tail: None }
2717 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2719 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2720 let mut second_payment_params = route_params.payment_params.clone();
2721 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2722 // On retry, we'll only return one path
2723 route.paths.remove(1);
2724 route.paths[0].hops[1].fee_msat = amt_msat;
2725 nodes[0].router.expect_find_route(RouteParameters {
2726 payment_params: second_payment_params,
2727 final_value_msat: amt_msat,
2728 }, Ok(route.clone()));
2730 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2731 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2732 let htlc_updates = SendEvent::from_node(&nodes[0]);
2733 check_added_monitors!(nodes[0], 1);
2734 assert_eq!(htlc_updates.msgs.len(), 1);
2736 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2737 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2738 check_added_monitors!(nodes[1], 1);
2739 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2741 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2742 check_added_monitors!(nodes[0], 1);
2743 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2745 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2746 check_added_monitors!(nodes[0], 1);
2747 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2749 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2750 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2751 check_added_monitors!(nodes[1], 1);
2752 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2754 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2755 check_added_monitors!(nodes[1], 1);
2756 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2758 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2759 check_added_monitors!(nodes[0], 1);
2761 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2762 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2763 check_added_monitors!(nodes[0], 1);
2764 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2766 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2767 check_added_monitors!(nodes[1], 1);
2768 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2770 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2771 check_added_monitors!(nodes[1], 1);
2772 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2774 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2775 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2776 check_added_monitors!(nodes[0], 1);
2778 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2779 check_added_monitors!(nodes[0], 1);
2780 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2782 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2783 check_added_monitors!(nodes[1], 1);
2784 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2785 check_added_monitors!(nodes[1], 1);
2786 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2788 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2789 check_added_monitors!(nodes[0], 1);
2791 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2792 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2795 // Previously, we retried payments in an event consumer, which would retry each
2796 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2797 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2798 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2799 // by adding the `PaymentFailed` event.
2801 // Because we now retry payments as a batch, we simply return a single-path route in the
2802 // second, batched, request, have that fail, ensure the payment was abandoned.
2803 let mut events = nodes[0].node.get_and_clear_pending_events();
2804 assert_eq!(events.len(), 3);
2806 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2807 assert_eq!(payment_hash, ev_payment_hash);
2808 assert_eq!(payment_failed_permanently, false);
2810 _ => panic!("Unexpected event"),
2813 Event::PendingHTLCsForwardable { .. } => {},
2814 _ => panic!("Unexpected event"),
2817 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2818 assert_eq!(payment_hash, ev_payment_hash);
2819 assert_eq!(payment_failed_permanently, false);
2821 _ => panic!("Unexpected event"),
2824 nodes[0].node.process_pending_htlc_forwards();
2825 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2826 check_added_monitors!(nodes[0], 1);
2828 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2829 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2830 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2831 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2832 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2834 let mut events = nodes[0].node.get_and_clear_pending_events();
2835 assert_eq!(events.len(), 2);
2837 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2838 assert_eq!(payment_hash, ev_payment_hash);
2839 assert_eq!(payment_failed_permanently, false);
2841 _ => panic!("Unexpected event"),
2844 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2845 assert_eq!(payment_hash, *ev_payment_hash);
2846 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2847 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2849 _ => panic!("Unexpected event"),
2854 fn test_simple_partial_retry() {
2855 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2856 // full amount of the payment, rather than only the missing amount. Here we simply test for
2857 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2858 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2860 let chanmon_cfgs = create_chanmon_cfgs(3);
2861 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2862 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2863 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2865 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2866 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2868 let amt_msat = 200_000_000;
2869 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2870 #[cfg(feature = "std")]
2871 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2872 #[cfg(not(feature = "std"))]
2873 let payment_expiry_secs = 60 * 60;
2874 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2875 invoice_features.set_variable_length_onion_required();
2876 invoice_features.set_payment_secret_required();
2877 invoice_features.set_basic_mpp_optional();
2878 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2879 .with_expiry_time(payment_expiry_secs as u64)
2880 .with_bolt11_features(invoice_features).unwrap();
2881 let route_params = RouteParameters {
2883 final_value_msat: amt_msat,
2886 let mut route = Route {
2888 Path { hops: vec![RouteHop {
2889 pubkey: nodes[1].node.get_our_node_id(),
2890 node_features: nodes[1].node.node_features(),
2891 short_channel_id: chan_1_scid,
2892 channel_features: nodes[1].node.channel_features(),
2893 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2894 cltv_expiry_delta: 100,
2896 pubkey: nodes[2].node.get_our_node_id(),
2897 node_features: nodes[2].node.node_features(),
2898 short_channel_id: chan_2_scid,
2899 channel_features: nodes[2].node.channel_features(),
2900 fee_msat: 100_000_000,
2901 cltv_expiry_delta: 100,
2902 }], blinded_tail: None },
2903 Path { hops: vec![RouteHop {
2904 pubkey: nodes[1].node.get_our_node_id(),
2905 node_features: nodes[1].node.node_features(),
2906 short_channel_id: chan_1_scid,
2907 channel_features: nodes[1].node.channel_features(),
2909 cltv_expiry_delta: 100,
2911 pubkey: nodes[2].node.get_our_node_id(),
2912 node_features: nodes[2].node.node_features(),
2913 short_channel_id: chan_2_scid,
2914 channel_features: nodes[2].node.channel_features(),
2915 fee_msat: 100_000_000,
2916 cltv_expiry_delta: 100,
2917 }], blinded_tail: None }
2919 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2921 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2922 let mut second_payment_params = route_params.payment_params.clone();
2923 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2924 // On retry, we'll only be asked for one path (or 100k sats)
2925 route.paths.remove(0);
2926 nodes[0].router.expect_find_route(RouteParameters {
2927 payment_params: second_payment_params,
2928 final_value_msat: amt_msat / 2,
2929 }, Ok(route.clone()));
2931 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2932 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2933 let htlc_updates = SendEvent::from_node(&nodes[0]);
2934 check_added_monitors!(nodes[0], 1);
2935 assert_eq!(htlc_updates.msgs.len(), 1);
2937 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2938 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2939 check_added_monitors!(nodes[1], 1);
2940 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2942 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2943 check_added_monitors!(nodes[0], 1);
2944 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2946 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2947 check_added_monitors!(nodes[0], 1);
2948 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2950 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2951 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2952 check_added_monitors!(nodes[1], 1);
2953 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2955 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2956 check_added_monitors!(nodes[1], 1);
2957 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2959 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2960 check_added_monitors!(nodes[0], 1);
2962 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2963 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2964 check_added_monitors!(nodes[0], 1);
2965 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2967 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2968 check_added_monitors!(nodes[1], 1);
2970 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2971 check_added_monitors!(nodes[1], 1);
2973 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2975 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2976 check_added_monitors!(nodes[0], 1);
2978 let mut events = nodes[0].node.get_and_clear_pending_events();
2979 assert_eq!(events.len(), 2);
2981 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2982 assert_eq!(payment_hash, ev_payment_hash);
2983 assert_eq!(payment_failed_permanently, false);
2985 _ => panic!("Unexpected event"),
2988 Event::PendingHTLCsForwardable { .. } => {},
2989 _ => panic!("Unexpected event"),
2992 nodes[0].node.process_pending_htlc_forwards();
2993 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2994 check_added_monitors!(nodes[0], 1);
2996 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2997 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2999 expect_pending_htlcs_forwardable!(nodes[1]);
3000 check_added_monitors!(nodes[1], 1);
3002 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3003 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
3004 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
3005 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
3007 expect_pending_htlcs_forwardable!(nodes[2]);
3008 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
3012 #[cfg(feature = "std")]
3013 fn test_threaded_payment_retries() {
3014 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
3015 // a single thread and would happily let multiple threads run retries at the same time. Because
3016 // retries are done by first calculating the amount we need to retry, then dropping the
3017 // relevant lock, then actually sending, we would happily let multiple threads retry the same
3018 // amount at the same time, overpaying our original HTLC!
3019 let chanmon_cfgs = create_chanmon_cfgs(4);
3020 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3021 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3022 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3024 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
3025 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
3026 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
3027 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
3029 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3030 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
3031 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
3032 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
3034 let amt_msat = 100_000_000;
3035 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3036 #[cfg(feature = "std")]
3037 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3038 #[cfg(not(feature = "std"))]
3039 let payment_expiry_secs = 60 * 60;
3040 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3041 invoice_features.set_variable_length_onion_required();
3042 invoice_features.set_payment_secret_required();
3043 invoice_features.set_basic_mpp_optional();
3044 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3045 .with_expiry_time(payment_expiry_secs as u64)
3046 .with_bolt11_features(invoice_features).unwrap();
3047 let mut route_params = RouteParameters {
3049 final_value_msat: amt_msat,
3052 let mut route = Route {
3054 Path { hops: vec![RouteHop {
3055 pubkey: nodes[1].node.get_our_node_id(),
3056 node_features: nodes[1].node.node_features(),
3057 short_channel_id: chan_1_scid,
3058 channel_features: nodes[1].node.channel_features(),
3060 cltv_expiry_delta: 100,
3062 pubkey: nodes[3].node.get_our_node_id(),
3063 node_features: nodes[2].node.node_features(),
3064 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3065 channel_features: nodes[2].node.channel_features(),
3066 fee_msat: amt_msat / 1000,
3067 cltv_expiry_delta: 100,
3068 }], blinded_tail: None },
3069 Path { hops: vec![RouteHop {
3070 pubkey: nodes[2].node.get_our_node_id(),
3071 node_features: nodes[2].node.node_features(),
3072 short_channel_id: chan_3_scid,
3073 channel_features: nodes[2].node.channel_features(),
3075 cltv_expiry_delta: 100,
3077 pubkey: nodes[3].node.get_our_node_id(),
3078 node_features: nodes[3].node.node_features(),
3079 short_channel_id: chan_4_scid,
3080 channel_features: nodes[3].node.channel_features(),
3081 fee_msat: amt_msat - amt_msat / 1000,
3082 cltv_expiry_delta: 100,
3083 }], blinded_tail: None }
3085 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
3087 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3089 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3090 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3091 check_added_monitors!(nodes[0], 2);
3092 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3093 assert_eq!(send_msg_events.len(), 2);
3094 send_msg_events.retain(|msg|
3095 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3096 // Drop the commitment update for nodes[2], we can just let that one sit pending
3098 *node_id == nodes[1].node.get_our_node_id()
3099 } else { panic!(); }
3102 // from here on out, the retry `RouteParameters` amount will be amt/1000
3103 route_params.final_value_msat /= 1000;
3106 let end_time = Instant::now() + Duration::from_secs(1);
3107 macro_rules! thread_body { () => { {
3108 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3109 let node_ref = NodePtr::from_node(&nodes[0]);
3111 let node_a = unsafe { &*node_ref.0 };
3112 while Instant::now() < end_time {
3113 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3114 // Ignore if we have any pending events, just always pretend we just got a
3115 // PendingHTLCsForwardable
3116 node_a.node.process_pending_htlc_forwards();
3120 let mut threads = Vec::new();
3121 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3123 // Back in the main thread, poll pending messages and make sure that we never have more than
3124 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3125 // there are HTLC messages shoved in while its running. This allows us to test that we never
3126 // generate an additional update_add_htlc until we've fully failed the first.
3127 let mut previously_failed_channels = Vec::new();
3129 assert_eq!(send_msg_events.len(), 1);
3130 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3131 assert_eq!(send_event.msgs.len(), 1);
3133 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3134 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3136 // Note that we only push one route into `expect_find_route` at a time, because that's all
3137 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3138 // we should still ultimately fail for the same reason - because we're trying to send too
3139 // many HTLCs at once.
3140 let mut new_route_params = route_params.clone();
3141 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3142 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3143 route.paths[0].hops[1].short_channel_id += 1;
3144 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3146 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3147 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3148 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3149 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3150 // This races with our other threads which may generate an add-HTLCs commitment update via
3151 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3152 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3153 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3154 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3156 let cur_time = Instant::now();
3157 if cur_time > end_time {
3158 for thread in threads.drain(..) { thread.join().unwrap(); }
3161 // Make sure we have some events to handle when we go around...
3162 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3163 nodes[0].node.process_pending_htlc_forwards();
3164 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3165 check_added_monitors!(nodes[0], 2);
3167 if cur_time > end_time {
3173 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
3174 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3175 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3176 // it was last persisted.
3177 let chanmon_cfgs = create_chanmon_cfgs(2);
3178 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3179 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3180 let (persister_a, persister_b, persister_c);
3181 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3182 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3183 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3185 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3187 let mut nodes_0_serialized = Vec::new();
3188 if !persist_manager_with_payment {
3189 nodes_0_serialized = nodes[0].node.encode();
3192 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3194 if persist_manager_with_payment {
3195 nodes_0_serialized = nodes[0].node.encode();
3198 nodes[1].node.claim_funds(our_payment_preimage);
3199 check_added_monitors!(nodes[1], 1);
3200 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3202 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3203 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3204 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3205 check_added_monitors!(nodes[0], 1);
3207 // The ChannelMonitor should always be the latest version, as we're required to persist it
3208 // during the commitment signed handling.
3209 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3210 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3212 let events = nodes[0].node.get_and_clear_pending_events();
3213 assert_eq!(events.len(), 2);
3214 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3215 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3216 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3217 // the double-claim that would otherwise appear at the end of this test.
3218 nodes[0].node.timer_tick_occurred();
3219 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3220 assert_eq!(as_broadcasted_txn.len(), 1);
3222 // Ensure that, even after some time, if we restart we still include *something* in the current
3223 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3224 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3225 // A naive implementation of the fix here would wipe the pending payments set, causing a
3226 // failure event when we restart.
3227 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3229 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3230 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);
3231 let events = nodes[0].node.get_and_clear_pending_events();
3232 assert!(events.is_empty());
3234 // Ensure that we don't generate any further events even after the channel-closing commitment
3235 // transaction is confirmed on-chain.
3236 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3237 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3239 let events = nodes[0].node.get_and_clear_pending_events();
3240 assert!(events.is_empty());
3242 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3243 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);
3244 let events = nodes[0].node.get_and_clear_pending_events();
3245 assert!(events.is_empty());
3246 check_added_monitors(&nodes[0], 1);
3250 fn no_missing_sent_on_midpoint_reload() {
3251 do_no_missing_sent_on_midpoint_reload(false);
3252 do_no_missing_sent_on_midpoint_reload(true);
3255 fn do_claim_from_closed_chan(fail_payment: bool) {
3256 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3257 // received had been closed between when the HTLC was received and when we went to claim it.
3258 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3259 // presumably the sender may retry later. Long ago it also reduced total code in the claim
3262 // However, this doesn't make sense if you're trying to do an atomic swap or some other
3263 // protocol that requires atomicity with some other action - if your money got claimed
3264 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3265 // is an over-optimization - there should be a very, very low likelihood that a channel closes
3266 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3267 // Since we now have code to handle this anyway we should allow it.
3269 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3270 // CLTVs on the paths to different value resulting in a different claim deadline.
3271 let chanmon_cfgs = create_chanmon_cfgs(4);
3272 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3273 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3274 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3276 create_announced_chan_between_nodes(&nodes, 0, 1);
3277 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3278 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3279 create_announced_chan_between_nodes(&nodes, 2, 3);
3281 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3282 let mut route_params = RouteParameters {
3283 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3284 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
3285 final_value_msat: 10_000_000,
3287 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3288 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3289 // Make sure the route is ordered as the B->D path before C->D
3290 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3291 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3293 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3294 // the HTLC is being relayed.
3295 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3296 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3297 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3299 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3300 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3301 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3302 check_added_monitors(&nodes[0], 2);
3303 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3304 send_msgs.sort_by(|a, _| {
3306 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3307 let node_b_id = nodes[1].node.get_our_node_id();
3308 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3311 assert_eq!(send_msgs.len(), 2);
3312 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3313 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3314 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3315 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3317 match receive_event.unwrap() {
3318 Event::PaymentClaimable { claim_deadline, .. } => {
3319 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3324 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3326 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3327 - if fail_payment { 0 } else { 2 });
3329 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3330 // and expire both immediately, though, by connecting another 4 blocks.
3331 let reason = HTLCDestination::FailedPayment { payment_hash };
3332 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3333 connect_blocks(&nodes[3], 4);
3334 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3335 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3337 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3338 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false);
3339 check_closed_broadcast(&nodes[1], 1, true);
3340 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3341 assert_eq!(bs_tx.len(), 1);
3343 mine_transaction(&nodes[3], &bs_tx[0]);
3344 check_added_monitors(&nodes[3], 1);
3345 check_closed_broadcast(&nodes[3], 1, true);
3346 check_closed_event(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false);
3348 nodes[3].node.claim_funds(payment_preimage);
3349 check_added_monitors(&nodes[3], 2);
3350 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3352 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3353 assert_eq!(ds_tx.len(), 1);
3354 check_spends!(&ds_tx[0], &bs_tx[0]);
3356 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3357 check_added_monitors(&nodes[1], 1);
3358 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3360 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3361 check_added_monitors(&nodes[1], 1);
3362 assert_eq!(bs_claims.len(), 1);
3363 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3364 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3365 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3366 } else { panic!(); }
3368 expect_payment_sent!(nodes[0], payment_preimage);
3370 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3371 assert_eq!(ds_claim_msgs.len(), 1);
3372 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3373 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3374 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3375 check_added_monitors(&nodes[2], 1);
3376 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3377 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3379 } else { panic!(); };
3381 assert_eq!(cs_claim_msgs.len(), 1);
3382 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3383 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3384 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3385 } else { panic!(); }
3387 expect_payment_path_successful!(nodes[0]);
3392 fn claim_from_closed_chan() {
3393 do_claim_from_closed_chan(true);
3394 do_claim_from_closed_chan(false);
3398 fn test_custom_tlvs_basic() {
3399 do_test_custom_tlvs(false, false, false);
3400 do_test_custom_tlvs(true, false, false);
3404 fn test_custom_tlvs_explicit_claim() {
3405 // Test that when receiving even custom TLVs the user must explicitly accept in case they
3407 do_test_custom_tlvs(false, true, false);
3408 do_test_custom_tlvs(false, true, true);
3411 fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) {
3412 let chanmon_cfgs = create_chanmon_cfgs(2);
3413 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3414 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None; 2]);
3415 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3417 create_announced_chan_between_nodes(&nodes, 0, 1);
3419 let amt_msat = 100_000;
3420 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat);
3421 let payment_id = PaymentId(our_payment_hash.0);
3422 let custom_tlvs = vec![
3423 (if even_tlvs { 5482373482 } else { 5482373483 }, vec![1, 2, 3, 4]),
3424 (5482373487, vec![0x42u8; 16]),
3426 let onion_fields = RecipientOnionFields {
3427 payment_secret: if spontaneous { None } else { Some(our_payment_secret) },
3428 payment_metadata: None,
3429 custom_tlvs: custom_tlvs.clone()
3432 nodes[0].node.send_spontaneous_payment(&route, Some(our_payment_preimage), onion_fields, payment_id).unwrap();
3434 nodes[0].node.send_payment_with_route(&route, our_payment_hash, onion_fields, payment_id).unwrap();
3436 check_added_monitors(&nodes[0], 1);
3438 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3439 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
3440 let mut payment_event = SendEvent::from_event(ev);
3442 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3443 check_added_monitors!(&nodes[1], 0);
3444 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3445 expect_pending_htlcs_forwardable!(nodes[1]);
3447 let events = nodes[1].node.get_and_clear_pending_events();
3448 assert_eq!(events.len(), 1);
3450 Event::PaymentClaimable { ref purpose, amount_msat, ref onion_fields, .. } => {
3452 PaymentPurpose::InvoicePayment { payment_secret, .. } => {
3453 assert_eq!(our_payment_secret, *payment_secret);
3454 assert_eq!(Some(*payment_secret), onion_fields.as_ref().unwrap().payment_secret);
3456 PaymentPurpose::SpontaneousPayment(payment_preimage) => {
3457 assert_eq!(our_payment_preimage, *payment_preimage);
3460 assert_eq!(amount_msat, amt_msat);
3461 assert_eq!(onion_fields.clone().unwrap().custom_tlvs().clone(), custom_tlvs);
3463 _ => panic!("Unexpected event"),
3466 match (known_tlvs, even_tlvs) {
3468 nodes[1].node.claim_funds_with_known_custom_tlvs(our_payment_preimage);
3469 let expected_total_fee_msat = pass_claimed_payment_along_route(&nodes[0], &[&[&nodes[1]]], &[0; 1], false, our_payment_preimage);
3470 expect_payment_sent!(&nodes[0], our_payment_preimage, Some(expected_total_fee_msat));
3473 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3476 nodes[1].node.claim_funds(our_payment_preimage);
3477 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3478 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], expected_destinations);
3479 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, our_payment_hash, PaymentFailureReason::RecipientRejected);
3485 fn test_retry_custom_tlvs() {
3486 // Test that custom TLVs are successfully sent on retries
3487 let chanmon_cfgs = create_chanmon_cfgs(3);
3488 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3489 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3490 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3492 create_announced_chan_between_nodes(&nodes, 0, 1);
3493 let (chan_2_update, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 2, 1);
3496 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3498 let amt_msat = 1_000_000;
3499 let (route, payment_hash, payment_preimage, payment_secret) =
3500 get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
3502 // Initiate the payment
3503 let payment_id = PaymentId(payment_hash.0);
3504 let mut route_params = RouteParameters {
3505 payment_params: route.payment_params.clone().unwrap(),
3506 final_value_msat: amt_msat,
3509 let custom_tlvs = vec![((1 << 16) + 1, vec![0x42u8; 16])];
3510 let onion_fields = RecipientOnionFields::secret_only(payment_secret);
3511 let onion_fields = onion_fields.with_custom_tlvs(custom_tlvs.clone()).unwrap();
3513 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3514 nodes[0].node.send_payment(payment_hash, onion_fields,
3515 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3516 check_added_monitors!(nodes[0], 1); // one monitor per path
3517 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3518 assert_eq!(events.len(), 1);
3520 // Add the HTLC along the first hop.
3521 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
3522 let (update_add, commitment_signed) = match fail_path_msgs_1 {
3523 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate {
3524 ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs,
3525 ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed }
3527 assert_eq!(update_add_htlcs.len(), 1);
3528 assert!(update_fail_htlcs.is_empty());
3529 assert!(update_fulfill_htlcs.is_empty());
3530 assert!(update_fail_malformed_htlcs.is_empty());
3531 assert!(update_fee.is_none());
3532 (update_add_htlcs[0].clone(), commitment_signed.clone())
3534 _ => panic!("Unexpected event"),
3536 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
3537 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
3539 // Attempt to forward the payment and complete the path's failure.
3540 expect_pending_htlcs_forwardable!(&nodes[1]);
3541 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1],
3542 vec![HTLCDestination::NextHopChannel {
3543 node_id: Some(nodes[2].node.get_our_node_id()),
3544 channel_id: chan_2_id
3546 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3547 assert!(htlc_updates.update_add_htlcs.is_empty());
3548 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
3549 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
3550 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
3551 check_added_monitors!(nodes[1], 1);
3552 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(),
3553 &htlc_updates.update_fail_htlcs[0]);
3554 commitment_signed_dance!(nodes[0], nodes[1], htlc_updates.commitment_signed, false);
3555 let mut events = nodes[0].node.get_and_clear_pending_events();
3557 Event::PendingHTLCsForwardable { .. } => {},
3558 _ => panic!("Unexpected event")
3561 expect_payment_failed_conditions_event(events, payment_hash, false,
3562 PaymentFailedConditions::new().mpp_parts_remain());
3564 // Rebalance the channel so the retry of the payment can succeed.
3565 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3567 // Retry the payment and make sure it succeeds
3568 route_params.payment_params.previously_failed_channels.push(chan_2_update.contents.short_channel_id);
3569 nodes[0].router.expect_find_route(route_params, Ok(route));
3570 nodes[0].node.process_pending_htlc_forwards();
3571 check_added_monitors!(nodes[0], 1);
3572 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3573 assert_eq!(events.len(), 1);
3574 let payment_claimable = pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000,
3575 payment_hash, Some(payment_secret), events.pop().unwrap(), true, None).unwrap();
3576 let onion_fields = match payment_claimable {
3577 Event::PaymentClaimable { onion_fields, .. } => onion_fields,
3578 _ => panic!("Unexpected event"),
3580 assert_eq!(onion_fields.unwrap().custom_tlvs(), &custom_tlvs);
3581 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
3585 fn test_custom_tlvs_consistency() {
3586 let even_type_1 = 1 << 16;
3587 let odd_type_1 = (1 << 16)+ 1;
3588 let even_type_2 = (1 << 16) + 2;
3589 let odd_type_2 = (1 << 16) + 3;
3590 let value_1 = || vec![1, 2, 3, 4];
3591 let differing_value_1 = || vec![1, 2, 3, 5];
3592 let value_2 = || vec![42u8; 16];
3594 // Drop missing odd tlvs
3595 do_test_custom_tlvs_consistency(
3596 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3597 vec![(odd_type_1, value_1())],
3598 Some(vec![(odd_type_1, value_1())]),
3600 // Drop non-matching odd tlvs
3601 do_test_custom_tlvs_consistency(
3602 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3603 vec![(odd_type_1, differing_value_1()), (odd_type_2, value_2())],
3604 Some(vec![(odd_type_2, value_2())]),
3606 // Fail missing even tlvs
3607 do_test_custom_tlvs_consistency(
3608 vec![(odd_type_1, value_1()), (even_type_2, value_2())],
3609 vec![(odd_type_1, value_1())],
3612 // Fail non-matching even tlvs
3613 do_test_custom_tlvs_consistency(
3614 vec![(even_type_1, value_1()), (odd_type_2, value_2())],
3615 vec![(even_type_1, differing_value_1()), (odd_type_2, value_2())],
3620 fn do_test_custom_tlvs_consistency(first_tlvs: Vec<(u64, Vec<u8>)>, second_tlvs: Vec<(u64, Vec<u8>)>,
3621 expected_receive_tlvs: Option<Vec<(u64, Vec<u8>)>>) {
3623 let chanmon_cfgs = create_chanmon_cfgs(4);
3624 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3625 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3626 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3628 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
3629 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
3630 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
3631 let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
3633 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3634 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
3635 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
3636 assert_eq!(route.paths.len(), 2);
3637 route.paths.sort_by(|path_a, _| {
3638 // Sort the path so that the path through nodes[1] comes first
3639 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3640 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
3643 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
3644 let payment_id = PaymentId([42; 32]);
3645 let amt_msat = 15_000_000;
3648 let onion_fields = RecipientOnionFields {
3649 payment_secret: Some(our_payment_secret),
3650 payment_metadata: None,
3651 custom_tlvs: first_tlvs
3653 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
3654 onion_fields.clone(), payment_id, &route).unwrap();
3655 let cur_height = nodes[0].best_block_info().1;
3656 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
3657 onion_fields.clone(), amt_msat, cur_height, payment_id,
3658 &None, session_privs[0]).unwrap();
3659 check_added_monitors!(nodes[0], 1);
3662 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3663 assert_eq!(events.len(), 1);
3664 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
3666 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
3669 let onion_fields = RecipientOnionFields {
3670 payment_secret: Some(our_payment_secret),
3671 payment_metadata: None,
3672 custom_tlvs: second_tlvs
3674 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
3675 onion_fields.clone(), amt_msat, cur_height, payment_id, &None, session_privs[1]).unwrap();
3676 check_added_monitors!(nodes[0], 1);
3679 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3680 assert_eq!(events.len(), 1);
3681 let payment_event = SendEvent::from_event(events.pop().unwrap());
3683 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3684 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
3686 expect_pending_htlcs_forwardable!(nodes[2]);
3687 check_added_monitors!(nodes[2], 1);
3689 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
3690 assert_eq!(events.len(), 1);
3691 let payment_event = SendEvent::from_event(events.pop().unwrap());
3693 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
3694 check_added_monitors!(nodes[3], 0);
3695 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
3697 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3698 nodes[3].node.process_pending_htlc_forwards();
3700 if let Some(expected_tlvs) = expected_receive_tlvs {
3701 // Claim and match expected
3702 let events = nodes[3].node.get_and_clear_pending_events();
3703 println!("events: {:?}", events);
3704 assert_eq!(events.len(), 1);
3706 Event::PaymentClaimable { ref purpose, amount_msat, ref onion_fields, .. } => {
3708 PaymentPurpose::InvoicePayment { payment_secret, .. } => {
3709 assert_eq!(our_payment_secret, *payment_secret);
3710 assert_eq!(Some(*payment_secret), onion_fields.as_ref().unwrap().payment_secret);
3712 PaymentPurpose::SpontaneousPayment(payment_preimage) => {
3713 assert_eq!(our_payment_preimage, *payment_preimage);
3716 assert_eq!(amount_msat, amt_msat);
3717 assert_eq!(onion_fields.clone().unwrap().custom_tlvs, expected_tlvs);
3719 _ => panic!("Unexpected event"),
3722 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
3723 expect_payment_sent(&nodes[0], our_payment_preimage, Some(Some(2000)), true);
3726 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3727 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], expected_destinations);
3728 check_added_monitors!(nodes[3], 1);
3730 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
3731 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
3732 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
3734 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_2_3.2 }]);
3735 check_added_monitors!(nodes[2], 1);
3737 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
3738 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
3739 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
3741 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
3745 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3746 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3747 // another results in the HTLC being rejected.
3749 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3750 // first of which we'll deliver and the second of which we'll fail and then re-send with
3751 // modified payment metadata, which will in turn result in it being failed by the recipient.
3752 let chanmon_cfgs = create_chanmon_cfgs(4);
3753 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3754 let mut config = test_default_channel_config();
3755 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3756 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3759 let new_chain_monitor;
3760 let nodes_0_deserialized;
3762 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3764 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3765 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3766 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3767 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3769 // Pay more than half of each channel's max, requiring MPP
3770 let amt_msat = 750_000_000;
3771 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3772 let payment_id = PaymentId(payment_hash.0);
3773 let payment_metadata = vec![44, 49, 52, 142];
3775 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3776 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3777 let mut route_params = RouteParameters {
3779 final_value_msat: amt_msat,
3782 // Send the MPP payment, delivering the updated commitment state to nodes[1].
3783 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3784 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata), custom_tlvs: vec![],
3785 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3786 check_added_monitors!(nodes[0], 2);
3788 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3789 assert_eq!(send_events.len(), 2);
3790 let first_send = SendEvent::from_event(send_events.pop().unwrap());
3791 let second_send = SendEvent::from_event(send_events.pop().unwrap());
3793 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3794 (&first_send, &second_send)
3796 (&second_send, &first_send)
3798 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3799 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3801 expect_pending_htlcs_forwardable!(nodes[1]);
3802 check_added_monitors(&nodes[1], 1);
3803 let b_forward_ev = SendEvent::from_node(&nodes[1]);
3804 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3805 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3807 expect_pending_htlcs_forwardable!(nodes[3]);
3809 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3810 // will result in nodes[2] failing the HTLC back.
3811 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3812 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3814 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3815 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3817 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3818 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3819 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3821 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3822 assert_eq!(payment_fail_retryable_evs.len(), 2);
3823 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3824 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3826 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3827 // stored for our payment.
3829 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3832 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3833 // the payment state.
3835 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3836 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3837 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3838 persister, new_chain_monitor, nodes_0_deserialized);
3839 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3840 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
3842 let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
3843 reconnect_args.send_channel_ready = (true, true);
3844 reconnect_nodes(reconnect_args);
3846 // Create a new channel between C and D as A will refuse to retry on the existing one because
3848 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3850 // Now retry the failed HTLC.
3851 nodes[0].node.process_pending_htlc_forwards();
3852 check_added_monitors(&nodes[0], 1);
3853 let as_resend = SendEvent::from_node(&nodes[0]);
3854 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3855 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3857 expect_pending_htlcs_forwardable!(nodes[2]);
3858 check_added_monitors(&nodes[2], 1);
3859 let cs_forward = SendEvent::from_node(&nodes[2]);
3860 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3861 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3863 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3864 // the payment metadata was modified, failing only the one modified HTLC and retaining the
3867 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3868 nodes[3].node.process_pending_htlc_forwards();
3869 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3870 &[HTLCDestination::FailedPayment {payment_hash}]);
3871 nodes[3].node.process_pending_htlc_forwards();
3873 check_added_monitors(&nodes[3], 1);
3874 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3876 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3877 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3878 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3879 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3881 expect_pending_htlcs_forwardable!(nodes[3]);
3882 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3883 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3888 fn test_payment_metadata_consistency() {
3889 do_test_payment_metadata_consistency(true, true);
3890 do_test_payment_metadata_consistency(true, false);
3891 do_test_payment_metadata_consistency(false, true);
3892 do_test_payment_metadata_consistency(false, false);