1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test the payment retry logic in ChannelManager, including various edge-cases around
11 //! serialization ordering between ChannelManager/ChannelMonitors and ensuring we can still retry
12 //! payments thereafter.
14 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
15 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::sign::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason};
19 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
20 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails, RecipientOnionFields, HTLCForwardInfo, PendingHTLCRouting, PendingAddHTLCInfo};
21 use crate::ln::features::Bolt11InvoiceFeatures;
22 use crate::ln::{msgs, PaymentSecret, PaymentPreimage};
23 use crate::ln::msgs::ChannelMessageHandler;
24 use crate::ln::outbound_payment::Retry;
25 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
26 use crate::routing::router::{get_route, Path, PaymentParameters, Route, Router, RouteHint, RouteHintHop, RouteHop, RouteParameters, find_route};
27 use crate::routing::scoring::ChannelUsage;
28 use crate::util::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
31 use crate::util::string::UntrustedString;
33 use bitcoin::network::constants::Network;
35 use crate::prelude::*;
37 use crate::ln::functional_test_utils::*;
38 use crate::routing::gossip::NodeId;
39 #[cfg(feature = "std")]
41 crate::util::time::tests::SinceEpoch,
42 std::time::{SystemTime, Instant, Duration}
47 let chanmon_cfgs = create_chanmon_cfgs(4);
48 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
49 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
50 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
52 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
53 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
54 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
55 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
57 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
58 let path = route.paths[0].clone();
59 route.paths.push(path);
60 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
61 route.paths[0].hops[0].short_channel_id = chan_1_id;
62 route.paths[0].hops[1].short_channel_id = chan_3_id;
63 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
64 route.paths[1].hops[0].short_channel_id = chan_2_id;
65 route.paths[1].hops[1].short_channel_id = chan_4_id;
66 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
67 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
72 let chanmon_cfgs = create_chanmon_cfgs(4);
73 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
74 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
75 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
77 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
78 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
79 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
80 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
82 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
84 let amt_msat = 1_000_000;
85 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
86 let path = route.paths[0].clone();
87 route.paths.push(path);
88 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
89 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
90 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
91 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
92 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
93 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
95 // Initiate the MPP payment.
96 let payment_id = PaymentId(payment_hash.0);
97 let mut route_params = RouteParameters {
98 payment_params: route.payment_params.clone().unwrap(),
99 final_value_msat: amt_msat,
102 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
103 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
104 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
105 check_added_monitors!(nodes[0], 2); // one monitor per path
106 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
107 assert_eq!(events.len(), 2);
109 // Pass half of the payment along the success path.
110 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
111 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
113 // Add the HTLC along the first hop.
114 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
115 let (update_add, commitment_signed) = match fail_path_msgs_1 {
116 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
117 assert_eq!(update_add_htlcs.len(), 1);
118 assert!(update_fail_htlcs.is_empty());
119 assert!(update_fulfill_htlcs.is_empty());
120 assert!(update_fail_malformed_htlcs.is_empty());
121 assert!(update_fee.is_none());
122 (update_add_htlcs[0].clone(), commitment_signed.clone())
124 _ => panic!("Unexpected event"),
126 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
127 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
129 // Attempt to forward the payment and complete the 2nd path's failure.
130 expect_pending_htlcs_forwardable!(&nodes[2]);
131 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_4_id }]);
132 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
133 assert!(htlc_updates.update_add_htlcs.is_empty());
134 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
135 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
136 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
137 check_added_monitors!(nodes[2], 1);
138 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
139 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
140 let mut events = nodes[0].node.get_and_clear_pending_events();
142 Event::PendingHTLCsForwardable { .. } => {},
143 _ => panic!("Unexpected event")
146 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
148 // Rebalance the channel so the second half of the payment can succeed.
149 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
151 // Retry the second half of the payment and make sure it succeeds.
152 route.paths.remove(0);
153 route_params.final_value_msat = 1_000_000;
154 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
155 nodes[0].router.expect_find_route(route_params, Ok(route));
156 nodes[0].node.process_pending_htlc_forwards();
157 check_added_monitors!(nodes[0], 1);
158 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
159 assert_eq!(events.len(), 1);
160 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
161 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
164 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
165 let chanmon_cfgs = create_chanmon_cfgs(4);
166 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
167 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
168 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
170 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
171 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
172 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
173 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
175 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
176 let path = route.paths[0].clone();
177 route.paths.push(path);
178 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
179 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
180 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
181 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
182 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
183 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
185 // Initiate the MPP payment.
186 nodes[0].node.send_payment_with_route(&route, payment_hash,
187 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
188 check_added_monitors!(nodes[0], 2); // one monitor per path
189 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
190 assert_eq!(events.len(), 2);
192 // Pass half of the payment along the first path.
193 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
194 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
196 if send_partial_mpp {
197 // Time out the partial MPP
198 for _ in 0..MPP_TIMEOUT_TICKS {
199 nodes[3].node.timer_tick_occurred();
202 // Failed HTLC from node 3 -> 1
203 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
204 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
205 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
206 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
207 check_added_monitors!(nodes[3], 1);
208 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
210 // Failed HTLC from node 1 -> 0
211 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_3_id }]);
212 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
213 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
214 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
215 check_added_monitors!(nodes[1], 1);
216 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
218 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
220 // Pass half of the payment along the second path.
221 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
222 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
224 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
225 for _ in 0..MPP_TIMEOUT_TICKS {
226 nodes[3].node.timer_tick_occurred();
229 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
234 fn mpp_receive_timeout() {
235 do_mpp_receive_timeout(true);
236 do_mpp_receive_timeout(false);
240 fn test_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
277 let test_preimage = PaymentPreimage([42; 32]);
278 let payment_hash = if with_retry {
279 nodes[0].node.send_spontaneous_payment_with_retry(Some(test_preimage),
280 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0),
281 route_params, Retry::Attempts(1)).unwrap()
283 nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
284 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap()
286 check_added_monitors!(nodes[0], 1);
287 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
288 assert_eq!(events.len(), 1);
289 let event = events.pop().unwrap();
290 let path = vec![&nodes[1]];
291 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
292 claim_payment(&nodes[0], &path, test_preimage);
296 fn test_mpp_keysend() {
297 let mut mpp_keysend_config = test_default_channel_config();
298 mpp_keysend_config.accept_mpp_keysend = true;
299 let chanmon_cfgs = create_chanmon_cfgs(4);
300 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
301 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
302 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
304 create_announced_chan_between_nodes(&nodes, 0, 1);
305 create_announced_chan_between_nodes(&nodes, 0, 2);
306 create_announced_chan_between_nodes(&nodes, 1, 3);
307 create_announced_chan_between_nodes(&nodes, 2, 3);
308 let network_graph = nodes[0].network_graph.clone();
310 let payer_pubkey = nodes[0].node.get_our_node_id();
311 let payee_pubkey = nodes[3].node.get_our_node_id();
312 let recv_value = 15_000_000;
313 let route_params = RouteParameters {
314 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, true),
315 final_value_msat: recv_value,
317 let scorer = test_utils::TestScorer::new();
318 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
319 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger,
320 &scorer, &(), &random_seed_bytes).unwrap();
322 let payment_preimage = PaymentPreimage([42; 32]);
323 let payment_secret = PaymentSecret(payment_preimage.0);
324 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
325 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_preimage.0)).unwrap();
326 check_added_monitors!(nodes[0], 2);
328 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
329 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
330 assert_eq!(events.len(), 2);
332 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
333 pass_along_path(&nodes[0], expected_route[0], recv_value, payment_hash.clone(),
334 Some(payment_secret), ev.clone(), false, Some(payment_preimage));
336 let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
337 pass_along_path(&nodes[0], expected_route[1], recv_value, payment_hash.clone(),
338 Some(payment_secret), ev.clone(), true, Some(payment_preimage));
339 claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
343 fn test_reject_mpp_keysend_htlc() {
344 // This test enforces that we reject MPP keysend HTLCs if our config states we don't support
345 // MPP keysend. When receiving a payment, if we don't support MPP keysend we'll reject the
346 // payment if it's keysend and has a payment secret, never reaching our payment validation
347 // logic. To check that we enforce rejecting MPP keysends in our payment logic, here we send
348 // keysend payments without payment secrets, then modify them by adding payment secrets in the
349 // final node in between receiving the HTLCs and actually processing them.
350 let mut reject_mpp_keysend_cfg = test_default_channel_config();
351 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
353 let chanmon_cfgs = create_chanmon_cfgs(4);
354 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
355 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(reject_mpp_keysend_cfg)]);
356 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
357 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
358 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
359 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
360 let (update_a, _, chan_4_channel_id, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
361 let chan_4_id = update_a.contents.short_channel_id;
363 let (mut route, payment_hash, payment_preimage, _) = get_route_and_payment_hash!(nodes[0], nodes[3], amount);
365 // Pay along nodes[1]
366 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
367 route.paths[0].hops[0].short_channel_id = chan_1_id;
368 route.paths[0].hops[1].short_channel_id = chan_3_id;
370 let payment_id_0 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
371 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_0).unwrap();
372 check_added_monitors!(nodes[0], 1);
374 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
375 let update_add_0 = update_0.update_add_htlcs[0].clone();
376 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
377 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
378 expect_pending_htlcs_forwardable!(nodes[1]);
380 check_added_monitors!(&nodes[1], 1);
381 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[3].node.get_our_node_id());
382 let update_add_1 = update_1.update_add_htlcs[0].clone();
383 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
384 commitment_signed_dance!(nodes[3], nodes[1], update_1.commitment_signed, false, true);
386 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
387 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
388 for f in pending_forwards.iter_mut() {
390 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
391 match forward_info.routing {
392 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
393 *payment_data = Some(msgs::FinalOnionHopData {
394 payment_secret: PaymentSecret([42; 32]),
395 total_msat: amount * 2,
398 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
405 expect_pending_htlcs_forwardable!(nodes[3]);
407 // Pay along nodes[2]
408 route.paths[0].hops[0].pubkey = nodes[2].node.get_our_node_id();
409 route.paths[0].hops[0].short_channel_id = chan_2_id;
410 route.paths[0].hops[1].short_channel_id = chan_4_id;
412 let payment_id_1 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
413 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
414 check_added_monitors!(nodes[0], 1);
416 let update_2 = get_htlc_update_msgs!(nodes[0], nodes[2].node.get_our_node_id());
417 let update_add_2 = update_2.update_add_htlcs[0].clone();
418 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_2);
419 commitment_signed_dance!(nodes[2], nodes[0], &update_2.commitment_signed, false, true);
420 expect_pending_htlcs_forwardable!(nodes[2]);
422 check_added_monitors!(&nodes[2], 1);
423 let update_3 = get_htlc_update_msgs!(nodes[2], nodes[3].node.get_our_node_id());
424 let update_add_3 = update_3.update_add_htlcs[0].clone();
425 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &update_add_3);
426 commitment_signed_dance!(nodes[3], nodes[2], update_3.commitment_signed, false, true);
428 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
429 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
430 for f in pending_forwards.iter_mut() {
432 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
433 match forward_info.routing {
434 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
435 *payment_data = Some(msgs::FinalOnionHopData {
436 payment_secret: PaymentSecret([42; 32]),
437 total_msat: amount * 2,
440 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
447 expect_pending_htlcs_forwardable!(nodes[3]);
448 check_added_monitors!(nodes[3], 1);
450 // Fail back along nodes[2]
451 let update_fail_0 = get_htlc_update_msgs!(&nodes[3], &nodes[2].node.get_our_node_id());
452 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &update_fail_0.update_fail_htlcs[0]);
453 commitment_signed_dance!(nodes[2], nodes[3], update_fail_0.commitment_signed, false);
454 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 }]);
455 check_added_monitors!(nodes[2], 1);
457 let update_fail_1 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
458 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_1.update_fail_htlcs[0]);
459 commitment_signed_dance!(nodes[0], nodes[2], update_fail_1.commitment_signed, false);
461 expect_payment_failed_conditions(&nodes[0], payment_hash, true, PaymentFailedConditions::new());
462 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
467 fn no_pending_leak_on_initial_send_failure() {
468 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
469 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
470 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
471 // pending payment forever and never time it out.
472 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
473 // try, and then check that no pending payment is being tracked.
474 let chanmon_cfgs = create_chanmon_cfgs(2);
475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
477 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
479 create_announced_chan_between_nodes(&nodes, 0, 1);
481 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
483 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
484 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
486 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
487 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
488 ), true, APIError::ChannelUnavailable { ref err },
489 assert_eq!(err, "Peer for first hop currently disconnected"));
491 assert!(!nodes[0].node.has_pending_payments());
494 fn do_retry_with_no_persist(confirm_before_reload: bool) {
495 // If we send a pending payment and `send_payment` returns success, we should always either
496 // return a payment failure event or a payment success event, and on failure the payment should
499 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
500 // always persisted asynchronously), the ChannelManager has to reload some payment data from
501 // ChannelMonitor(s) in some cases. This tests that reloading.
503 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
504 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
505 // which has separate codepaths for "commitment transaction already confirmed" and not.
506 let chanmon_cfgs = create_chanmon_cfgs(3);
507 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
508 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
509 let persister: test_utils::TestPersister;
510 let new_chain_monitor: test_utils::TestChainMonitor;
511 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>;
512 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
514 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
515 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
517 // Serialize the ChannelManager prior to sending payments
518 let nodes_0_serialized = nodes[0].node.encode();
520 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
522 let amt_msat = 1_000_000;
523 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
524 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
525 let route_params = RouteParameters {
526 payment_params: route.payment_params.clone().unwrap(),
527 final_value_msat: amt_msat,
529 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
530 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
531 check_added_monitors!(nodes[0], 1);
533 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
534 assert_eq!(events.len(), 1);
535 let payment_event = SendEvent::from_event(events.pop().unwrap());
536 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
538 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
539 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
540 // which would prevent retry.
541 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
542 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
544 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
545 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
546 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
547 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
549 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
551 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
552 if confirm_before_reload {
553 mine_transaction(&nodes[0], &as_commitment_tx);
554 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
557 // The ChannelMonitor should always be the latest version, as we're required to persist it
558 // during the `commitment_signed_dance!()`.
559 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
560 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
562 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
563 // force-close the channel.
564 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
565 assert!(nodes[0].node.list_channels().is_empty());
566 assert!(nodes[0].node.has_pending_payments());
567 nodes[0].node.timer_tick_occurred();
568 if !confirm_before_reload {
569 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
570 assert_eq!(as_broadcasted_txn.len(), 1);
571 assert_eq!(as_broadcasted_txn[0].txid(), as_commitment_tx.txid());
573 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
575 check_added_monitors!(nodes[0], 1);
577 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
578 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
579 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
581 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
583 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
584 // error, as the channel has hit the chain.
585 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
586 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
588 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
589 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
590 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
591 assert_eq!(as_err.len(), 1);
593 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
594 assert_eq!(node_id, nodes[1].node.get_our_node_id());
595 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
596 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())) });
597 check_added_monitors!(nodes[1], 1);
598 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
600 _ => panic!("Unexpected event"),
602 check_closed_broadcast!(nodes[1], false);
604 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
605 // we close in a moment.
606 nodes[2].node.claim_funds(payment_preimage_1);
607 check_added_monitors!(nodes[2], 1);
608 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
610 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
611 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
612 check_added_monitors!(nodes[1], 1);
613 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
614 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
616 if confirm_before_reload {
617 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
618 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
621 // Create a new channel on which to retry the payment before we fail the payment via the
622 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
623 // connecting several blocks while creating the channel (implying time has passed).
624 create_announced_chan_between_nodes(&nodes, 0, 1);
625 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
627 mine_transaction(&nodes[1], &as_commitment_tx);
628 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
629 assert_eq!(bs_htlc_claim_txn.len(), 1);
630 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
632 if !confirm_before_reload {
633 mine_transaction(&nodes[0], &as_commitment_tx);
635 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
636 expect_payment_sent!(nodes[0], payment_preimage_1);
637 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
638 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
639 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
640 assert_eq!(txn.len(), 2);
641 (txn.remove(0), txn.remove(0))
643 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
644 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
645 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
646 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
648 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
650 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
651 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
653 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
654 // reloaded) via a route over the new channel, which work without issue and eventually be
655 // received and claimed at the recipient just like any other payment.
656 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
658 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
659 // and not the original fee. We also update node[1]'s relevant config as
660 // do_claim_payment_along_route expects us to never overpay.
662 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
663 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
664 .unwrap().lock().unwrap();
665 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
666 let mut new_config = channel.context.config();
667 new_config.forwarding_fee_base_msat += 100_000;
668 channel.context.update_config(&new_config);
669 new_route.paths[0].hops[0].fee_msat += 100_000;
672 // Force expiration of the channel's previous config.
673 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
674 nodes[1].node.timer_tick_occurred();
677 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
678 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
679 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
680 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
681 check_added_monitors!(nodes[0], 1);
682 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
683 assert_eq!(events.len(), 1);
684 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
685 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
686 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
690 fn retry_with_no_persist() {
691 do_retry_with_no_persist(true);
692 do_retry_with_no_persist(false);
695 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
696 // Test that an off-chain completed payment is not retryable on restart. This was previously
697 // broken for dust payments, but we test for both dust and non-dust payments.
699 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
701 let chanmon_cfgs = create_chanmon_cfgs(3);
702 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
704 let mut manually_accept_config = test_default_channel_config();
705 manually_accept_config.manually_accept_inbound_channels = true;
707 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
709 let first_persister: test_utils::TestPersister;
710 let first_new_chain_monitor: test_utils::TestChainMonitor;
711 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>;
712 let second_persister: test_utils::TestPersister;
713 let second_new_chain_monitor: test_utils::TestChainMonitor;
714 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>;
715 let third_persister: test_utils::TestPersister;
716 let third_new_chain_monitor: test_utils::TestChainMonitor;
717 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>;
719 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
721 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
722 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
723 confirm_transaction(&nodes[0], &funding_tx);
724 confirm_transaction(&nodes[1], &funding_tx);
725 // Ignore the announcement_signatures messages
726 nodes[0].node.get_and_clear_pending_msg_events();
727 nodes[1].node.get_and_clear_pending_msg_events();
728 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
730 // Serialize the ChannelManager prior to sending payments
731 let mut nodes_0_serialized = nodes[0].node.encode();
733 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
734 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 });
736 // The ChannelMonitor should always be the latest version, as we're required to persist it
737 // during the `commitment_signed_dance!()`.
738 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
740 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);
741 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
743 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
744 // force-close the channel.
745 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
746 nodes[0].node.timer_tick_occurred();
747 assert!(nodes[0].node.list_channels().is_empty());
748 assert!(nodes[0].node.has_pending_payments());
749 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
750 check_added_monitors!(nodes[0], 1);
752 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
753 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
755 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
757 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
758 // error, as the channel has hit the chain.
759 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
760 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
762 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
763 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
764 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
765 assert_eq!(as_err.len(), 1);
766 let bs_commitment_tx;
768 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
769 assert_eq!(node_id, nodes[1].node.get_our_node_id());
770 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
771 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())) });
772 check_added_monitors!(nodes[1], 1);
773 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
775 _ => panic!("Unexpected event"),
777 check_closed_broadcast!(nodes[1], false);
779 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
780 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
781 // incoming HTLCs with the same payment hash later.
782 nodes[2].node.fail_htlc_backwards(&payment_hash);
783 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
784 check_added_monitors!(nodes[2], 1);
786 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
787 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
788 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
789 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
790 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
792 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
793 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
794 // after the commitment transaction, so always connect the commitment transaction.
795 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
796 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
798 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
799 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
800 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
801 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
802 assert_eq!(as_htlc_timeout.len(), 1);
804 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
805 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
806 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
807 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
810 // Create a new channel on which to retry the payment before we fail the payment via the
811 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
812 // connecting several blocks while creating the channel (implying time has passed).
813 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
814 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
815 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
817 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
818 // confirming, we will fail as it's considered still-pending...
819 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
820 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
821 Err(PaymentSendFailure::DuplicatePayment) => {},
822 _ => panic!("Unexpected error")
824 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
826 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
827 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
828 // (which should also still work).
829 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
830 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
831 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
833 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
834 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
835 nodes_0_serialized = nodes[0].node.encode();
837 // After the payment failed, we're free to send it again.
838 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
839 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
840 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
842 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);
843 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
845 nodes[0].node.test_process_background_events();
846 check_added_monitors(&nodes[0], 1);
848 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
849 reconnect_args.send_channel_ready = (true, true);
850 reconnect_nodes(reconnect_args);
852 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
853 // the payment is not (spuriously) listed as still pending.
854 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
855 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
856 check_added_monitors!(nodes[0], 1);
857 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
858 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
860 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
861 Err(PaymentSendFailure::DuplicatePayment) => {},
862 _ => panic!("Unexpected error")
864 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
866 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
867 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
868 nodes_0_serialized = nodes[0].node.encode();
870 // Check that after reload we can send the payment again (though we shouldn't, since it was
871 // claimed previously).
872 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);
873 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
875 nodes[0].node.test_process_background_events();
876 check_added_monitors(&nodes[0], 1);
878 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
880 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
881 Err(PaymentSendFailure::DuplicatePayment) => {},
882 _ => panic!("Unexpected error")
884 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
888 fn test_completed_payment_not_retryable_on_reload() {
889 do_test_completed_payment_not_retryable_on_reload(true);
890 do_test_completed_payment_not_retryable_on_reload(false);
894 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
895 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
896 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
897 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
898 // the ChannelMonitor tells it to.
900 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
901 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
902 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
903 let chanmon_cfgs = create_chanmon_cfgs(2);
904 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
905 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
906 let persister: test_utils::TestPersister;
907 let new_chain_monitor: test_utils::TestChainMonitor;
908 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>;
909 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
911 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
913 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
915 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
916 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
917 check_closed_broadcast!(nodes[0], true);
918 check_added_monitors!(nodes[0], 1);
919 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
921 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
922 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
924 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
925 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
926 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
927 assert_eq!(node_txn.len(), 3);
928 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
929 check_spends!(node_txn[1], funding_tx);
930 check_spends!(node_txn[2], node_txn[1]);
931 let timeout_txn = vec![node_txn[2].clone()];
933 nodes[1].node.claim_funds(payment_preimage);
934 check_added_monitors!(nodes[1], 1);
935 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
937 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[1].clone()]));
938 check_closed_broadcast!(nodes[1], true);
939 check_added_monitors!(nodes[1], 1);
940 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
941 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
942 assert_eq!(claim_txn.len(), 1);
943 check_spends!(claim_txn[0], node_txn[1]);
945 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[1].clone()]));
947 if confirm_commitment_tx {
948 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
951 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] });
954 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
955 connect_block(&nodes[0], &claim_block);
956 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
959 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
960 // returning InProgress. This should cause the claim event to never make its way to the
962 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
963 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
966 connect_blocks(&nodes[0], 1);
968 connect_block(&nodes[0], &claim_block);
971 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
972 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
973 .get_mut(&funding_txo).unwrap().drain().collect();
974 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
975 // If we're testing connection idempotency we may get substantially more.
976 assert!(mon_updates.len() >= 1);
977 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
978 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
980 // If we persist the ChannelManager here, we should get the PaymentSent event after
982 let mut chan_manager_serialized = Vec::new();
983 if !persist_manager_post_event {
984 chan_manager_serialized = nodes[0].node.encode();
987 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
988 // payment sent event.
989 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
990 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
991 for update in mon_updates {
992 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
995 expect_payment_failed!(nodes[0], payment_hash, false);
997 expect_payment_sent!(nodes[0], payment_preimage);
1000 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
1002 if persist_manager_post_event {
1003 chan_manager_serialized = nodes[0].node.encode();
1006 // Now reload nodes[0]...
1007 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
1009 if persist_manager_post_event {
1010 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1011 } else if payment_timeout {
1012 expect_payment_failed!(nodes[0], payment_hash, false);
1014 expect_payment_sent!(nodes[0], payment_preimage);
1017 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
1018 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
1019 // payment events should kick in, leaving us with no pending events here.
1020 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
1021 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
1022 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1023 check_added_monitors(&nodes[0], 1);
1027 fn test_dup_htlc_onchain_fails_on_reload() {
1028 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
1029 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
1030 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
1031 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
1032 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
1033 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
1037 fn test_fulfill_restart_failure() {
1038 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
1039 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
1040 // again, or fail it, giving us free money.
1042 // Of course probably they won't fail it and give us free money, but because we have code to
1043 // handle it, we should test the logic for it anyway. We do that here.
1044 let chanmon_cfgs = create_chanmon_cfgs(2);
1045 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1046 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1047 let persister: test_utils::TestPersister;
1048 let new_chain_monitor: test_utils::TestChainMonitor;
1049 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>;
1050 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1052 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1053 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
1055 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
1056 // pre-fulfill, which we do by serializing it here.
1057 let chan_manager_serialized = nodes[1].node.encode();
1058 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1060 nodes[1].node.claim_funds(payment_preimage);
1061 check_added_monitors!(nodes[1], 1);
1062 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1064 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1065 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1066 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
1068 // Now reload nodes[1]...
1069 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1071 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1072 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1074 nodes[1].node.fail_htlc_backwards(&payment_hash);
1075 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1076 check_added_monitors!(nodes[1], 1);
1077 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1078 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1079 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1080 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1081 // it had already considered the payment fulfilled, and now they just got free money.
1082 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1086 fn get_ldk_payment_preimage() {
1087 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1088 let chanmon_cfgs = create_chanmon_cfgs(2);
1089 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1090 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1091 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1092 create_announced_chan_between_nodes(&nodes, 0, 1);
1094 let amt_msat = 60_000;
1095 let expiry_secs = 60 * 60;
1096 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1098 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1099 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
1100 let scorer = test_utils::TestScorer::new();
1101 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1102 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1103 let route = get_route(
1104 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
1105 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
1106 amt_msat, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
1107 nodes[0].node.send_payment_with_route(&route, payment_hash,
1108 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1109 check_added_monitors!(nodes[0], 1);
1111 // Make sure to use `get_payment_preimage`
1112 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1113 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1114 assert_eq!(events.len(), 1);
1115 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1116 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1120 fn sent_probe_is_probe_of_sending_node() {
1121 let chanmon_cfgs = create_chanmon_cfgs(3);
1122 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1123 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1124 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1126 create_announced_chan_between_nodes(&nodes, 0, 1);
1127 create_announced_chan_between_nodes(&nodes, 1, 2);
1129 // First check we refuse to build a single-hop probe
1130 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1131 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1133 // Then build an actual two-hop probing path
1134 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1136 match nodes[0].node.send_probe(route.paths[0].clone()) {
1137 Ok((payment_hash, payment_id)) => {
1138 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1139 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1140 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1145 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1146 check_added_monitors!(nodes[0], 1);
1150 fn successful_probe_yields_event() {
1151 let chanmon_cfgs = create_chanmon_cfgs(3);
1152 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1153 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1154 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1156 create_announced_chan_between_nodes(&nodes, 0, 1);
1157 create_announced_chan_between_nodes(&nodes, 1, 2);
1159 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1161 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1163 // node[0] -- update_add_htlcs -> node[1]
1164 check_added_monitors!(nodes[0], 1);
1165 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1166 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1167 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1168 check_added_monitors!(nodes[1], 0);
1169 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1170 expect_pending_htlcs_forwardable!(nodes[1]);
1172 // node[1] -- update_add_htlcs -> node[2]
1173 check_added_monitors!(nodes[1], 1);
1174 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1175 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1176 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1177 check_added_monitors!(nodes[2], 0);
1178 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
1180 // node[1] <- update_fail_htlcs -- node[2]
1181 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1182 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1183 check_added_monitors!(nodes[1], 0);
1184 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1186 // node[0] <- update_fail_htlcs -- node[1]
1187 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1188 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1189 check_added_monitors!(nodes[0], 0);
1190 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1192 let mut events = nodes[0].node.get_and_clear_pending_events();
1193 assert_eq!(events.len(), 1);
1194 match events.drain(..).next().unwrap() {
1195 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1196 assert_eq!(payment_id, ev_pid);
1197 assert_eq!(payment_hash, ev_ph);
1201 assert!(!nodes[0].node.has_pending_payments());
1205 fn failed_probe_yields_event() {
1206 let chanmon_cfgs = create_chanmon_cfgs(3);
1207 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1208 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1209 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1211 create_announced_chan_between_nodes(&nodes, 0, 1);
1212 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1214 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1216 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000);
1218 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1220 // node[0] -- update_add_htlcs -> node[1]
1221 check_added_monitors!(nodes[0], 1);
1222 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1223 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1224 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1225 check_added_monitors!(nodes[1], 0);
1226 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1227 expect_pending_htlcs_forwardable!(nodes[1]);
1229 // node[0] <- update_fail_htlcs -- node[1]
1230 check_added_monitors!(nodes[1], 1);
1231 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1232 // Skip the PendingHTLCsForwardable event
1233 let _events = nodes[1].node.get_and_clear_pending_events();
1234 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1235 check_added_monitors!(nodes[0], 0);
1236 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1238 let mut events = nodes[0].node.get_and_clear_pending_events();
1239 assert_eq!(events.len(), 1);
1240 match events.drain(..).next().unwrap() {
1241 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1242 assert_eq!(payment_id, ev_pid);
1243 assert_eq!(payment_hash, ev_ph);
1247 assert!(!nodes[0].node.has_pending_payments());
1251 fn onchain_failed_probe_yields_event() {
1252 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1254 let chanmon_cfgs = create_chanmon_cfgs(3);
1255 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1256 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1257 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1259 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1260 create_announced_chan_between_nodes(&nodes, 1, 2);
1262 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1264 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1265 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000);
1266 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1268 // node[0] -- update_add_htlcs -> node[1]
1269 check_added_monitors!(nodes[0], 1);
1270 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1271 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1272 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1273 check_added_monitors!(nodes[1], 0);
1274 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1275 expect_pending_htlcs_forwardable!(nodes[1]);
1277 check_added_monitors!(nodes[1], 1);
1278 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1280 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1281 // Node A, which after 6 confirmations should result in a probe failure event.
1282 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1283 confirm_transaction(&nodes[0], &bs_txn[0]);
1284 check_closed_broadcast!(&nodes[0], true);
1285 check_added_monitors!(nodes[0], 1);
1287 let mut events = nodes[0].node.get_and_clear_pending_events();
1288 assert_eq!(events.len(), 2);
1289 let mut found_probe_failed = false;
1290 for event in events.drain(..) {
1292 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1293 assert_eq!(payment_id, ev_pid);
1294 assert_eq!(payment_hash, ev_ph);
1295 found_probe_failed = true;
1297 Event::ChannelClosed { .. } => {},
1301 assert!(found_probe_failed);
1302 assert!(!nodes[0].node.has_pending_payments());
1306 fn claimed_send_payment_idempotent() {
1307 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1308 let chanmon_cfgs = create_chanmon_cfgs(2);
1309 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1310 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1311 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1313 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1315 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1316 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1318 macro_rules! check_send_rejected {
1320 // If we try to resend a new payment with a different payment_hash but with the same
1321 // payment_id, it should be rejected.
1322 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1323 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1325 Err(PaymentSendFailure::DuplicatePayment) => {},
1326 _ => panic!("Unexpected send result: {:?}", send_result),
1329 // Further, if we try to send a spontaneous payment with the same payment_id it should
1330 // also be rejected.
1331 let send_result = nodes[0].node.send_spontaneous_payment(
1332 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1334 Err(PaymentSendFailure::DuplicatePayment) => {},
1335 _ => panic!("Unexpected send result: {:?}", send_result),
1340 check_send_rejected!();
1342 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1343 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1344 // we must remain just as idempotent as we were before.
1345 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1347 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1348 nodes[0].node.timer_tick_occurred();
1351 check_send_rejected!();
1353 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1354 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1355 // the payment complete. However, they could have called `send_payment` while the event was
1356 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1357 // after the event is handled a duplicate payment should sitll be rejected.
1358 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1359 check_send_rejected!();
1361 // If relatively little time has passed, a duplicate payment should still fail.
1362 nodes[0].node.timer_tick_occurred();
1363 check_send_rejected!();
1365 // However, after some time has passed (at least more than the one timer tick above), a
1366 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1367 // references to the old payment data.
1368 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1369 nodes[0].node.timer_tick_occurred();
1372 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1373 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1374 check_added_monitors!(nodes[0], 1);
1375 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1376 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1380 fn abandoned_send_payment_idempotent() {
1381 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1383 let chanmon_cfgs = create_chanmon_cfgs(2);
1384 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1385 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1386 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1388 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1390 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1391 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1393 macro_rules! check_send_rejected {
1395 // If we try to resend a new payment with a different payment_hash but with the same
1396 // payment_id, it should be rejected.
1397 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1398 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1400 Err(PaymentSendFailure::DuplicatePayment) => {},
1401 _ => panic!("Unexpected send result: {:?}", send_result),
1404 // Further, if we try to send a spontaneous payment with the same payment_id it should
1405 // also be rejected.
1406 let send_result = nodes[0].node.send_spontaneous_payment(
1407 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1409 Err(PaymentSendFailure::DuplicatePayment) => {},
1410 _ => panic!("Unexpected send result: {:?}", send_result),
1415 check_send_rejected!();
1417 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1418 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1420 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1422 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1423 nodes[0].node.timer_tick_occurred();
1425 check_send_rejected!();
1427 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1429 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1430 // failed payment back.
1431 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1432 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1433 check_added_monitors!(nodes[0], 1);
1434 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1435 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1438 #[derive(PartialEq)]
1439 enum InterceptTest {
1446 fn test_trivial_inflight_htlc_tracking(){
1447 // In this test, we test three scenarios:
1448 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1449 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1450 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1451 let chanmon_cfgs = create_chanmon_cfgs(3);
1452 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1453 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1454 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1456 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1457 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1459 // Send and claim the payment. Inflight HTLCs should be empty.
1460 let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1461 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1463 let mut node_0_per_peer_lock;
1464 let mut node_0_peer_state_lock;
1465 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1467 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1468 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1469 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1470 channel_1.context.get_short_channel_id().unwrap()
1472 assert_eq!(chan_1_used_liquidity, None);
1475 let mut node_1_per_peer_lock;
1476 let mut node_1_peer_state_lock;
1477 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1479 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1480 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1481 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1482 channel_2.context.get_short_channel_id().unwrap()
1485 assert_eq!(chan_2_used_liquidity, None);
1487 let pending_payments = nodes[0].node.list_recent_payments();
1488 assert_eq!(pending_payments.len(), 1);
1489 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1491 // Remove fulfilled payment
1492 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1493 nodes[0].node.timer_tick_occurred();
1496 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1497 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1498 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1500 let mut node_0_per_peer_lock;
1501 let mut node_0_peer_state_lock;
1502 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1504 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1505 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1506 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1507 channel_1.context.get_short_channel_id().unwrap()
1509 // First hop accounts for expected 1000 msat fee
1510 assert_eq!(chan_1_used_liquidity, Some(501000));
1513 let mut node_1_per_peer_lock;
1514 let mut node_1_peer_state_lock;
1515 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1517 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1518 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1519 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1520 channel_2.context.get_short_channel_id().unwrap()
1523 assert_eq!(chan_2_used_liquidity, Some(500000));
1525 let pending_payments = nodes[0].node.list_recent_payments();
1526 assert_eq!(pending_payments.len(), 1);
1527 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1529 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1530 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1532 // Remove fulfilled payment
1533 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1534 nodes[0].node.timer_tick_occurred();
1537 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1539 let mut node_0_per_peer_lock;
1540 let mut node_0_peer_state_lock;
1541 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1543 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1544 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1545 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1546 channel_1.context.get_short_channel_id().unwrap()
1548 assert_eq!(chan_1_used_liquidity, None);
1551 let mut node_1_per_peer_lock;
1552 let mut node_1_peer_state_lock;
1553 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1555 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1556 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1557 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1558 channel_2.context.get_short_channel_id().unwrap()
1560 assert_eq!(chan_2_used_liquidity, None);
1563 let pending_payments = nodes[0].node.list_recent_payments();
1564 assert_eq!(pending_payments.len(), 0);
1568 fn test_holding_cell_inflight_htlcs() {
1569 let chanmon_cfgs = create_chanmon_cfgs(2);
1570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1572 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1573 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1575 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1576 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1578 // Queue up two payments - one will be delivered right away, one immediately goes into the
1579 // holding cell as nodes[0] is AwaitingRAA.
1581 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1582 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1583 check_added_monitors!(nodes[0], 1);
1584 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1585 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1586 check_added_monitors!(nodes[0], 0);
1589 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1592 let mut node_0_per_peer_lock;
1593 let mut node_0_peer_state_lock;
1594 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1596 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1597 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1598 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1599 channel.context.get_short_channel_id().unwrap()
1602 assert_eq!(used_liquidity, Some(2000000));
1605 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1606 nodes[0].node.get_and_clear_pending_msg_events();
1610 fn intercepted_payment() {
1611 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1612 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1613 // payment or (b) fail the payment.
1614 do_test_intercepted_payment(InterceptTest::Forward);
1615 do_test_intercepted_payment(InterceptTest::Fail);
1616 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1617 do_test_intercepted_payment(InterceptTest::Timeout);
1620 fn do_test_intercepted_payment(test: InterceptTest) {
1621 let chanmon_cfgs = create_chanmon_cfgs(3);
1622 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1624 let mut zero_conf_chan_config = test_default_channel_config();
1625 zero_conf_chan_config.manually_accept_inbound_channels = true;
1626 let mut intercept_forwards_config = test_default_channel_config();
1627 intercept_forwards_config.accept_intercept_htlcs = true;
1628 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1630 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1631 let scorer = test_utils::TestScorer::new();
1632 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1634 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1636 let amt_msat = 100_000;
1637 let intercept_scid = nodes[1].node.get_intercept_scid();
1638 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1639 .with_route_hints(vec![
1640 RouteHint(vec![RouteHintHop {
1641 src_node_id: nodes[1].node.get_our_node_id(),
1642 short_channel_id: intercept_scid,
1645 proportional_millionths: 0,
1647 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1648 htlc_minimum_msat: None,
1649 htlc_maximum_msat: None,
1652 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1653 let route_params = RouteParameters {
1655 final_value_msat: amt_msat,
1657 let route = get_route(
1658 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1659 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1660 nodes[0].logger, &scorer, &(), &random_seed_bytes,
1663 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1664 nodes[0].node.send_payment_with_route(&route, payment_hash,
1665 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1666 let payment_event = {
1668 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1669 assert_eq!(added_monitors.len(), 1);
1670 added_monitors.clear();
1672 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1673 assert_eq!(events.len(), 1);
1674 SendEvent::from_event(events.remove(0))
1676 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1677 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1679 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1680 let events = nodes[1].node.get_and_clear_pending_events();
1681 assert_eq!(events.len(), 1);
1682 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1683 crate::events::Event::HTLCIntercepted {
1684 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1686 assert_eq!(pmt_hash, payment_hash);
1687 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1688 assert_eq!(short_channel_id, intercept_scid);
1689 (intercept_id, expected_outbound_amount_msat)
1694 // Check for unknown channel id error.
1695 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();
1696 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable {
1697 err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1698 log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1700 if test == InterceptTest::Fail {
1701 // Ensure we can fail the intercepted payment back.
1702 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1703 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1704 nodes[1].node.process_pending_htlc_forwards();
1705 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1706 check_added_monitors!(&nodes[1], 1);
1707 assert!(update_fail.update_fail_htlcs.len() == 1);
1708 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1709 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1710 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1712 // Ensure the payment fails with the expected error.
1713 let fail_conditions = PaymentFailedConditions::new()
1714 .blamed_scid(intercept_scid)
1715 .blamed_chan_closed(true)
1716 .expected_htlc_error_data(0x4000 | 10, &[]);
1717 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1718 } else if test == InterceptTest::Forward {
1719 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1720 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1721 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();
1722 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1723 err: format!("Funded channel with id {} not found for the passed counterparty node_id {}. Channel may still be opening.",
1724 log_bytes!(temp_chan_id), nodes[2].node.get_our_node_id()) });
1725 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1727 // Open the just-in-time channel so the payment can then be forwarded.
1728 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1730 // Finally, forward the intercepted payment through and claim it.
1731 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1732 expect_pending_htlcs_forwardable!(nodes[1]);
1734 let payment_event = {
1736 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1737 assert_eq!(added_monitors.len(), 1);
1738 added_monitors.clear();
1740 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1741 assert_eq!(events.len(), 1);
1742 SendEvent::from_event(events.remove(0))
1744 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1745 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1746 expect_pending_htlcs_forwardable!(nodes[2]);
1748 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1749 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1750 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1751 let events = nodes[0].node.get_and_clear_pending_events();
1752 assert_eq!(events.len(), 2);
1754 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1755 assert_eq!(payment_preimage, *ev_preimage);
1756 assert_eq!(payment_hash, *ev_hash);
1757 assert_eq!(fee_paid_msat, &Some(1000));
1759 _ => panic!("Unexpected event")
1762 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1763 assert_eq!(hash, Some(payment_hash));
1765 _ => panic!("Unexpected event")
1767 } else if test == InterceptTest::Timeout {
1768 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
1769 connect_block(&nodes[0], &block);
1770 connect_block(&nodes[1], &block);
1771 for _ in 0..TEST_FINAL_CLTV {
1772 block.header.prev_blockhash = block.block_hash();
1773 connect_block(&nodes[0], &block);
1774 connect_block(&nodes[1], &block);
1776 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1777 check_added_monitors!(nodes[1], 1);
1778 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1779 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1780 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1781 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1782 assert!(htlc_timeout_updates.update_fee.is_none());
1784 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1785 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1786 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1788 // Check for unknown intercept id error.
1789 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1790 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();
1791 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1792 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1793 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1798 fn accept_underpaying_htlcs_config() {
1799 do_accept_underpaying_htlcs_config(1);
1800 do_accept_underpaying_htlcs_config(2);
1801 do_accept_underpaying_htlcs_config(3);
1804 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
1805 let chanmon_cfgs = create_chanmon_cfgs(3);
1806 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1807 let mut intercept_forwards_config = test_default_channel_config();
1808 intercept_forwards_config.accept_intercept_htlcs = true;
1809 let mut underpay_config = test_default_channel_config();
1810 underpay_config.channel_config.accept_underpaying_htlcs = true;
1811 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
1812 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1814 let mut chan_ids = Vec::new();
1815 for _ in 0..num_mpp_parts {
1816 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000, 0);
1817 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 2_000_000, 0).0.channel_id;
1818 chan_ids.push(channel_id);
1821 // Send the initial payment.
1822 let amt_msat = 900_000;
1823 let skimmed_fee_msat = 20;
1824 let mut route_hints = Vec::new();
1825 for _ in 0..num_mpp_parts {
1826 route_hints.push(RouteHint(vec![RouteHintHop {
1827 src_node_id: nodes[1].node.get_our_node_id(),
1828 short_channel_id: nodes[1].node.get_intercept_scid(),
1831 proportional_millionths: 0,
1833 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1834 htlc_minimum_msat: None,
1835 htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
1838 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1839 .with_route_hints(route_hints).unwrap()
1840 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1841 let route_params = RouteParameters {
1843 final_value_msat: amt_msat,
1845 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1846 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1847 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
1848 check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
1849 let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
1850 assert_eq!(events.len(), num_mpp_parts);
1852 // Forward the intercepted payments.
1853 for (idx, ev) in events.into_iter().enumerate() {
1854 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
1855 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
1857 let events = nodes[1].node.get_and_clear_pending_events();
1858 assert_eq!(events.len(), 1);
1859 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
1860 crate::events::Event::HTLCIntercepted {
1861 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
1863 assert_eq!(pmt_hash, payment_hash);
1864 (intercept_id, expected_outbound_amount_msat)
1868 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
1869 nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
1870 expect_pending_htlcs_forwardable!(nodes[1]);
1871 let payment_event = {
1873 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1874 assert_eq!(added_monitors.len(), 1);
1875 added_monitors.clear();
1877 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1878 assert_eq!(events.len(), 1);
1879 SendEvent::from_event(events.remove(0))
1881 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1882 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
1883 if idx == num_mpp_parts - 1 {
1884 expect_pending_htlcs_forwardable!(nodes[2]);
1888 // Claim the payment and check that the skimmed fee is as expected.
1889 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1890 let events = nodes[2].node.get_and_clear_pending_events();
1891 assert_eq!(events.len(), 1);
1893 crate::events::Event::PaymentClaimable {
1894 ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
1896 assert_eq!(payment_hash, payment_hash);
1897 assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
1898 assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
1899 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1901 crate::events::PaymentPurpose::InvoicePayment { payment_preimage: ev_payment_preimage,
1902 payment_secret: ev_payment_secret, .. } =>
1904 assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
1905 assert_eq!(payment_secret, *ev_payment_secret);
1910 _ => panic!("Unexpected event"),
1912 let mut expected_paths_vecs = Vec::new();
1913 let mut expected_paths = Vec::new();
1914 for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
1915 for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
1916 let total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
1917 &nodes[0], &expected_paths[..], &vec![skimmed_fee_msat as u32; num_mpp_parts][..], false,
1919 // The sender doesn't know that the penultimate hop took an extra fee.
1920 expect_payment_sent(&nodes[0], payment_preimage,
1921 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true);
1924 #[derive(PartialEq)]
1935 fn automatic_retries() {
1936 do_automatic_retries(AutoRetry::Success);
1937 do_automatic_retries(AutoRetry::Spontaneous);
1938 do_automatic_retries(AutoRetry::FailAttempts);
1939 do_automatic_retries(AutoRetry::FailTimeout);
1940 do_automatic_retries(AutoRetry::FailOnRestart);
1941 do_automatic_retries(AutoRetry::FailOnRetry);
1943 fn do_automatic_retries(test: AutoRetry) {
1944 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1946 let chanmon_cfgs = create_chanmon_cfgs(3);
1947 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1948 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1951 let new_chain_monitor;
1952 let node_0_deserialized;
1954 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1955 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1956 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1958 // Marshall data to send the payment
1959 #[cfg(feature = "std")]
1960 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1961 #[cfg(not(feature = "std"))]
1962 let payment_expiry_secs = 60 * 60;
1963 let amt_msat = 1000;
1964 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1965 invoice_features.set_variable_length_onion_required();
1966 invoice_features.set_payment_secret_required();
1967 invoice_features.set_basic_mpp_optional();
1968 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1969 .with_expiry_time(payment_expiry_secs as u64)
1970 .with_bolt11_features(invoice_features).unwrap();
1971 let route_params = RouteParameters {
1973 final_value_msat: amt_msat,
1975 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1977 macro_rules! pass_failed_attempt_with_retry_along_path {
1978 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1979 // Send a payment attempt that fails due to lack of liquidity on the second hop
1980 check_added_monitors!(nodes[0], 1);
1981 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1982 let mut update_add = update_0.update_add_htlcs[0].clone();
1983 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1984 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1985 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1986 nodes[1].node.process_pending_htlc_forwards();
1987 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1988 vec![HTLCDestination::NextHopChannel {
1989 node_id: Some(nodes[2].node.get_our_node_id()),
1990 channel_id: $failing_channel_id,
1992 nodes[1].node.process_pending_htlc_forwards();
1993 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1994 check_added_monitors!(&nodes[1], 1);
1995 assert!(update_1.update_fail_htlcs.len() == 1);
1996 let fail_msg = update_1.update_fail_htlcs[0].clone();
1997 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1998 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
2000 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
2001 let mut events = nodes[0].node.get_and_clear_pending_events();
2002 assert_eq!(events.len(), 2);
2004 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2005 assert_eq!(payment_hash, ev_payment_hash);
2006 assert_eq!(payment_failed_permanently, false);
2008 _ => panic!("Unexpected event"),
2010 if $expect_pending_htlcs_forwardable {
2012 Event::PendingHTLCsForwardable { .. } => {},
2013 _ => panic!("Unexpected event"),
2017 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
2018 assert_eq!(payment_hash, ev_payment_hash);
2020 _ => panic!("Unexpected event"),
2026 if test == AutoRetry::Success {
2027 // Test that we can succeed on the first retry.
2028 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2029 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2030 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2032 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2033 // attempt, since the initial second hop channel will be excluded from pathfinding
2034 create_announced_chan_between_nodes(&nodes, 1, 2);
2036 // We retry payments in `process_pending_htlc_forwards`
2037 nodes[0].node.process_pending_htlc_forwards();
2038 check_added_monitors!(nodes[0], 1);
2039 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2040 assert_eq!(msg_events.len(), 1);
2041 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
2042 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2043 } else if test == AutoRetry::Spontaneous {
2044 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
2045 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
2046 Retry::Attempts(1)).unwrap();
2047 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2049 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2050 // attempt, since the initial second hop channel will be excluded from pathfinding
2051 create_announced_chan_between_nodes(&nodes, 1, 2);
2053 // We retry payments in `process_pending_htlc_forwards`
2054 nodes[0].node.process_pending_htlc_forwards();
2055 check_added_monitors!(nodes[0], 1);
2056 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2057 assert_eq!(msg_events.len(), 1);
2058 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2059 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2060 } else if test == AutoRetry::FailAttempts {
2061 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2062 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2063 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2064 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2066 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2067 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2068 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2070 // We retry payments in `process_pending_htlc_forwards`
2071 nodes[0].node.process_pending_htlc_forwards();
2072 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2074 // Ensure we won't retry a second time.
2075 nodes[0].node.process_pending_htlc_forwards();
2076 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2077 assert_eq!(msg_events.len(), 0);
2078 } else if test == AutoRetry::FailTimeout {
2079 #[cfg(not(feature = "no-std"))] {
2080 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2081 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2082 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2083 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2085 // Advance the time so the second attempt fails due to timeout.
2086 SinceEpoch::advance(Duration::from_secs(61));
2088 // Make sure we don't retry again.
2089 nodes[0].node.process_pending_htlc_forwards();
2090 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2091 assert_eq!(msg_events.len(), 0);
2093 let mut events = nodes[0].node.get_and_clear_pending_events();
2094 assert_eq!(events.len(), 1);
2096 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2097 assert_eq!(payment_hash, *ev_payment_hash);
2098 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2099 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2101 _ => panic!("Unexpected event"),
2104 } else if test == AutoRetry::FailOnRestart {
2105 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2106 // attempts remaining prior to restart.
2107 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2108 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2109 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2111 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2112 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2113 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2115 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2116 nodes[0].node.process_pending_htlc_forwards();
2117 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2119 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2120 let node_encoded = nodes[0].node.encode();
2121 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2122 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2124 let mut events = nodes[0].node.get_and_clear_pending_events();
2125 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2126 // Make sure we don't retry again.
2127 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2128 assert_eq!(msg_events.len(), 0);
2130 let mut events = nodes[0].node.get_and_clear_pending_events();
2131 assert_eq!(events.len(), 1);
2133 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2134 assert_eq!(payment_hash, *ev_payment_hash);
2135 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2136 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2138 _ => panic!("Unexpected event"),
2140 } else if test == AutoRetry::FailOnRetry {
2141 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2142 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2143 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2145 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2146 // fail to find a route.
2147 nodes[0].node.process_pending_htlc_forwards();
2148 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2149 assert_eq!(msg_events.len(), 0);
2151 let mut events = nodes[0].node.get_and_clear_pending_events();
2152 assert_eq!(events.len(), 1);
2154 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2155 assert_eq!(payment_hash, *ev_payment_hash);
2156 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2157 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2159 _ => panic!("Unexpected event"),
2165 fn auto_retry_partial_failure() {
2166 // Test that we'll retry appropriately on send partial failure and retry partial failure.
2167 let chanmon_cfgs = create_chanmon_cfgs(2);
2168 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2169 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2170 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2172 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2173 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2174 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2176 // Marshall data to send the payment
2177 let amt_msat = 20_000;
2178 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2179 #[cfg(feature = "std")]
2180 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2181 #[cfg(not(feature = "std"))]
2182 let payment_expiry_secs = 60 * 60;
2183 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2184 invoice_features.set_variable_length_onion_required();
2185 invoice_features.set_payment_secret_required();
2186 invoice_features.set_basic_mpp_optional();
2187 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2188 .with_expiry_time(payment_expiry_secs as u64)
2189 .with_bolt11_features(invoice_features).unwrap();
2190 let route_params = RouteParameters {
2192 final_value_msat: amt_msat,
2195 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
2196 // second (for the initial send path2 over chan_2) fails.
2197 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2198 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2199 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
2200 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
2201 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2202 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2203 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
2205 // Configure the initial send, retry1 and retry2's paths.
2206 let send_route = Route {
2208 Path { hops: vec![RouteHop {
2209 pubkey: nodes[1].node.get_our_node_id(),
2210 node_features: nodes[1].node.node_features(),
2211 short_channel_id: chan_1_id,
2212 channel_features: nodes[1].node.channel_features(),
2213 fee_msat: amt_msat / 2,
2214 cltv_expiry_delta: 100,
2215 }], blinded_tail: None },
2216 Path { hops: vec![RouteHop {
2217 pubkey: nodes[1].node.get_our_node_id(),
2218 node_features: nodes[1].node.node_features(),
2219 short_channel_id: chan_2_id,
2220 channel_features: nodes[1].node.channel_features(),
2221 fee_msat: amt_msat / 2,
2222 cltv_expiry_delta: 100,
2223 }], blinded_tail: None },
2225 payment_params: Some(route_params.payment_params.clone()),
2227 let retry_1_route = Route {
2229 Path { hops: vec![RouteHop {
2230 pubkey: nodes[1].node.get_our_node_id(),
2231 node_features: nodes[1].node.node_features(),
2232 short_channel_id: chan_1_id,
2233 channel_features: nodes[1].node.channel_features(),
2234 fee_msat: amt_msat / 4,
2235 cltv_expiry_delta: 100,
2236 }], blinded_tail: None },
2237 Path { hops: vec![RouteHop {
2238 pubkey: nodes[1].node.get_our_node_id(),
2239 node_features: nodes[1].node.node_features(),
2240 short_channel_id: chan_3_id,
2241 channel_features: nodes[1].node.channel_features(),
2242 fee_msat: amt_msat / 4,
2243 cltv_expiry_delta: 100,
2244 }], blinded_tail: None },
2246 payment_params: Some(route_params.payment_params.clone()),
2248 let retry_2_route = Route {
2250 Path { hops: vec![RouteHop {
2251 pubkey: nodes[1].node.get_our_node_id(),
2252 node_features: nodes[1].node.node_features(),
2253 short_channel_id: chan_1_id,
2254 channel_features: nodes[1].node.channel_features(),
2255 fee_msat: amt_msat / 4,
2256 cltv_expiry_delta: 100,
2257 }], blinded_tail: None },
2259 payment_params: Some(route_params.payment_params.clone()),
2261 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2262 let mut payment_params = route_params.payment_params.clone();
2263 payment_params.previously_failed_channels.push(chan_2_id);
2264 nodes[0].router.expect_find_route(RouteParameters {
2265 payment_params, final_value_msat: amt_msat / 2,
2266 }, Ok(retry_1_route));
2267 let mut payment_params = route_params.payment_params.clone();
2268 payment_params.previously_failed_channels.push(chan_3_id);
2269 nodes[0].router.expect_find_route(RouteParameters {
2270 payment_params, final_value_msat: amt_msat / 4,
2271 }, Ok(retry_2_route));
2273 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2274 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2275 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2276 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
2277 assert_eq!(closed_chan_events.len(), 4);
2278 match closed_chan_events[0] {
2279 Event::ChannelClosed { .. } => {},
2280 _ => panic!("Unexpected event"),
2282 match closed_chan_events[1] {
2283 Event::PaymentPathFailed { .. } => {},
2284 _ => panic!("Unexpected event"),
2286 match closed_chan_events[2] {
2287 Event::ChannelClosed { .. } => {},
2288 _ => panic!("Unexpected event"),
2290 match closed_chan_events[3] {
2291 Event::PaymentPathFailed { .. } => {},
2292 _ => panic!("Unexpected event"),
2295 // Pass the first part of the payment along the path.
2296 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
2297 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2299 // First message is the first update_add, remaining messages are broadcasting channel updates and
2300 // errors for the permfailed channels
2301 assert_eq!(msg_events.len(), 5);
2302 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2304 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2305 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2306 check_added_monitors!(nodes[1], 1);
2307 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2309 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2310 check_added_monitors!(nodes[0], 1);
2311 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2313 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2314 check_added_monitors!(nodes[0], 1);
2315 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2317 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2318 check_added_monitors!(nodes[1], 1);
2320 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2321 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2322 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2323 check_added_monitors!(nodes[1], 1);
2324 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2326 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2327 check_added_monitors!(nodes[0], 1);
2329 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2330 check_added_monitors!(nodes[0], 1);
2331 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2333 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2334 check_added_monitors!(nodes[1], 1);
2336 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2337 nodes[1].node.process_pending_htlc_forwards();
2338 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2339 nodes[1].node.claim_funds(payment_preimage);
2340 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2341 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2342 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2344 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2345 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2346 check_added_monitors!(nodes[0], 1);
2347 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2349 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2350 check_added_monitors!(nodes[1], 4);
2351 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2353 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2354 check_added_monitors!(nodes[1], 1);
2355 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2357 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2358 check_added_monitors!(nodes[0], 1);
2360 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2361 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2362 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2363 check_added_monitors!(nodes[0], 1);
2364 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2366 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2367 check_added_monitors!(nodes[1], 1);
2369 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2370 check_added_monitors!(nodes[1], 1);
2371 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2373 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2374 check_added_monitors!(nodes[0], 1);
2375 expect_payment_sent!(nodes[0], payment_preimage);
2379 fn auto_retry_zero_attempts_send_error() {
2380 let chanmon_cfgs = create_chanmon_cfgs(2);
2381 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2382 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2383 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2385 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2386 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2388 // Marshall data to send the payment
2389 let amt_msat = 20_000;
2390 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2391 #[cfg(feature = "std")]
2392 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2393 #[cfg(not(feature = "std"))]
2394 let payment_expiry_secs = 60 * 60;
2395 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2396 invoice_features.set_variable_length_onion_required();
2397 invoice_features.set_payment_secret_required();
2398 invoice_features.set_basic_mpp_optional();
2399 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2400 .with_expiry_time(payment_expiry_secs as u64)
2401 .with_bolt11_features(invoice_features).unwrap();
2402 let route_params = RouteParameters {
2404 final_value_msat: amt_msat,
2407 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2408 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2409 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2410 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2411 let events = nodes[0].node.get_and_clear_pending_events();
2412 assert_eq!(events.len(), 3);
2413 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2414 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2415 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2416 check_added_monitors!(nodes[0], 2);
2420 fn fails_paying_after_rejected_by_payee() {
2421 let chanmon_cfgs = create_chanmon_cfgs(2);
2422 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2423 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2424 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2426 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2428 // Marshall data to send the payment
2429 let amt_msat = 20_000;
2430 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2431 #[cfg(feature = "std")]
2432 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2433 #[cfg(not(feature = "std"))]
2434 let payment_expiry_secs = 60 * 60;
2435 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2436 invoice_features.set_variable_length_onion_required();
2437 invoice_features.set_payment_secret_required();
2438 invoice_features.set_basic_mpp_optional();
2439 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2440 .with_expiry_time(payment_expiry_secs as u64)
2441 .with_bolt11_features(invoice_features).unwrap();
2442 let route_params = RouteParameters {
2444 final_value_msat: amt_msat,
2447 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2448 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2449 check_added_monitors!(nodes[0], 1);
2450 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2451 assert_eq!(events.len(), 1);
2452 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2453 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2454 check_added_monitors!(nodes[1], 0);
2455 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2456 expect_pending_htlcs_forwardable!(nodes[1]);
2457 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2459 nodes[1].node.fail_htlc_backwards(&payment_hash);
2460 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2461 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2465 fn retry_multi_path_single_failed_payment() {
2466 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2467 let chanmon_cfgs = create_chanmon_cfgs(2);
2468 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2469 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2470 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2472 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2473 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2475 let amt_msat = 100_010_000;
2477 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2478 #[cfg(feature = "std")]
2479 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2480 #[cfg(not(feature = "std"))]
2481 let payment_expiry_secs = 60 * 60;
2482 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2483 invoice_features.set_variable_length_onion_required();
2484 invoice_features.set_payment_secret_required();
2485 invoice_features.set_basic_mpp_optional();
2486 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2487 .with_expiry_time(payment_expiry_secs as u64)
2488 .with_bolt11_features(invoice_features).unwrap();
2489 let route_params = RouteParameters {
2490 payment_params: payment_params.clone(),
2491 final_value_msat: amt_msat,
2494 let chans = nodes[0].node.list_usable_channels();
2495 let mut route = Route {
2497 Path { hops: vec![RouteHop {
2498 pubkey: nodes[1].node.get_our_node_id(),
2499 node_features: nodes[1].node.node_features(),
2500 short_channel_id: chans[0].short_channel_id.unwrap(),
2501 channel_features: nodes[1].node.channel_features(),
2503 cltv_expiry_delta: 100,
2504 }], blinded_tail: None },
2505 Path { hops: vec![RouteHop {
2506 pubkey: nodes[1].node.get_our_node_id(),
2507 node_features: nodes[1].node.node_features(),
2508 short_channel_id: chans[1].short_channel_id.unwrap(),
2509 channel_features: nodes[1].node.channel_features(),
2510 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2511 cltv_expiry_delta: 100,
2512 }], blinded_tail: None },
2514 payment_params: Some(payment_params),
2516 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2517 // On retry, split the payment across both channels.
2518 route.paths[0].hops[0].fee_msat = 50_000_001;
2519 route.paths[1].hops[0].fee_msat = 50_000_000;
2520 let mut pay_params = route.payment_params.clone().unwrap();
2521 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2522 nodes[0].router.expect_find_route(RouteParameters {
2523 payment_params: pay_params,
2524 // Note that the second request here requests the amount we originally failed to send,
2525 // not the amount remaining on the full payment, which should be changed.
2526 final_value_msat: 100_000_001,
2527 }, Ok(route.clone()));
2530 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2531 // The initial send attempt, 2 paths
2532 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2533 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2534 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2535 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2536 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2539 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2540 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2541 let events = nodes[0].node.get_and_clear_pending_events();
2542 assert_eq!(events.len(), 1);
2544 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2545 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2546 short_channel_id: Some(expected_scid), .. } =>
2548 assert_eq!(payment_hash, ev_payment_hash);
2549 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2551 _ => panic!("Unexpected event"),
2553 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2554 assert_eq!(htlc_msgs.len(), 2);
2555 check_added_monitors!(nodes[0], 2);
2559 fn immediate_retry_on_failure() {
2560 // Tests that we can/will retry immediately after a failure
2561 let chanmon_cfgs = create_chanmon_cfgs(2);
2562 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2563 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2564 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2566 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2567 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2569 let amt_msat = 100_000_001;
2570 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2571 #[cfg(feature = "std")]
2572 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2573 #[cfg(not(feature = "std"))]
2574 let payment_expiry_secs = 60 * 60;
2575 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2576 invoice_features.set_variable_length_onion_required();
2577 invoice_features.set_payment_secret_required();
2578 invoice_features.set_basic_mpp_optional();
2579 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2580 .with_expiry_time(payment_expiry_secs as u64)
2581 .with_bolt11_features(invoice_features).unwrap();
2582 let route_params = RouteParameters {
2584 final_value_msat: amt_msat,
2587 let chans = nodes[0].node.list_usable_channels();
2588 let mut route = Route {
2590 Path { hops: vec![RouteHop {
2591 pubkey: nodes[1].node.get_our_node_id(),
2592 node_features: nodes[1].node.node_features(),
2593 short_channel_id: chans[0].short_channel_id.unwrap(),
2594 channel_features: nodes[1].node.channel_features(),
2595 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2596 cltv_expiry_delta: 100,
2597 }], blinded_tail: None },
2599 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2601 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2602 // On retry, split the payment across both channels.
2603 route.paths.push(route.paths[0].clone());
2604 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2605 route.paths[0].hops[0].fee_msat = 50_000_000;
2606 route.paths[1].hops[0].fee_msat = 50_000_001;
2607 let mut pay_params = route_params.payment_params.clone();
2608 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2609 nodes[0].router.expect_find_route(RouteParameters {
2610 payment_params: pay_params, final_value_msat: amt_msat,
2611 }, Ok(route.clone()));
2613 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2614 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2615 let events = nodes[0].node.get_and_clear_pending_events();
2616 assert_eq!(events.len(), 1);
2618 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2619 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2620 short_channel_id: Some(expected_scid), .. } =>
2622 assert_eq!(payment_hash, ev_payment_hash);
2623 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2625 _ => panic!("Unexpected event"),
2627 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2628 assert_eq!(htlc_msgs.len(), 2);
2629 check_added_monitors!(nodes[0], 2);
2633 fn no_extra_retries_on_back_to_back_fail() {
2634 // In a previous release, we had a race where we may exceed the payment retry count if we
2635 // get two failures in a row with the second indicating that all paths had failed (this field,
2636 // `all_paths_failed`, has since been removed).
2637 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2638 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2639 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2640 // pending which we will see later. Thus, when we previously removed the retry tracking map
2641 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2642 // retry entry even though more events for the same payment were still pending. This led to
2643 // us retrying a payment again even though we'd already given up on it.
2645 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2646 // is used to remove the payment retry counter entries instead. This tests for the specific
2647 // excess-retry case while also testing `PaymentFailed` generation.
2649 let chanmon_cfgs = create_chanmon_cfgs(3);
2650 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2651 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2652 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2654 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2655 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2657 let amt_msat = 200_000_000;
2658 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2659 #[cfg(feature = "std")]
2660 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2661 #[cfg(not(feature = "std"))]
2662 let payment_expiry_secs = 60 * 60;
2663 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2664 invoice_features.set_variable_length_onion_required();
2665 invoice_features.set_payment_secret_required();
2666 invoice_features.set_basic_mpp_optional();
2667 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2668 .with_expiry_time(payment_expiry_secs as u64)
2669 .with_bolt11_features(invoice_features).unwrap();
2670 let route_params = RouteParameters {
2672 final_value_msat: amt_msat,
2675 let mut route = Route {
2677 Path { hops: vec![RouteHop {
2678 pubkey: nodes[1].node.get_our_node_id(),
2679 node_features: nodes[1].node.node_features(),
2680 short_channel_id: chan_1_scid,
2681 channel_features: nodes[1].node.channel_features(),
2682 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2683 cltv_expiry_delta: 100,
2685 pubkey: nodes[2].node.get_our_node_id(),
2686 node_features: nodes[2].node.node_features(),
2687 short_channel_id: chan_2_scid,
2688 channel_features: nodes[2].node.channel_features(),
2689 fee_msat: 100_000_000,
2690 cltv_expiry_delta: 100,
2691 }], blinded_tail: None },
2692 Path { hops: vec![RouteHop {
2693 pubkey: nodes[1].node.get_our_node_id(),
2694 node_features: nodes[1].node.node_features(),
2695 short_channel_id: chan_1_scid,
2696 channel_features: nodes[1].node.channel_features(),
2697 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2698 cltv_expiry_delta: 100,
2700 pubkey: nodes[2].node.get_our_node_id(),
2701 node_features: nodes[2].node.node_features(),
2702 short_channel_id: chan_2_scid,
2703 channel_features: nodes[2].node.channel_features(),
2704 fee_msat: 100_000_000,
2705 cltv_expiry_delta: 100,
2706 }], blinded_tail: None }
2708 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2710 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2711 let mut second_payment_params = route_params.payment_params.clone();
2712 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2713 // On retry, we'll only return one path
2714 route.paths.remove(1);
2715 route.paths[0].hops[1].fee_msat = amt_msat;
2716 nodes[0].router.expect_find_route(RouteParameters {
2717 payment_params: second_payment_params,
2718 final_value_msat: amt_msat,
2719 }, Ok(route.clone()));
2721 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2722 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2723 let htlc_updates = SendEvent::from_node(&nodes[0]);
2724 check_added_monitors!(nodes[0], 1);
2725 assert_eq!(htlc_updates.msgs.len(), 1);
2727 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2728 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2729 check_added_monitors!(nodes[1], 1);
2730 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2732 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2733 check_added_monitors!(nodes[0], 1);
2734 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2736 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2737 check_added_monitors!(nodes[0], 1);
2738 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2740 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2741 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2742 check_added_monitors!(nodes[1], 1);
2743 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2745 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2746 check_added_monitors!(nodes[1], 1);
2747 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2749 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2750 check_added_monitors!(nodes[0], 1);
2752 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2753 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2754 check_added_monitors!(nodes[0], 1);
2755 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2757 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2758 check_added_monitors!(nodes[1], 1);
2759 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2761 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2762 check_added_monitors!(nodes[1], 1);
2763 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2765 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2766 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2767 check_added_monitors!(nodes[0], 1);
2769 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2770 check_added_monitors!(nodes[0], 1);
2771 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2773 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2774 check_added_monitors!(nodes[1], 1);
2775 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2776 check_added_monitors!(nodes[1], 1);
2777 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2779 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2780 check_added_monitors!(nodes[0], 1);
2782 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2783 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2786 // Previously, we retried payments in an event consumer, which would retry each
2787 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2788 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2789 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2790 // by adding the `PaymentFailed` event.
2792 // Because we now retry payments as a batch, we simply return a single-path route in the
2793 // second, batched, request, have that fail, ensure the payment was abandoned.
2794 let mut events = nodes[0].node.get_and_clear_pending_events();
2795 assert_eq!(events.len(), 3);
2797 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2798 assert_eq!(payment_hash, ev_payment_hash);
2799 assert_eq!(payment_failed_permanently, false);
2801 _ => panic!("Unexpected event"),
2804 Event::PendingHTLCsForwardable { .. } => {},
2805 _ => panic!("Unexpected event"),
2808 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2809 assert_eq!(payment_hash, ev_payment_hash);
2810 assert_eq!(payment_failed_permanently, false);
2812 _ => panic!("Unexpected event"),
2815 nodes[0].node.process_pending_htlc_forwards();
2816 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2817 check_added_monitors!(nodes[0], 1);
2819 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2820 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2821 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2822 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2823 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2825 let mut events = nodes[0].node.get_and_clear_pending_events();
2826 assert_eq!(events.len(), 2);
2828 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2829 assert_eq!(payment_hash, ev_payment_hash);
2830 assert_eq!(payment_failed_permanently, false);
2832 _ => panic!("Unexpected event"),
2835 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2836 assert_eq!(payment_hash, *ev_payment_hash);
2837 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2838 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2840 _ => panic!("Unexpected event"),
2845 fn test_simple_partial_retry() {
2846 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2847 // full amount of the payment, rather than only the missing amount. Here we simply test for
2848 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2849 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2851 let chanmon_cfgs = create_chanmon_cfgs(3);
2852 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2853 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2854 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2856 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2857 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2859 let amt_msat = 200_000_000;
2860 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2861 #[cfg(feature = "std")]
2862 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2863 #[cfg(not(feature = "std"))]
2864 let payment_expiry_secs = 60 * 60;
2865 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2866 invoice_features.set_variable_length_onion_required();
2867 invoice_features.set_payment_secret_required();
2868 invoice_features.set_basic_mpp_optional();
2869 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2870 .with_expiry_time(payment_expiry_secs as u64)
2871 .with_bolt11_features(invoice_features).unwrap();
2872 let route_params = RouteParameters {
2874 final_value_msat: amt_msat,
2877 let mut route = Route {
2879 Path { hops: vec![RouteHop {
2880 pubkey: nodes[1].node.get_our_node_id(),
2881 node_features: nodes[1].node.node_features(),
2882 short_channel_id: chan_1_scid,
2883 channel_features: nodes[1].node.channel_features(),
2884 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2885 cltv_expiry_delta: 100,
2887 pubkey: nodes[2].node.get_our_node_id(),
2888 node_features: nodes[2].node.node_features(),
2889 short_channel_id: chan_2_scid,
2890 channel_features: nodes[2].node.channel_features(),
2891 fee_msat: 100_000_000,
2892 cltv_expiry_delta: 100,
2893 }], blinded_tail: None },
2894 Path { hops: vec![RouteHop {
2895 pubkey: nodes[1].node.get_our_node_id(),
2896 node_features: nodes[1].node.node_features(),
2897 short_channel_id: chan_1_scid,
2898 channel_features: nodes[1].node.channel_features(),
2900 cltv_expiry_delta: 100,
2902 pubkey: nodes[2].node.get_our_node_id(),
2903 node_features: nodes[2].node.node_features(),
2904 short_channel_id: chan_2_scid,
2905 channel_features: nodes[2].node.channel_features(),
2906 fee_msat: 100_000_000,
2907 cltv_expiry_delta: 100,
2908 }], blinded_tail: None }
2910 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2912 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2913 let mut second_payment_params = route_params.payment_params.clone();
2914 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2915 // On retry, we'll only be asked for one path (or 100k sats)
2916 route.paths.remove(0);
2917 nodes[0].router.expect_find_route(RouteParameters {
2918 payment_params: second_payment_params,
2919 final_value_msat: amt_msat / 2,
2920 }, Ok(route.clone()));
2922 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2923 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2924 let htlc_updates = SendEvent::from_node(&nodes[0]);
2925 check_added_monitors!(nodes[0], 1);
2926 assert_eq!(htlc_updates.msgs.len(), 1);
2928 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2929 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2930 check_added_monitors!(nodes[1], 1);
2931 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2933 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2934 check_added_monitors!(nodes[0], 1);
2935 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2937 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2938 check_added_monitors!(nodes[0], 1);
2939 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2942 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2943 check_added_monitors!(nodes[1], 1);
2944 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2946 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2947 check_added_monitors!(nodes[1], 1);
2948 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2950 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2951 check_added_monitors!(nodes[0], 1);
2953 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2954 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2955 check_added_monitors!(nodes[0], 1);
2956 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2958 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2959 check_added_monitors!(nodes[1], 1);
2961 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2962 check_added_monitors!(nodes[1], 1);
2964 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2966 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2967 check_added_monitors!(nodes[0], 1);
2969 let mut events = nodes[0].node.get_and_clear_pending_events();
2970 assert_eq!(events.len(), 2);
2972 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2973 assert_eq!(payment_hash, ev_payment_hash);
2974 assert_eq!(payment_failed_permanently, false);
2976 _ => panic!("Unexpected event"),
2979 Event::PendingHTLCsForwardable { .. } => {},
2980 _ => panic!("Unexpected event"),
2983 nodes[0].node.process_pending_htlc_forwards();
2984 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2985 check_added_monitors!(nodes[0], 1);
2987 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2988 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2990 expect_pending_htlcs_forwardable!(nodes[1]);
2991 check_added_monitors!(nodes[1], 1);
2993 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2994 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2995 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2996 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2998 expect_pending_htlcs_forwardable!(nodes[2]);
2999 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
3003 #[cfg(feature = "std")]
3004 fn test_threaded_payment_retries() {
3005 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
3006 // a single thread and would happily let multiple threads run retries at the same time. Because
3007 // retries are done by first calculating the amount we need to retry, then dropping the
3008 // relevant lock, then actually sending, we would happily let multiple threads retry the same
3009 // amount at the same time, overpaying our original HTLC!
3010 let chanmon_cfgs = create_chanmon_cfgs(4);
3011 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3012 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3013 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3015 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
3016 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
3017 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
3018 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
3020 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3021 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
3022 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
3023 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
3025 let amt_msat = 100_000_000;
3026 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3027 #[cfg(feature = "std")]
3028 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3029 #[cfg(not(feature = "std"))]
3030 let payment_expiry_secs = 60 * 60;
3031 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3032 invoice_features.set_variable_length_onion_required();
3033 invoice_features.set_payment_secret_required();
3034 invoice_features.set_basic_mpp_optional();
3035 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3036 .with_expiry_time(payment_expiry_secs as u64)
3037 .with_bolt11_features(invoice_features).unwrap();
3038 let mut route_params = RouteParameters {
3040 final_value_msat: amt_msat,
3043 let mut route = Route {
3045 Path { hops: vec![RouteHop {
3046 pubkey: nodes[1].node.get_our_node_id(),
3047 node_features: nodes[1].node.node_features(),
3048 short_channel_id: chan_1_scid,
3049 channel_features: nodes[1].node.channel_features(),
3051 cltv_expiry_delta: 100,
3053 pubkey: nodes[3].node.get_our_node_id(),
3054 node_features: nodes[2].node.node_features(),
3055 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3056 channel_features: nodes[2].node.channel_features(),
3057 fee_msat: amt_msat / 1000,
3058 cltv_expiry_delta: 100,
3059 }], blinded_tail: None },
3060 Path { hops: vec![RouteHop {
3061 pubkey: nodes[2].node.get_our_node_id(),
3062 node_features: nodes[2].node.node_features(),
3063 short_channel_id: chan_3_scid,
3064 channel_features: nodes[2].node.channel_features(),
3066 cltv_expiry_delta: 100,
3068 pubkey: nodes[3].node.get_our_node_id(),
3069 node_features: nodes[3].node.node_features(),
3070 short_channel_id: chan_4_scid,
3071 channel_features: nodes[3].node.channel_features(),
3072 fee_msat: amt_msat - amt_msat / 1000,
3073 cltv_expiry_delta: 100,
3074 }], blinded_tail: None }
3076 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
3078 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3080 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3081 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3082 check_added_monitors!(nodes[0], 2);
3083 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3084 assert_eq!(send_msg_events.len(), 2);
3085 send_msg_events.retain(|msg|
3086 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3087 // Drop the commitment update for nodes[2], we can just let that one sit pending
3089 *node_id == nodes[1].node.get_our_node_id()
3090 } else { panic!(); }
3093 // from here on out, the retry `RouteParameters` amount will be amt/1000
3094 route_params.final_value_msat /= 1000;
3097 let end_time = Instant::now() + Duration::from_secs(1);
3098 macro_rules! thread_body { () => { {
3099 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3100 let node_ref = NodePtr::from_node(&nodes[0]);
3102 let node_a = unsafe { &*node_ref.0 };
3103 while Instant::now() < end_time {
3104 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3105 // Ignore if we have any pending events, just always pretend we just got a
3106 // PendingHTLCsForwardable
3107 node_a.node.process_pending_htlc_forwards();
3111 let mut threads = Vec::new();
3112 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3114 // Back in the main thread, poll pending messages and make sure that we never have more than
3115 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3116 // there are HTLC messages shoved in while its running. This allows us to test that we never
3117 // generate an additional update_add_htlc until we've fully failed the first.
3118 let mut previously_failed_channels = Vec::new();
3120 assert_eq!(send_msg_events.len(), 1);
3121 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3122 assert_eq!(send_event.msgs.len(), 1);
3124 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3125 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3127 // Note that we only push one route into `expect_find_route` at a time, because that's all
3128 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3129 // we should still ultimately fail for the same reason - because we're trying to send too
3130 // many HTLCs at once.
3131 let mut new_route_params = route_params.clone();
3132 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3133 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3134 route.paths[0].hops[1].short_channel_id += 1;
3135 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3137 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3138 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3139 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3140 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3141 // This races with our other threads which may generate an add-HTLCs commitment update via
3142 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3143 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3144 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3145 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3147 let cur_time = Instant::now();
3148 if cur_time > end_time {
3149 for thread in threads.drain(..) { thread.join().unwrap(); }
3152 // Make sure we have some events to handle when we go around...
3153 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3154 nodes[0].node.process_pending_htlc_forwards();
3155 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3156 check_added_monitors!(nodes[0], 2);
3158 if cur_time > end_time {
3164 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
3165 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3166 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3167 // it was last persisted.
3168 let chanmon_cfgs = create_chanmon_cfgs(2);
3169 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3170 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3171 let (persister_a, persister_b, persister_c);
3172 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3173 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3174 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3176 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3178 let mut nodes_0_serialized = Vec::new();
3179 if !persist_manager_with_payment {
3180 nodes_0_serialized = nodes[0].node.encode();
3183 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3185 if persist_manager_with_payment {
3186 nodes_0_serialized = nodes[0].node.encode();
3189 nodes[1].node.claim_funds(our_payment_preimage);
3190 check_added_monitors!(nodes[1], 1);
3191 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3193 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3194 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3195 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3196 check_added_monitors!(nodes[0], 1);
3198 // The ChannelMonitor should always be the latest version, as we're required to persist it
3199 // during the commitment signed handling.
3200 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3201 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3203 let events = nodes[0].node.get_and_clear_pending_events();
3204 assert_eq!(events.len(), 2);
3205 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3206 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3207 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3208 // the double-claim that would otherwise appear at the end of this test.
3209 nodes[0].node.timer_tick_occurred();
3210 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3211 assert_eq!(as_broadcasted_txn.len(), 1);
3213 // Ensure that, even after some time, if we restart we still include *something* in the current
3214 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3215 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3216 // A naive implementation of the fix here would wipe the pending payments set, causing a
3217 // failure event when we restart.
3218 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3220 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3221 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);
3222 let events = nodes[0].node.get_and_clear_pending_events();
3223 assert!(events.is_empty());
3225 // Ensure that we don't generate any further events even after the channel-closing commitment
3226 // transaction is confirmed on-chain.
3227 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3228 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3230 let events = nodes[0].node.get_and_clear_pending_events();
3231 assert!(events.is_empty());
3233 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3234 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);
3235 let events = nodes[0].node.get_and_clear_pending_events();
3236 assert!(events.is_empty());
3237 check_added_monitors(&nodes[0], 1);
3241 fn no_missing_sent_on_midpoint_reload() {
3242 do_no_missing_sent_on_midpoint_reload(false);
3243 do_no_missing_sent_on_midpoint_reload(true);
3246 fn do_claim_from_closed_chan(fail_payment: bool) {
3247 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3248 // received had been closed between when the HTLC was received and when we went to claim it.
3249 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3250 // presumably the sender may retry later. Long ago it also reduced total code in the claim
3253 // However, this doesn't make sense if you're trying to do an atomic swap or some other
3254 // protocol that requires atomicity with some other action - if your money got claimed
3255 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3256 // is an over-optimization - there should be a very, very low likelihood that a channel closes
3257 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3258 // Since we now have code to handle this anyway we should allow it.
3260 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3261 // CLTVs on the paths to different value resulting in a different claim deadline.
3262 let chanmon_cfgs = create_chanmon_cfgs(4);
3263 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3264 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3265 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3267 create_announced_chan_between_nodes(&nodes, 0, 1);
3268 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3269 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3270 create_announced_chan_between_nodes(&nodes, 2, 3);
3272 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3273 let mut route_params = RouteParameters {
3274 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3275 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
3276 final_value_msat: 10_000_000,
3278 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3279 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3280 // Make sure the route is ordered as the B->D path before C->D
3281 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3282 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3284 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3285 // the HTLC is being relayed.
3286 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3287 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3288 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3290 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3291 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3292 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3293 check_added_monitors(&nodes[0], 2);
3294 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3295 send_msgs.sort_by(|a, _| {
3297 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3298 let node_b_id = nodes[1].node.get_our_node_id();
3299 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3302 assert_eq!(send_msgs.len(), 2);
3303 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3304 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3305 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3306 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3308 match receive_event.unwrap() {
3309 Event::PaymentClaimable { claim_deadline, .. } => {
3310 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3315 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3317 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3318 - if fail_payment { 0 } else { 2 });
3320 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3321 // and expire both immediately, though, by connecting another 4 blocks.
3322 let reason = HTLCDestination::FailedPayment { payment_hash };
3323 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3324 connect_blocks(&nodes[3], 4);
3325 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3326 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3328 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3329 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false);
3330 check_closed_broadcast(&nodes[1], 1, true);
3331 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3332 assert_eq!(bs_tx.len(), 1);
3334 mine_transaction(&nodes[3], &bs_tx[0]);
3335 check_added_monitors(&nodes[3], 1);
3336 check_closed_broadcast(&nodes[3], 1, true);
3337 check_closed_event(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false);
3339 nodes[3].node.claim_funds(payment_preimage);
3340 check_added_monitors(&nodes[3], 2);
3341 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3343 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3344 assert_eq!(ds_tx.len(), 1);
3345 check_spends!(&ds_tx[0], &bs_tx[0]);
3347 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3348 check_added_monitors(&nodes[1], 1);
3349 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3351 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3352 check_added_monitors(&nodes[1], 1);
3353 assert_eq!(bs_claims.len(), 1);
3354 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3355 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3356 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3357 } else { panic!(); }
3359 expect_payment_sent!(nodes[0], payment_preimage);
3361 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3362 assert_eq!(ds_claim_msgs.len(), 1);
3363 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3364 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3365 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3366 check_added_monitors(&nodes[2], 1);
3367 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3368 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3370 } else { panic!(); };
3372 assert_eq!(cs_claim_msgs.len(), 1);
3373 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3374 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3375 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3376 } else { panic!(); }
3378 expect_payment_path_successful!(nodes[0]);
3383 fn claim_from_closed_chan() {
3384 do_claim_from_closed_chan(true);
3385 do_claim_from_closed_chan(false);
3388 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3389 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3390 // another results in the HTLC being rejected.
3392 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3393 // first of which we'll deliver and the second of which we'll fail and then re-send with
3394 // modified payment metadata, which will in turn result in it being failed by the recipient.
3395 let chanmon_cfgs = create_chanmon_cfgs(4);
3396 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3397 let mut config = test_default_channel_config();
3398 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3399 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3402 let new_chain_monitor;
3403 let nodes_0_deserialized;
3405 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3407 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3408 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3409 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3410 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3412 // Pay more than half of each channel's max, requiring MPP
3413 let amt_msat = 750_000_000;
3414 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3415 let payment_id = PaymentId(payment_hash.0);
3416 let payment_metadata = vec![44, 49, 52, 142];
3418 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3419 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3420 let mut route_params = RouteParameters {
3422 final_value_msat: amt_msat,
3425 // Send the MPP payment, delivering the updated commitment state to nodes[1].
3426 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3427 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata),
3428 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3429 check_added_monitors!(nodes[0], 2);
3431 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3432 assert_eq!(send_events.len(), 2);
3433 let first_send = SendEvent::from_event(send_events.pop().unwrap());
3434 let second_send = SendEvent::from_event(send_events.pop().unwrap());
3436 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3437 (&first_send, &second_send)
3439 (&second_send, &first_send)
3441 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3442 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3444 expect_pending_htlcs_forwardable!(nodes[1]);
3445 check_added_monitors(&nodes[1], 1);
3446 let b_forward_ev = SendEvent::from_node(&nodes[1]);
3447 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3448 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3450 expect_pending_htlcs_forwardable!(nodes[3]);
3452 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3453 // will result in nodes[2] failing the HTLC back.
3454 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3455 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3457 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3458 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3460 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3461 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3462 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3464 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3465 assert_eq!(payment_fail_retryable_evs.len(), 2);
3466 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3467 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3469 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3470 // stored for our payment.
3472 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3475 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3476 // the payment state.
3478 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3479 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3480 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3481 persister, new_chain_monitor, nodes_0_deserialized);
3482 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3483 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
3485 let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
3486 reconnect_args.send_channel_ready = (true, true);
3487 reconnect_nodes(reconnect_args);
3489 // Create a new channel between C and D as A will refuse to retry on the existing one because
3491 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3493 // Now retry the failed HTLC.
3494 nodes[0].node.process_pending_htlc_forwards();
3495 check_added_monitors(&nodes[0], 1);
3496 let as_resend = SendEvent::from_node(&nodes[0]);
3497 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3498 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3500 expect_pending_htlcs_forwardable!(nodes[2]);
3501 check_added_monitors(&nodes[2], 1);
3502 let cs_forward = SendEvent::from_node(&nodes[2]);
3503 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3504 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3506 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3507 // the payment metadata was modified, failing only the one modified HTLC and retaining the
3510 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3511 nodes[3].node.process_pending_htlc_forwards();
3512 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3513 &[HTLCDestination::FailedPayment {payment_hash}]);
3514 nodes[3].node.process_pending_htlc_forwards();
3516 check_added_monitors(&nodes[3], 1);
3517 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3519 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3520 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3521 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3522 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3524 expect_pending_htlcs_forwardable!(nodes[3]);
3525 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3526 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3531 fn test_payment_metadata_consistency() {
3532 do_test_payment_metadata_consistency(true, true);
3533 do_test_payment_metadata_consistency(true, false);
3534 do_test_payment_metadata_consistency(false, true);
3535 do_test_payment_metadata_consistency(false, false);