1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test the payment retry logic in ChannelManager, including various edge-cases around
11 //! serialization ordering between ChannelManager/ChannelMonitors and ensuring we can still retry
12 //! payments thereafter.
14 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
15 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::sign::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason, PaymentPurpose};
19 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
20 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, RecentPaymentDetails, RecipientOnionFields, HTLCForwardInfo, PendingHTLCRouting, PendingAddHTLCInfo};
21 use crate::ln::features::Bolt11InvoiceFeatures;
22 use crate::ln::{msgs, ChannelId, PaymentSecret, PaymentPreimage};
23 use crate::ln::msgs::ChannelMessageHandler;
24 use crate::ln::outbound_payment::{IDEMPOTENCY_TIMEOUT_TICKS, 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::config::UserConfig;
29 use crate::util::test_utils;
30 use crate::util::errors::APIError;
31 use crate::util::ser::Writeable;
32 use crate::util::string::UntrustedString;
34 use bitcoin::network::constants::Network;
36 use crate::prelude::*;
38 use crate::ln::functional_test_utils::*;
39 use crate::routing::gossip::NodeId;
40 #[cfg(feature = "std")]
42 crate::util::time::tests::SinceEpoch,
43 std::time::{SystemTime, Instant, Duration}
48 let chanmon_cfgs = create_chanmon_cfgs(4);
49 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
50 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
51 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
53 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
54 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
55 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
56 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
58 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
59 let path = route.paths[0].clone();
60 route.paths.push(path);
61 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
62 route.paths[0].hops[0].short_channel_id = chan_1_id;
63 route.paths[0].hops[1].short_channel_id = chan_3_id;
64 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
65 route.paths[1].hops[0].short_channel_id = chan_2_id;
66 route.paths[1].hops[1].short_channel_id = chan_4_id;
67 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
68 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
73 let chanmon_cfgs = create_chanmon_cfgs(4);
74 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
75 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
76 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
78 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
79 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
80 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
81 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
83 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
85 let amt_msat = 1_000_000;
86 let max_total_routing_fee_msat = 50_000;
87 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
88 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
89 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(
90 nodes[0], nodes[3], payment_params, amt_msat, Some(max_total_routing_fee_msat));
91 let path = route.paths[0].clone();
92 route.paths.push(path);
93 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
94 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
95 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
96 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
97 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
98 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
100 // Initiate the MPP payment.
101 let payment_id = PaymentId(payment_hash.0);
102 let mut route_params = route.route_params.clone().unwrap();
104 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
105 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
106 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
107 check_added_monitors!(nodes[0], 2); // one monitor per path
108 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
109 assert_eq!(events.len(), 2);
111 // Pass half of the payment along the success path.
112 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
113 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
115 // Add the HTLC along the first hop.
116 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
117 let (update_add, commitment_signed) = match fail_path_msgs_1 {
118 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 } } => {
119 assert_eq!(update_add_htlcs.len(), 1);
120 assert!(update_fail_htlcs.is_empty());
121 assert!(update_fulfill_htlcs.is_empty());
122 assert!(update_fail_malformed_htlcs.is_empty());
123 assert!(update_fee.is_none());
124 (update_add_htlcs[0].clone(), commitment_signed.clone())
126 _ => panic!("Unexpected event"),
128 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
129 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
131 // Attempt to forward the payment and complete the 2nd path's failure.
132 expect_pending_htlcs_forwardable!(&nodes[2]);
133 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 }]);
134 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
135 assert!(htlc_updates.update_add_htlcs.is_empty());
136 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
137 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
138 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
139 check_added_monitors!(nodes[2], 1);
140 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
141 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
142 let mut events = nodes[0].node.get_and_clear_pending_events();
144 Event::PendingHTLCsForwardable { .. } => {},
145 _ => panic!("Unexpected event")
148 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
150 // Rebalance the channel so the second half of the payment can succeed.
151 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
153 // Retry the second half of the payment and make sure it succeeds.
154 route.paths.remove(0);
155 route_params.final_value_msat = 1_000_000;
156 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
157 // Check the remaining max total routing fee for the second attempt is 50_000 - 1_000 msat fee
158 // used by the first path
159 route_params.max_total_routing_fee_msat = Some(max_total_routing_fee_msat - 1_000);
160 nodes[0].router.expect_find_route(route_params, Ok(route));
161 nodes[0].node.process_pending_htlc_forwards();
162 check_added_monitors!(nodes[0], 1);
163 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
164 assert_eq!(events.len(), 1);
165 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
166 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
170 fn mpp_retry_overpay() {
171 // We create an MPP scenario with two paths in which we need to overpay to reach
172 // htlc_minimum_msat. We then fail the overpaid path and check that on retry our
173 // max_total_routing_fee_msat only accounts for the path's fees, but not for the fees overpaid
174 // in the first attempt.
175 let chanmon_cfgs = create_chanmon_cfgs(4);
176 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
177 let mut user_config = test_default_channel_config();
178 user_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
179 let mut limited_config_1 = user_config.clone();
180 limited_config_1.channel_handshake_config.our_htlc_minimum_msat = 35_000_000;
181 let mut limited_config_2 = user_config.clone();
182 limited_config_2.channel_handshake_config.our_htlc_minimum_msat = 34_500_000;
183 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
184 &[Some(user_config), Some(limited_config_1), Some(limited_config_2), Some(user_config)]);
185 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
187 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 40_000, 0);
188 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 40_000, 0);
189 let (_chan_3_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 40_000, 0);
190 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes_with_value(&nodes, 3, 2, 40_000, 0);
192 let amt_msat = 70_000_000;
193 let max_total_routing_fee_msat = Some(1_000_000);
195 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
196 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
197 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(
198 nodes[0], nodes[3], payment_params, amt_msat, max_total_routing_fee_msat);
200 // Check we overpay on the second path which we're about to fail.
201 assert_eq!(chan_1_update.contents.fee_proportional_millionths, 0);
202 let overpaid_amount_1 = route.paths[0].fee_msat() as u32 - chan_1_update.contents.fee_base_msat;
203 assert_eq!(overpaid_amount_1, 0);
205 assert_eq!(chan_2_update.contents.fee_proportional_millionths, 0);
206 let overpaid_amount_2 = route.paths[1].fee_msat() as u32 - chan_2_update.contents.fee_base_msat;
208 let total_overpaid_amount = overpaid_amount_1 + overpaid_amount_2;
210 // Initiate the payment.
211 let payment_id = PaymentId(payment_hash.0);
212 let mut route_params = route.route_params.clone().unwrap();
214 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
215 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
216 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
217 check_added_monitors!(nodes[0], 2); // one monitor per path
218 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
219 assert_eq!(events.len(), 2);
221 // Pass half of the payment along the success path.
222 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
223 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, payment_hash,
224 Some(payment_secret), success_path_msgs, false, None);
226 // Add the HTLC along the first hop.
227 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
228 let (update_add, commitment_signed) = match fail_path_msgs_1 {
229 MessageSendEvent::UpdateHTLCs {
231 updates: msgs::CommitmentUpdate {
232 ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs,
233 ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed
236 assert_eq!(update_add_htlcs.len(), 1);
237 assert!(update_fail_htlcs.is_empty());
238 assert!(update_fulfill_htlcs.is_empty());
239 assert!(update_fail_malformed_htlcs.is_empty());
240 assert!(update_fee.is_none());
241 (update_add_htlcs[0].clone(), commitment_signed.clone())
243 _ => panic!("Unexpected event"),
245 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
246 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
248 // Attempt to forward the payment and complete the 2nd path's failure.
249 expect_pending_htlcs_forwardable!(&nodes[2]);
250 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[2],
251 vec![HTLCDestination::NextHopChannel {
252 node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_4_id
255 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
256 assert!(htlc_updates.update_add_htlcs.is_empty());
257 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
258 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
259 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
260 check_added_monitors!(nodes[2], 1);
261 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(),
262 &htlc_updates.update_fail_htlcs[0]);
263 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
264 let mut events = nodes[0].node.get_and_clear_pending_events();
266 Event::PendingHTLCsForwardable { .. } => {},
267 _ => panic!("Unexpected event")
270 expect_payment_failed_conditions_event(events, payment_hash, false,
271 PaymentFailedConditions::new().mpp_parts_remain());
273 // Rebalance the channel so the second half of the payment can succeed.
274 send_payment(&nodes[3], &vec!(&nodes[2])[..], 38_000_000);
276 // Retry the second half of the payment and make sure it succeeds.
277 let first_path_value = route.paths[0].final_value_msat();
278 assert_eq!(first_path_value, 36_000_000);
280 route.paths.remove(0);
281 route_params.final_value_msat -= first_path_value;
282 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
284 // Check the remaining max total routing fee for the second attempt accounts only for 1_000 msat
285 // base fee, but not for overpaid value of the first try.
286 route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 1000);
287 nodes[0].router.expect_find_route(route_params, Ok(route));
288 nodes[0].node.process_pending_htlc_forwards();
290 check_added_monitors!(nodes[0], 1);
291 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
292 assert_eq!(events.len(), 1);
293 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], amt_msat, payment_hash,
294 Some(payment_secret), events.pop().unwrap(), true, None);
296 // Can't use claim_payment_along_route as it doesn't support overpayment, so we break out the
297 // individual steps here.
298 let extra_fees = vec![0, total_overpaid_amount];
299 let expected_total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
300 &nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], &extra_fees[..], false,
302 expect_payment_sent!(&nodes[0], payment_preimage, Some(expected_total_fee_msat));
305 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
306 let chanmon_cfgs = create_chanmon_cfgs(4);
307 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
308 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
309 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
311 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
312 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
313 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
314 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
316 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
317 let path = route.paths[0].clone();
318 route.paths.push(path);
319 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
320 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
321 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
322 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
323 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
324 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
326 // Initiate the MPP payment.
327 nodes[0].node.send_payment_with_route(&route, payment_hash,
328 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
329 check_added_monitors!(nodes[0], 2); // one monitor per path
330 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
331 assert_eq!(events.len(), 2);
333 // Pass half of the payment along the first path.
334 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
335 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
337 if send_partial_mpp {
338 // Time out the partial MPP
339 for _ in 0..MPP_TIMEOUT_TICKS {
340 nodes[3].node.timer_tick_occurred();
343 // Failed HTLC from node 3 -> 1
344 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
345 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
346 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
347 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
348 check_added_monitors!(nodes[3], 1);
349 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
351 // Failed HTLC from node 1 -> 0
352 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 }]);
353 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
354 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
355 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
356 check_added_monitors!(nodes[1], 1);
357 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
359 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
361 // Pass half of the payment along the second path.
362 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
363 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
365 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
366 for _ in 0..MPP_TIMEOUT_TICKS {
367 nodes[3].node.timer_tick_occurred();
370 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
375 fn mpp_receive_timeout() {
376 do_mpp_receive_timeout(true);
377 do_mpp_receive_timeout(false);
381 fn test_keysend_payments() {
382 do_test_keysend_payments(false, false);
383 do_test_keysend_payments(false, true);
384 do_test_keysend_payments(true, false);
385 do_test_keysend_payments(true, true);
388 fn do_test_keysend_payments(public_node: bool, with_retry: bool) {
389 let chanmon_cfgs = create_chanmon_cfgs(2);
390 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
391 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
392 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
395 create_announced_chan_between_nodes(&nodes, 0, 1);
397 create_chan_between_nodes(&nodes[0], &nodes[1]);
399 let payer_pubkey = nodes[0].node.get_our_node_id();
400 let payee_pubkey = nodes[1].node.get_our_node_id();
401 let route_params = RouteParameters::from_payment_params_and_value(
402 PaymentParameters::for_keysend(payee_pubkey, 40, false), 10000);
404 let network_graph = nodes[0].network_graph.clone();
405 let channels = nodes[0].node.list_usable_channels();
406 let first_hops = channels.iter().collect::<Vec<_>>();
407 let first_hops = if public_node { None } else { Some(first_hops.as_slice()) };
409 let scorer = test_utils::TestScorer::new();
410 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
411 let route = find_route(
412 &payer_pubkey, &route_params, &network_graph, first_hops,
413 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
417 let test_preimage = PaymentPreimage([42; 32]);
419 nodes[0].node.send_spontaneous_payment_with_retry(Some(test_preimage),
420 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0),
421 route_params, Retry::Attempts(1)).unwrap()
423 nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
424 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap()
427 check_added_monitors!(nodes[0], 1);
428 let send_event = SendEvent::from_node(&nodes[0]);
429 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
430 do_commitment_signed_dance(&nodes[1], &nodes[0], &send_event.commitment_msg, false, false);
431 expect_pending_htlcs_forwardable!(nodes[1]);
432 // Previously, a refactor caused us to stop including the payment preimage in the onion which
433 // is sent as a part of keysend payments. Thus, to be extra careful here, we scope the preimage
434 // above to demonstrate that we have no way to get the preimage at this point except by
435 // extracting it from the onion nodes[1] received.
436 let event = nodes[1].node.get_and_clear_pending_events();
437 assert_eq!(event.len(), 1);
438 if let Event::PaymentClaimable { purpose: PaymentPurpose::SpontaneousPayment(preimage), .. } = event[0] {
439 claim_payment(&nodes[0], &[&nodes[1]], preimage);
444 fn test_mpp_keysend() {
445 let mut mpp_keysend_config = test_default_channel_config();
446 mpp_keysend_config.accept_mpp_keysend = true;
447 let chanmon_cfgs = create_chanmon_cfgs(4);
448 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
449 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
450 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
452 create_announced_chan_between_nodes(&nodes, 0, 1);
453 create_announced_chan_between_nodes(&nodes, 0, 2);
454 create_announced_chan_between_nodes(&nodes, 1, 3);
455 create_announced_chan_between_nodes(&nodes, 2, 3);
456 let network_graph = nodes[0].network_graph.clone();
458 let payer_pubkey = nodes[0].node.get_our_node_id();
459 let payee_pubkey = nodes[3].node.get_our_node_id();
460 let recv_value = 15_000_000;
461 let route_params = RouteParameters::from_payment_params_and_value(
462 PaymentParameters::for_keysend(payee_pubkey, 40, true), recv_value);
463 let scorer = test_utils::TestScorer::new();
464 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
465 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger,
466 &scorer, &Default::default(), &random_seed_bytes).unwrap();
468 let payment_preimage = PaymentPreimage([42; 32]);
469 let payment_secret = PaymentSecret(payment_preimage.0);
470 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
471 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_preimage.0)).unwrap();
472 check_added_monitors!(nodes[0], 2);
474 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
475 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
476 assert_eq!(events.len(), 2);
478 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
479 pass_along_path(&nodes[0], expected_route[0], recv_value, payment_hash.clone(),
480 Some(payment_secret), ev.clone(), false, Some(payment_preimage));
482 let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
483 pass_along_path(&nodes[0], expected_route[1], recv_value, payment_hash.clone(),
484 Some(payment_secret), ev.clone(), true, Some(payment_preimage));
485 claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
489 fn test_reject_mpp_keysend_htlc() {
490 // This test enforces that we reject MPP keysend HTLCs if our config states we don't support
491 // MPP keysend. When receiving a payment, if we don't support MPP keysend we'll reject the
492 // payment if it's keysend and has a payment secret, never reaching our payment validation
493 // logic. To check that we enforce rejecting MPP keysends in our payment logic, here we send
494 // keysend payments without payment secrets, then modify them by adding payment secrets in the
495 // final node in between receiving the HTLCs and actually processing them.
496 let mut reject_mpp_keysend_cfg = test_default_channel_config();
497 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
499 let chanmon_cfgs = create_chanmon_cfgs(4);
500 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
501 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(reject_mpp_keysend_cfg)]);
502 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
503 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
504 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
505 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
506 let (update_a, _, chan_4_channel_id, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
507 let chan_4_id = update_a.contents.short_channel_id;
509 let (mut route, payment_hash, payment_preimage, _) = get_route_and_payment_hash!(nodes[0], nodes[3], amount);
511 // Pay along nodes[1]
512 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
513 route.paths[0].hops[0].short_channel_id = chan_1_id;
514 route.paths[0].hops[1].short_channel_id = chan_3_id;
516 let payment_id_0 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
517 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_0).unwrap();
518 check_added_monitors!(nodes[0], 1);
520 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
521 let update_add_0 = update_0.update_add_htlcs[0].clone();
522 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
523 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
524 expect_pending_htlcs_forwardable!(nodes[1]);
526 check_added_monitors!(&nodes[1], 1);
527 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[3].node.get_our_node_id());
528 let update_add_1 = update_1.update_add_htlcs[0].clone();
529 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
530 commitment_signed_dance!(nodes[3], nodes[1], update_1.commitment_signed, false, true);
532 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
533 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
534 for f in pending_forwards.iter_mut() {
536 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
537 match forward_info.routing {
538 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
539 *payment_data = Some(msgs::FinalOnionHopData {
540 payment_secret: PaymentSecret([42; 32]),
541 total_msat: amount * 2,
544 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
551 expect_pending_htlcs_forwardable!(nodes[3]);
553 // Pay along nodes[2]
554 route.paths[0].hops[0].pubkey = nodes[2].node.get_our_node_id();
555 route.paths[0].hops[0].short_channel_id = chan_2_id;
556 route.paths[0].hops[1].short_channel_id = chan_4_id;
558 let payment_id_1 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
559 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
560 check_added_monitors!(nodes[0], 1);
562 let update_2 = get_htlc_update_msgs!(nodes[0], nodes[2].node.get_our_node_id());
563 let update_add_2 = update_2.update_add_htlcs[0].clone();
564 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_2);
565 commitment_signed_dance!(nodes[2], nodes[0], &update_2.commitment_signed, false, true);
566 expect_pending_htlcs_forwardable!(nodes[2]);
568 check_added_monitors!(&nodes[2], 1);
569 let update_3 = get_htlc_update_msgs!(nodes[2], nodes[3].node.get_our_node_id());
570 let update_add_3 = update_3.update_add_htlcs[0].clone();
571 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &update_add_3);
572 commitment_signed_dance!(nodes[3], nodes[2], update_3.commitment_signed, false, true);
574 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
575 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
576 for f in pending_forwards.iter_mut() {
578 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
579 match forward_info.routing {
580 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
581 *payment_data = Some(msgs::FinalOnionHopData {
582 payment_secret: PaymentSecret([42; 32]),
583 total_msat: amount * 2,
586 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
593 expect_pending_htlcs_forwardable!(nodes[3]);
594 check_added_monitors!(nodes[3], 1);
596 // Fail back along nodes[2]
597 let update_fail_0 = get_htlc_update_msgs!(&nodes[3], &nodes[2].node.get_our_node_id());
598 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &update_fail_0.update_fail_htlcs[0]);
599 commitment_signed_dance!(nodes[2], nodes[3], update_fail_0.commitment_signed, false);
600 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 }]);
601 check_added_monitors!(nodes[2], 1);
603 let update_fail_1 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
604 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_1.update_fail_htlcs[0]);
605 commitment_signed_dance!(nodes[0], nodes[2], update_fail_1.commitment_signed, false);
607 expect_payment_failed_conditions(&nodes[0], payment_hash, true, PaymentFailedConditions::new());
608 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
613 fn no_pending_leak_on_initial_send_failure() {
614 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
615 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
616 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
617 // pending payment forever and never time it out.
618 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
619 // try, and then check that no pending payment is being tracked.
620 let chanmon_cfgs = create_chanmon_cfgs(2);
621 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
622 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
623 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
625 create_announced_chan_between_nodes(&nodes, 0, 1);
627 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
629 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
630 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
632 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
633 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
634 ), true, APIError::ChannelUnavailable { ref err },
635 assert_eq!(err, "Peer for first hop currently disconnected"));
637 assert!(!nodes[0].node.has_pending_payments());
640 fn do_retry_with_no_persist(confirm_before_reload: bool) {
641 // If we send a pending payment and `send_payment` returns success, we should always either
642 // return a payment failure event or a payment success event, and on failure the payment should
645 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
646 // always persisted asynchronously), the ChannelManager has to reload some payment data from
647 // ChannelMonitor(s) in some cases. This tests that reloading.
649 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
650 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
651 // which has separate codepaths for "commitment transaction already confirmed" and not.
652 let chanmon_cfgs = create_chanmon_cfgs(3);
653 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
655 let new_chain_monitor;
656 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
657 let nodes_0_deserialized;
658 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
660 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
661 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
663 // Serialize the ChannelManager prior to sending payments
664 let nodes_0_serialized = nodes[0].node.encode();
666 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
668 let amt_msat = 1_000_000;
669 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
670 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
671 let route_params = route.route_params.unwrap().clone();
672 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
673 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
674 check_added_monitors!(nodes[0], 1);
676 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
677 assert_eq!(events.len(), 1);
678 let payment_event = SendEvent::from_event(events.pop().unwrap());
679 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
681 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
682 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
683 // which would prevent retry.
684 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
685 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
687 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
688 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
689 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
690 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
692 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
694 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
695 if confirm_before_reload {
696 mine_transaction(&nodes[0], &as_commitment_tx);
697 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
700 // The ChannelMonitor should always be the latest version, as we're required to persist it
701 // during the `commitment_signed_dance!()`.
702 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
703 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
705 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
706 // force-close the channel.
707 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
708 assert!(nodes[0].node.list_channels().is_empty());
709 assert!(nodes[0].node.has_pending_payments());
710 nodes[0].node.timer_tick_occurred();
711 if !confirm_before_reload {
712 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
713 assert_eq!(as_broadcasted_txn.len(), 1);
714 assert_eq!(as_broadcasted_txn[0].txid(), as_commitment_tx.txid());
716 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
718 check_added_monitors!(nodes[0], 1);
720 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
721 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
722 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
724 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
726 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
727 // error, as the channel has hit the chain.
728 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
729 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
731 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
732 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
733 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
734 assert_eq!(as_err.len(), 1);
736 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
737 assert_eq!(node_id, nodes[1].node.get_our_node_id());
738 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
739 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 {}",
740 &nodes[1].node.get_our_node_id())) }, [nodes[0].node.get_our_node_id()], 100000);
741 check_added_monitors!(nodes[1], 1);
742 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
744 _ => panic!("Unexpected event"),
746 check_closed_broadcast!(nodes[1], false);
748 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
749 // we close in a moment.
750 nodes[2].node.claim_funds(payment_preimage_1);
751 check_added_monitors!(nodes[2], 1);
752 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
754 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
755 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
756 check_added_monitors!(nodes[1], 1);
757 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
758 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, true, false);
760 if confirm_before_reload {
761 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
762 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
765 // Create a new channel on which to retry the payment before we fail the payment via the
766 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
767 // connecting several blocks while creating the channel (implying time has passed).
768 create_announced_chan_between_nodes(&nodes, 0, 1);
769 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
771 mine_transaction(&nodes[1], &as_commitment_tx);
772 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
773 assert_eq!(bs_htlc_claim_txn.len(), 1);
774 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
776 if !confirm_before_reload {
777 mine_transaction(&nodes[0], &as_commitment_tx);
779 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
780 expect_payment_sent(&nodes[0], payment_preimage_1, None, true, false);
781 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
782 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
783 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
784 assert_eq!(txn.len(), 2);
785 (txn.remove(0), txn.remove(0))
787 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
788 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
789 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
790 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
792 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
794 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
795 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
797 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
798 // reloaded) via a route over the new channel, which work without issue and eventually be
799 // received and claimed at the recipient just like any other payment.
800 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
802 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
803 // and not the original fee. We also update node[1]'s relevant config as
804 // do_claim_payment_along_route expects us to never overpay.
806 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
807 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
808 .unwrap().lock().unwrap();
809 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
810 let mut new_config = channel.context().config();
811 new_config.forwarding_fee_base_msat += 100_000;
812 channel.context_mut().update_config(&new_config);
813 new_route.paths[0].hops[0].fee_msat += 100_000;
816 // Force expiration of the channel's previous config.
817 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
818 nodes[1].node.timer_tick_occurred();
821 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
822 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
823 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
824 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
825 check_added_monitors!(nodes[0], 1);
826 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
827 assert_eq!(events.len(), 1);
828 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
829 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
830 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
834 fn retry_with_no_persist() {
835 do_retry_with_no_persist(true);
836 do_retry_with_no_persist(false);
839 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
840 // Test that an off-chain completed payment is not retryable on restart. This was previously
841 // broken for dust payments, but we test for both dust and non-dust payments.
843 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
845 let chanmon_cfgs = create_chanmon_cfgs(3);
846 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
848 let mut manually_accept_config = test_default_channel_config();
849 manually_accept_config.manually_accept_inbound_channels = true;
852 let first_new_chain_monitor;
853 let second_persister;
854 let second_new_chain_monitor;
856 let third_new_chain_monitor;
858 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
859 let first_nodes_0_deserialized;
860 let second_nodes_0_deserialized;
861 let third_nodes_0_deserialized;
863 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
865 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
866 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
867 confirm_transaction(&nodes[0], &funding_tx);
868 confirm_transaction(&nodes[1], &funding_tx);
869 // Ignore the announcement_signatures messages
870 nodes[0].node.get_and_clear_pending_msg_events();
871 nodes[1].node.get_and_clear_pending_msg_events();
872 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
874 // Serialize the ChannelManager prior to sending payments
875 let mut nodes_0_serialized = nodes[0].node.encode();
877 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
878 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 });
880 // The ChannelMonitor should always be the latest version, as we're required to persist it
881 // during the `commitment_signed_dance!()`.
882 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
884 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);
885 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
887 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
888 // force-close the channel.
889 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
890 nodes[0].node.timer_tick_occurred();
891 assert!(nodes[0].node.list_channels().is_empty());
892 assert!(nodes[0].node.has_pending_payments());
893 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
894 check_added_monitors!(nodes[0], 1);
896 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
897 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
899 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
901 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
902 // error, as the channel has hit the chain.
903 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
904 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
906 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
907 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
908 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
909 assert_eq!(as_err.len(), 1);
910 let bs_commitment_tx;
912 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
913 assert_eq!(node_id, nodes[1].node.get_our_node_id());
914 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
915 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())) }
916 , [nodes[0].node.get_our_node_id()], 100000);
917 check_added_monitors!(nodes[1], 1);
918 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
920 _ => panic!("Unexpected event"),
922 check_closed_broadcast!(nodes[1], false);
924 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
925 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
926 // incoming HTLCs with the same payment hash later.
927 nodes[2].node.fail_htlc_backwards(&payment_hash);
928 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
929 check_added_monitors!(nodes[2], 1);
931 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
932 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
933 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
934 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
935 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
937 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
938 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
939 // after the commitment transaction, so always connect the commitment transaction.
940 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
941 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
943 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
944 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
945 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
946 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
947 assert_eq!(as_htlc_timeout.len(), 1);
949 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
950 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
951 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
952 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
955 // Create a new channel on which to retry the payment before we fail the payment via the
956 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
957 // connecting several blocks while creating the channel (implying time has passed).
958 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
959 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
960 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
962 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
963 // confirming, we will fail as it's considered still-pending...
964 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
965 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
966 Err(PaymentSendFailure::DuplicatePayment) => {},
967 _ => panic!("Unexpected error")
969 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
971 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
972 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
973 // (which should also still work).
974 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
975 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
976 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
978 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
979 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
980 nodes_0_serialized = nodes[0].node.encode();
982 // After the payment failed, we're free to send it again.
983 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
984 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
985 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
987 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);
988 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
990 nodes[0].node.test_process_background_events();
991 check_added_monitors(&nodes[0], 1);
993 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
994 reconnect_args.send_channel_ready = (true, true);
995 reconnect_nodes(reconnect_args);
997 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
998 // the payment is not (spuriously) listed as still pending.
999 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
1000 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
1001 check_added_monitors!(nodes[0], 1);
1002 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
1003 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1005 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
1006 Err(PaymentSendFailure::DuplicatePayment) => {},
1007 _ => panic!("Unexpected error")
1009 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1011 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1012 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
1013 nodes_0_serialized = nodes[0].node.encode();
1015 // Check that after reload we can send the payment again (though we shouldn't, since it was
1016 // claimed previously).
1017 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);
1018 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
1020 nodes[0].node.test_process_background_events();
1021 check_added_monitors(&nodes[0], 1);
1023 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1025 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
1026 Err(PaymentSendFailure::DuplicatePayment) => {},
1027 _ => panic!("Unexpected error")
1029 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1033 fn test_completed_payment_not_retryable_on_reload() {
1034 do_test_completed_payment_not_retryable_on_reload(true);
1035 do_test_completed_payment_not_retryable_on_reload(false);
1039 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
1040 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
1041 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
1042 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
1043 // the ChannelMonitor tells it to.
1045 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
1046 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
1047 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
1048 let chanmon_cfgs = create_chanmon_cfgs(2);
1049 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1051 let new_chain_monitor;
1052 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1053 let nodes_0_deserialized;
1054 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1056 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
1058 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
1060 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
1061 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
1062 check_closed_broadcast!(nodes[0], true);
1063 check_added_monitors!(nodes[0], 1);
1064 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
1066 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1067 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
1069 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
1070 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
1071 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1072 assert_eq!(node_txn.len(), 3);
1073 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
1074 check_spends!(node_txn[1], funding_tx);
1075 check_spends!(node_txn[2], node_txn[1]);
1076 let timeout_txn = vec![node_txn[2].clone()];
1078 nodes[1].node.claim_funds(payment_preimage);
1079 check_added_monitors!(nodes[1], 1);
1080 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
1082 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[1].clone()]));
1083 check_closed_broadcast!(nodes[1], true);
1084 check_added_monitors!(nodes[1], 1);
1085 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
1086 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
1087 assert_eq!(claim_txn.len(), 1);
1088 check_spends!(claim_txn[0], node_txn[1]);
1090 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[1].clone()]));
1092 if confirm_commitment_tx {
1093 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
1096 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] });
1098 if payment_timeout {
1099 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
1100 connect_block(&nodes[0], &claim_block);
1101 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
1104 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
1105 // returning InProgress. This should cause the claim event to never make its way to the
1107 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
1108 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
1110 if payment_timeout {
1111 connect_blocks(&nodes[0], 1);
1113 connect_block(&nodes[0], &claim_block);
1116 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
1117 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
1118 .get_mut(&funding_txo).unwrap().drain().collect();
1119 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
1120 // If we're testing connection idempotency we may get substantially more.
1121 assert!(mon_updates.len() >= 1);
1122 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
1123 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1125 // If we persist the ChannelManager here, we should get the PaymentSent event after
1127 let mut chan_manager_serialized = Vec::new();
1128 if !persist_manager_post_event {
1129 chan_manager_serialized = nodes[0].node.encode();
1132 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
1133 // payment sent event.
1134 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1135 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1136 for update in mon_updates {
1137 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
1139 if payment_timeout {
1140 expect_payment_failed!(nodes[0], payment_hash, false);
1142 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1145 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
1147 if persist_manager_post_event {
1148 chan_manager_serialized = nodes[0].node.encode();
1151 // Now reload nodes[0]...
1152 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
1154 if persist_manager_post_event {
1155 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1156 } else if payment_timeout {
1157 expect_payment_failed!(nodes[0], payment_hash, false);
1159 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1162 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
1163 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
1164 // payment events should kick in, leaving us with no pending events here.
1165 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
1166 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
1167 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1168 check_added_monitors(&nodes[0], 1);
1172 fn test_dup_htlc_onchain_fails_on_reload() {
1173 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
1174 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
1175 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
1176 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
1177 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
1178 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
1182 fn test_fulfill_restart_failure() {
1183 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
1184 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
1185 // again, or fail it, giving us free money.
1187 // Of course probably they won't fail it and give us free money, but because we have code to
1188 // handle it, we should test the logic for it anyway. We do that here.
1189 let chanmon_cfgs = create_chanmon_cfgs(2);
1190 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1192 let new_chain_monitor;
1193 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1194 let nodes_1_deserialized;
1195 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1197 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1198 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
1200 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
1201 // pre-fulfill, which we do by serializing it here.
1202 let chan_manager_serialized = nodes[1].node.encode();
1203 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1205 nodes[1].node.claim_funds(payment_preimage);
1206 check_added_monitors!(nodes[1], 1);
1207 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1209 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1210 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1211 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
1213 // Now reload nodes[1]...
1214 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1216 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1217 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1219 nodes[1].node.fail_htlc_backwards(&payment_hash);
1220 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1221 check_added_monitors!(nodes[1], 1);
1222 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1223 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1224 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1225 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1226 // it had already considered the payment fulfilled, and now they just got free money.
1227 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1231 fn get_ldk_payment_preimage() {
1232 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1233 let chanmon_cfgs = create_chanmon_cfgs(2);
1234 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1235 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1236 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1237 create_announced_chan_between_nodes(&nodes, 0, 1);
1239 let amt_msat = 60_000;
1240 let expiry_secs = 60 * 60;
1241 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1243 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1244 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
1245 let scorer = test_utils::TestScorer::new();
1246 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1247 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1248 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
1249 let route = get_route( &nodes[0].node.get_our_node_id(), &route_params,
1250 &nodes[0].network_graph.read_only(),
1251 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()), nodes[0].logger,
1252 &scorer, &Default::default(), &random_seed_bytes).unwrap();
1253 nodes[0].node.send_payment_with_route(&route, payment_hash,
1254 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1255 check_added_monitors!(nodes[0], 1);
1257 // Make sure to use `get_payment_preimage`
1258 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1259 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1260 assert_eq!(events.len(), 1);
1261 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1262 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1266 fn sent_probe_is_probe_of_sending_node() {
1267 let chanmon_cfgs = create_chanmon_cfgs(3);
1268 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1269 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1270 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1272 create_announced_chan_between_nodes(&nodes, 0, 1);
1273 create_announced_chan_between_nodes(&nodes, 1, 2);
1275 // First check we refuse to build a single-hop probe
1276 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1277 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1279 // Then build an actual two-hop probing path
1280 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1282 match nodes[0].node.send_probe(route.paths[0].clone()) {
1283 Ok((payment_hash, payment_id)) => {
1284 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1285 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1286 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1291 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1292 check_added_monitors!(nodes[0], 1);
1296 fn successful_probe_yields_event() {
1297 let chanmon_cfgs = create_chanmon_cfgs(3);
1298 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1299 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1300 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1302 create_announced_chan_between_nodes(&nodes, 0, 1);
1303 create_announced_chan_between_nodes(&nodes, 1, 2);
1305 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1307 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1309 // node[0] -- update_add_htlcs -> node[1]
1310 check_added_monitors!(nodes[0], 1);
1311 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1312 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1313 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1314 check_added_monitors!(nodes[1], 0);
1315 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1316 expect_pending_htlcs_forwardable!(nodes[1]);
1318 // node[1] -- update_add_htlcs -> node[2]
1319 check_added_monitors!(nodes[1], 1);
1320 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1321 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1322 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1323 check_added_monitors!(nodes[2], 0);
1324 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
1326 // node[1] <- update_fail_htlcs -- node[2]
1327 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1328 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1329 check_added_monitors!(nodes[1], 0);
1330 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1332 // node[0] <- update_fail_htlcs -- node[1]
1333 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1334 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1335 check_added_monitors!(nodes[0], 0);
1336 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1338 let mut events = nodes[0].node.get_and_clear_pending_events();
1339 assert_eq!(events.len(), 1);
1340 match events.drain(..).next().unwrap() {
1341 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1342 assert_eq!(payment_id, ev_pid);
1343 assert_eq!(payment_hash, ev_ph);
1347 assert!(!nodes[0].node.has_pending_payments());
1351 fn failed_probe_yields_event() {
1352 let chanmon_cfgs = create_chanmon_cfgs(3);
1353 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1354 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1355 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1357 create_announced_chan_between_nodes(&nodes, 0, 1);
1358 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1360 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1362 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 9_998_000);
1364 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1366 // node[0] -- update_add_htlcs -> node[1]
1367 check_added_monitors!(nodes[0], 1);
1368 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1369 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1370 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1371 check_added_monitors!(nodes[1], 0);
1372 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1373 expect_pending_htlcs_forwardable!(nodes[1]);
1375 // node[0] <- update_fail_htlcs -- node[1]
1376 check_added_monitors!(nodes[1], 1);
1377 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1378 // Skip the PendingHTLCsForwardable event
1379 let _events = nodes[1].node.get_and_clear_pending_events();
1380 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1381 check_added_monitors!(nodes[0], 0);
1382 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1384 let mut events = nodes[0].node.get_and_clear_pending_events();
1385 assert_eq!(events.len(), 1);
1386 match events.drain(..).next().unwrap() {
1387 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1388 assert_eq!(payment_id, ev_pid);
1389 assert_eq!(payment_hash, ev_ph);
1393 assert!(!nodes[0].node.has_pending_payments());
1397 fn onchain_failed_probe_yields_event() {
1398 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1400 let chanmon_cfgs = create_chanmon_cfgs(3);
1401 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1402 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1403 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1405 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1406 create_announced_chan_between_nodes(&nodes, 1, 2);
1408 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1410 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1411 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 1_000);
1412 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1414 // node[0] -- update_add_htlcs -> node[1]
1415 check_added_monitors!(nodes[0], 1);
1416 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1417 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1418 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1419 check_added_monitors!(nodes[1], 0);
1420 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1421 expect_pending_htlcs_forwardable!(nodes[1]);
1423 check_added_monitors!(nodes[1], 1);
1424 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1426 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1427 // Node A, which after 6 confirmations should result in a probe failure event.
1428 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1429 confirm_transaction(&nodes[0], &bs_txn[0]);
1430 check_closed_broadcast!(&nodes[0], true);
1431 check_added_monitors!(nodes[0], 1);
1433 let mut events = nodes[0].node.get_and_clear_pending_events();
1434 assert_eq!(events.len(), 2);
1435 let mut found_probe_failed = false;
1436 for event in events.drain(..) {
1438 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1439 assert_eq!(payment_id, ev_pid);
1440 assert_eq!(payment_hash, ev_ph);
1441 found_probe_failed = true;
1443 Event::ChannelClosed { .. } => {},
1447 assert!(found_probe_failed);
1448 assert!(!nodes[0].node.has_pending_payments());
1452 fn preflight_probes_yield_event_and_skip() {
1453 let chanmon_cfgs = create_chanmon_cfgs(5);
1454 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1456 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1457 let mut no_htlc_limit_config = test_default_channel_config();
1458 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1460 let user_configs = std::iter::repeat(no_htlc_limit_config).take(5).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1461 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &user_configs);
1462 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1464 // Setup channel topology:
1465 // (30k:0)- N2 -(1M:0)
1467 // N0 -(100k:0)-> N1 N4
1469 // (70k:0)- N3 -(1M:0)
1471 let first_chan_update = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0).0;
1472 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 30_000, 0);
1473 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 70_000, 0);
1474 create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 1_000_000, 0);
1475 create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0);
1477 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1478 invoice_features.set_basic_mpp_optional();
1480 let mut payment_params = PaymentParameters::from_node_id(nodes[4].node.get_our_node_id(), TEST_FINAL_CLTV)
1481 .with_bolt11_features(invoice_features).unwrap();
1483 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 80_000_000);
1484 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1486 // We check that only one probe was sent, the other one was skipped due to limited liquidity.
1487 assert_eq!(res.len(), 1);
1488 let log_msg = format!("Skipped sending payment probe to avoid putting channel {} under the liquidity limit.",
1489 first_chan_update.contents.short_channel_id);
1490 node_cfgs[0].logger.assert_log_contains("lightning::ln::channelmanager", &log_msg, 1);
1492 let (payment_hash, payment_id) = res.first().unwrap();
1494 // node[0] -- update_add_htlcs -> node[1]
1495 check_added_monitors!(nodes[0], 1);
1496 let probe_event = SendEvent::from_node(&nodes[0]);
1497 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1498 check_added_monitors!(nodes[1], 0);
1499 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1500 expect_pending_htlcs_forwardable!(nodes[1]);
1502 // node[1] -- update_add_htlcs -> node[2]
1503 check_added_monitors!(nodes[1], 1);
1504 let probe_event = SendEvent::from_node(&nodes[1]);
1505 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1506 check_added_monitors!(nodes[2], 0);
1507 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, false);
1508 expect_pending_htlcs_forwardable!(nodes[2]);
1510 // node[2] -- update_add_htlcs -> node[4]
1511 check_added_monitors!(nodes[2], 1);
1512 let probe_event = SendEvent::from_node(&nodes[2]);
1513 nodes[4].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &probe_event.msgs[0]);
1514 check_added_monitors!(nodes[4], 0);
1515 commitment_signed_dance!(nodes[4], nodes[2], probe_event.commitment_msg, true, true);
1517 // node[2] <- update_fail_htlcs -- node[4]
1518 let updates = get_htlc_update_msgs!(nodes[4], nodes[2].node.get_our_node_id());
1519 nodes[2].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1520 check_added_monitors!(nodes[2], 0);
1521 commitment_signed_dance!(nodes[2], nodes[4], updates.commitment_signed, true);
1523 // node[1] <- update_fail_htlcs -- node[2]
1524 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1525 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1526 check_added_monitors!(nodes[1], 0);
1527 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1529 // node[0] <- update_fail_htlcs -- node[1]
1530 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1531 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1532 check_added_monitors!(nodes[0], 0);
1533 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1535 let mut events = nodes[0].node.get_and_clear_pending_events();
1536 assert_eq!(events.len(), 1);
1537 match events.drain(..).next().unwrap() {
1538 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1539 assert_eq!(*payment_id, ev_pid);
1540 assert_eq!(*payment_hash, ev_ph);
1544 assert!(!nodes[0].node.has_pending_payments());
1548 fn claimed_send_payment_idempotent() {
1549 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1550 let chanmon_cfgs = create_chanmon_cfgs(2);
1551 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1552 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1553 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1555 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1557 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1558 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1560 macro_rules! check_send_rejected {
1562 // If we try to resend a new payment with a different payment_hash but with the same
1563 // payment_id, it should be rejected.
1564 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1565 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1567 Err(PaymentSendFailure::DuplicatePayment) => {},
1568 _ => panic!("Unexpected send result: {:?}", send_result),
1571 // Further, if we try to send a spontaneous payment with the same payment_id it should
1572 // also be rejected.
1573 let send_result = nodes[0].node.send_spontaneous_payment(
1574 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1576 Err(PaymentSendFailure::DuplicatePayment) => {},
1577 _ => panic!("Unexpected send result: {:?}", send_result),
1582 check_send_rejected!();
1584 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1585 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1586 // we must remain just as idempotent as we were before.
1587 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1589 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1590 nodes[0].node.timer_tick_occurred();
1593 check_send_rejected!();
1595 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1596 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1597 // the payment complete. However, they could have called `send_payment` while the event was
1598 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1599 // after the event is handled a duplicate payment should sitll be rejected.
1600 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1601 check_send_rejected!();
1603 // If relatively little time has passed, a duplicate payment should still fail.
1604 nodes[0].node.timer_tick_occurred();
1605 check_send_rejected!();
1607 // However, after some time has passed (at least more than the one timer tick above), a
1608 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1609 // references to the old payment data.
1610 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1611 nodes[0].node.timer_tick_occurred();
1614 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1615 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1616 check_added_monitors!(nodes[0], 1);
1617 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1618 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1622 fn abandoned_send_payment_idempotent() {
1623 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1625 let chanmon_cfgs = create_chanmon_cfgs(2);
1626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1628 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1630 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1632 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1633 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1635 macro_rules! check_send_rejected {
1637 // If we try to resend a new payment with a different payment_hash but with the same
1638 // payment_id, it should be rejected.
1639 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1640 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1642 Err(PaymentSendFailure::DuplicatePayment) => {},
1643 _ => panic!("Unexpected send result: {:?}", send_result),
1646 // Further, if we try to send a spontaneous payment with the same payment_id it should
1647 // also be rejected.
1648 let send_result = nodes[0].node.send_spontaneous_payment(
1649 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1651 Err(PaymentSendFailure::DuplicatePayment) => {},
1652 _ => panic!("Unexpected send result: {:?}", send_result),
1657 check_send_rejected!();
1659 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1660 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1662 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1664 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1665 nodes[0].node.timer_tick_occurred();
1667 check_send_rejected!();
1669 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1671 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1672 // failed payment back.
1673 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1674 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1675 check_added_monitors!(nodes[0], 1);
1676 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1677 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1680 #[derive(PartialEq)]
1681 enum InterceptTest {
1688 fn test_trivial_inflight_htlc_tracking(){
1689 // In this test, we test three scenarios:
1690 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1691 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1692 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1693 let chanmon_cfgs = create_chanmon_cfgs(3);
1694 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1695 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1696 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1698 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1699 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1701 // Send and claim the payment. Inflight HTLCs should be empty.
1702 let (_, payment_hash, _, payment_id) = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1703 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1705 let mut node_0_per_peer_lock;
1706 let mut node_0_peer_state_lock;
1707 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1709 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1710 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1711 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1712 channel_1.context().get_short_channel_id().unwrap()
1714 assert_eq!(chan_1_used_liquidity, None);
1717 let mut node_1_per_peer_lock;
1718 let mut node_1_peer_state_lock;
1719 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1721 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1722 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1723 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1724 channel_2.context().get_short_channel_id().unwrap()
1727 assert_eq!(chan_2_used_liquidity, None);
1729 let pending_payments = nodes[0].node.list_recent_payments();
1730 assert_eq!(pending_payments.len(), 1);
1731 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash), payment_id });
1733 // Remove fulfilled payment
1734 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1735 nodes[0].node.timer_tick_occurred();
1738 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1739 let (payment_preimage, payment_hash, _, payment_id) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1740 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1742 let mut node_0_per_peer_lock;
1743 let mut node_0_peer_state_lock;
1744 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1746 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1747 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1748 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1749 channel_1.context().get_short_channel_id().unwrap()
1751 // First hop accounts for expected 1000 msat fee
1752 assert_eq!(chan_1_used_liquidity, Some(501000));
1755 let mut node_1_per_peer_lock;
1756 let mut node_1_peer_state_lock;
1757 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1759 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1760 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1761 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1762 channel_2.context().get_short_channel_id().unwrap()
1765 assert_eq!(chan_2_used_liquidity, Some(500000));
1767 let pending_payments = nodes[0].node.list_recent_payments();
1768 assert_eq!(pending_payments.len(), 1);
1769 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_id, payment_hash, total_msat: 500000 });
1771 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1772 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1774 // Remove fulfilled payment
1775 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1776 nodes[0].node.timer_tick_occurred();
1779 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1781 let mut node_0_per_peer_lock;
1782 let mut node_0_peer_state_lock;
1783 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1785 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1786 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1787 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1788 channel_1.context().get_short_channel_id().unwrap()
1790 assert_eq!(chan_1_used_liquidity, None);
1793 let mut node_1_per_peer_lock;
1794 let mut node_1_peer_state_lock;
1795 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1797 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1798 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1799 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1800 channel_2.context().get_short_channel_id().unwrap()
1802 assert_eq!(chan_2_used_liquidity, None);
1805 let pending_payments = nodes[0].node.list_recent_payments();
1806 assert_eq!(pending_payments.len(), 0);
1810 fn test_holding_cell_inflight_htlcs() {
1811 let chanmon_cfgs = create_chanmon_cfgs(2);
1812 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1813 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1814 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1815 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1817 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1818 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1820 // Queue up two payments - one will be delivered right away, one immediately goes into the
1821 // holding cell as nodes[0] is AwaitingRAA.
1823 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1824 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1825 check_added_monitors!(nodes[0], 1);
1826 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1827 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1828 check_added_monitors!(nodes[0], 0);
1831 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1834 let mut node_0_per_peer_lock;
1835 let mut node_0_peer_state_lock;
1836 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1838 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1839 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1840 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1841 channel.context().get_short_channel_id().unwrap()
1844 assert_eq!(used_liquidity, Some(2000000));
1847 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1848 nodes[0].node.get_and_clear_pending_msg_events();
1852 fn intercepted_payment() {
1853 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1854 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1855 // payment or (b) fail the payment.
1856 do_test_intercepted_payment(InterceptTest::Forward);
1857 do_test_intercepted_payment(InterceptTest::Fail);
1858 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1859 do_test_intercepted_payment(InterceptTest::Timeout);
1862 fn do_test_intercepted_payment(test: InterceptTest) {
1863 let chanmon_cfgs = create_chanmon_cfgs(3);
1864 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1866 let mut zero_conf_chan_config = test_default_channel_config();
1867 zero_conf_chan_config.manually_accept_inbound_channels = true;
1868 let mut intercept_forwards_config = test_default_channel_config();
1869 intercept_forwards_config.accept_intercept_htlcs = true;
1870 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1872 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1873 let scorer = test_utils::TestScorer::new();
1874 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1876 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1878 let amt_msat = 100_000;
1879 let intercept_scid = nodes[1].node.get_intercept_scid();
1880 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1881 .with_route_hints(vec![
1882 RouteHint(vec![RouteHintHop {
1883 src_node_id: nodes[1].node.get_our_node_id(),
1884 short_channel_id: intercept_scid,
1887 proportional_millionths: 0,
1889 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1890 htlc_minimum_msat: None,
1891 htlc_maximum_msat: None,
1894 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1895 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat,);
1896 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params,
1897 &nodes[0].network_graph.read_only(), None, nodes[0].logger, &scorer, &Default::default(),
1898 &random_seed_bytes).unwrap();
1900 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1901 nodes[0].node.send_payment_with_route(&route, payment_hash,
1902 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1903 let payment_event = {
1905 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1906 assert_eq!(added_monitors.len(), 1);
1907 added_monitors.clear();
1909 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1910 assert_eq!(events.len(), 1);
1911 SendEvent::from_event(events.remove(0))
1913 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1914 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1916 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1917 let events = nodes[1].node.get_and_clear_pending_events();
1918 assert_eq!(events.len(), 1);
1919 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1920 crate::events::Event::HTLCIntercepted {
1921 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1923 assert_eq!(pmt_hash, payment_hash);
1924 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1925 assert_eq!(short_channel_id, intercept_scid);
1926 (intercept_id, expected_outbound_amount_msat)
1931 // Check for unknown channel id error.
1932 let unknown_chan_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &ChannelId::from_bytes([42; 32]), nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1933 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable {
1934 err: format!("Channel with id {} not found for the passed counterparty node_id {}.",
1935 log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1937 if test == InterceptTest::Fail {
1938 // Ensure we can fail the intercepted payment back.
1939 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1940 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1941 nodes[1].node.process_pending_htlc_forwards();
1942 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1943 check_added_monitors!(&nodes[1], 1);
1944 assert!(update_fail.update_fail_htlcs.len() == 1);
1945 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1946 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1947 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1949 // Ensure the payment fails with the expected error.
1950 let fail_conditions = PaymentFailedConditions::new()
1951 .blamed_scid(intercept_scid)
1952 .blamed_chan_closed(true)
1953 .expected_htlc_error_data(0x4000 | 10, &[]);
1954 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1955 } else if test == InterceptTest::Forward {
1956 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1957 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1958 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();
1959 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1960 err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
1961 temp_chan_id, nodes[2].node.get_our_node_id()) });
1962 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1964 // Open the just-in-time channel so the payment can then be forwarded.
1965 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1967 // Finally, forward the intercepted payment through and claim it.
1968 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1969 expect_pending_htlcs_forwardable!(nodes[1]);
1971 let payment_event = {
1973 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1974 assert_eq!(added_monitors.len(), 1);
1975 added_monitors.clear();
1977 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1978 assert_eq!(events.len(), 1);
1979 SendEvent::from_event(events.remove(0))
1981 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1982 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1983 expect_pending_htlcs_forwardable!(nodes[2]);
1985 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1986 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1987 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1988 let events = nodes[0].node.get_and_clear_pending_events();
1989 assert_eq!(events.len(), 2);
1991 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1992 assert_eq!(payment_preimage, *ev_preimage);
1993 assert_eq!(payment_hash, *ev_hash);
1994 assert_eq!(fee_paid_msat, &Some(1000));
1996 _ => panic!("Unexpected event")
1999 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
2000 assert_eq!(hash, Some(payment_hash));
2002 _ => panic!("Unexpected event")
2004 check_added_monitors(&nodes[0], 1);
2005 } else if test == InterceptTest::Timeout {
2006 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
2007 connect_block(&nodes[0], &block);
2008 connect_block(&nodes[1], &block);
2009 for _ in 0..TEST_FINAL_CLTV {
2010 block.header.prev_blockhash = block.block_hash();
2011 connect_block(&nodes[0], &block);
2012 connect_block(&nodes[1], &block);
2014 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
2015 check_added_monitors!(nodes[1], 1);
2016 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2017 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
2018 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
2019 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
2020 assert!(htlc_timeout_updates.update_fee.is_none());
2022 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
2023 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
2024 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
2026 // Check for unknown intercept id error.
2027 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
2028 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();
2029 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2030 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
2031 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2036 fn accept_underpaying_htlcs_config() {
2037 do_accept_underpaying_htlcs_config(1);
2038 do_accept_underpaying_htlcs_config(2);
2039 do_accept_underpaying_htlcs_config(3);
2042 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
2043 let chanmon_cfgs = create_chanmon_cfgs(3);
2044 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2045 let mut intercept_forwards_config = test_default_channel_config();
2046 intercept_forwards_config.accept_intercept_htlcs = true;
2047 let mut underpay_config = test_default_channel_config();
2048 underpay_config.channel_config.accept_underpaying_htlcs = true;
2049 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
2050 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2052 let mut chan_ids = Vec::new();
2053 for _ in 0..num_mpp_parts {
2054 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000, 0);
2055 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 2_000_000, 0).0.channel_id;
2056 chan_ids.push(channel_id);
2059 // Send the initial payment.
2060 let amt_msat = 900_000;
2061 let skimmed_fee_msat = 20;
2062 let mut route_hints = Vec::new();
2063 for _ in 0..num_mpp_parts {
2064 route_hints.push(RouteHint(vec![RouteHintHop {
2065 src_node_id: nodes[1].node.get_our_node_id(),
2066 short_channel_id: nodes[1].node.get_intercept_scid(),
2069 proportional_millionths: 0,
2071 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
2072 htlc_minimum_msat: None,
2073 htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
2076 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2077 .with_route_hints(route_hints).unwrap()
2078 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
2079 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2080 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
2081 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2082 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2083 check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
2084 let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
2085 assert_eq!(events.len(), num_mpp_parts);
2087 // Forward the intercepted payments.
2088 for (idx, ev) in events.into_iter().enumerate() {
2089 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
2090 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
2092 let events = nodes[1].node.get_and_clear_pending_events();
2093 assert_eq!(events.len(), 1);
2094 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
2095 crate::events::Event::HTLCIntercepted {
2096 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
2098 assert_eq!(pmt_hash, payment_hash);
2099 (intercept_id, expected_outbound_amount_msat)
2103 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
2104 nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
2105 expect_pending_htlcs_forwardable!(nodes[1]);
2106 let payment_event = {
2108 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2109 assert_eq!(added_monitors.len(), 1);
2110 added_monitors.clear();
2112 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2113 assert_eq!(events.len(), 1);
2114 SendEvent::from_event(events.remove(0))
2116 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
2117 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
2118 if idx == num_mpp_parts - 1 {
2119 expect_pending_htlcs_forwardable!(nodes[2]);
2123 // Claim the payment and check that the skimmed fee is as expected.
2124 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
2125 let events = nodes[2].node.get_and_clear_pending_events();
2126 assert_eq!(events.len(), 1);
2128 crate::events::Event::PaymentClaimable {
2129 ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
2131 assert_eq!(payment_hash, payment_hash);
2132 assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
2133 assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
2134 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2136 crate::events::PaymentPurpose::InvoicePayment { payment_preimage: ev_payment_preimage,
2137 payment_secret: ev_payment_secret, .. } =>
2139 assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
2140 assert_eq!(payment_secret, *ev_payment_secret);
2145 _ => panic!("Unexpected event"),
2147 let mut expected_paths_vecs = Vec::new();
2148 let mut expected_paths = Vec::new();
2149 for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
2150 for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
2151 let total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
2152 &nodes[0], &expected_paths[..], &vec![skimmed_fee_msat as u32; num_mpp_parts][..], false,
2154 // The sender doesn't know that the penultimate hop took an extra fee.
2155 expect_payment_sent(&nodes[0], payment_preimage,
2156 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true, true);
2159 #[derive(PartialEq)]
2170 fn automatic_retries() {
2171 do_automatic_retries(AutoRetry::Success);
2172 do_automatic_retries(AutoRetry::Spontaneous);
2173 do_automatic_retries(AutoRetry::FailAttempts);
2174 do_automatic_retries(AutoRetry::FailTimeout);
2175 do_automatic_retries(AutoRetry::FailOnRestart);
2176 do_automatic_retries(AutoRetry::FailOnRetry);
2178 fn do_automatic_retries(test: AutoRetry) {
2179 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
2181 let chanmon_cfgs = create_chanmon_cfgs(3);
2182 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2184 let new_chain_monitor;
2186 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2187 let node_0_deserialized;
2189 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2190 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2191 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2193 // Marshall data to send the payment
2194 #[cfg(feature = "std")]
2195 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2196 #[cfg(not(feature = "std"))]
2197 let payment_expiry_secs = 60 * 60;
2198 let amt_msat = 1000;
2199 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2200 invoice_features.set_variable_length_onion_required();
2201 invoice_features.set_payment_secret_required();
2202 invoice_features.set_basic_mpp_optional();
2203 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2204 .with_expiry_time(payment_expiry_secs as u64)
2205 .with_bolt11_features(invoice_features).unwrap();
2206 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2207 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
2209 macro_rules! pass_failed_attempt_with_retry_along_path {
2210 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
2211 // Send a payment attempt that fails due to lack of liquidity on the second hop
2212 check_added_monitors!(nodes[0], 1);
2213 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2214 let mut update_add = update_0.update_add_htlcs[0].clone();
2215 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
2216 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
2217 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2218 nodes[1].node.process_pending_htlc_forwards();
2219 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
2220 vec![HTLCDestination::NextHopChannel {
2221 node_id: Some(nodes[2].node.get_our_node_id()),
2222 channel_id: $failing_channel_id,
2224 nodes[1].node.process_pending_htlc_forwards();
2225 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2226 check_added_monitors!(&nodes[1], 1);
2227 assert!(update_1.update_fail_htlcs.len() == 1);
2228 let fail_msg = update_1.update_fail_htlcs[0].clone();
2229 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
2230 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
2232 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
2233 let mut events = nodes[0].node.get_and_clear_pending_events();
2234 assert_eq!(events.len(), 2);
2236 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2237 assert_eq!(payment_hash, ev_payment_hash);
2238 assert_eq!(payment_failed_permanently, false);
2240 _ => panic!("Unexpected event"),
2242 if $expect_pending_htlcs_forwardable {
2244 Event::PendingHTLCsForwardable { .. } => {},
2245 _ => panic!("Unexpected event"),
2249 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
2250 assert_eq!(payment_hash, ev_payment_hash);
2252 _ => panic!("Unexpected event"),
2258 if test == AutoRetry::Success {
2259 // Test that we can succeed on the first retry.
2260 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2261 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2262 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2264 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2265 // attempt, since the initial second hop channel will be excluded from pathfinding
2266 create_announced_chan_between_nodes(&nodes, 1, 2);
2268 // We retry payments in `process_pending_htlc_forwards`
2269 nodes[0].node.process_pending_htlc_forwards();
2270 check_added_monitors!(nodes[0], 1);
2271 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2272 assert_eq!(msg_events.len(), 1);
2273 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
2274 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2275 } else if test == AutoRetry::Spontaneous {
2276 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
2277 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
2278 Retry::Attempts(1)).unwrap();
2279 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2281 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2282 // attempt, since the initial second hop channel will be excluded from pathfinding
2283 create_announced_chan_between_nodes(&nodes, 1, 2);
2285 // We retry payments in `process_pending_htlc_forwards`
2286 nodes[0].node.process_pending_htlc_forwards();
2287 check_added_monitors!(nodes[0], 1);
2288 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2289 assert_eq!(msg_events.len(), 1);
2290 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2291 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2292 } else if test == AutoRetry::FailAttempts {
2293 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2294 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2295 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2296 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2298 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2299 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2300 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2302 // We retry payments in `process_pending_htlc_forwards`
2303 nodes[0].node.process_pending_htlc_forwards();
2304 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2306 // Ensure we won't retry a second time.
2307 nodes[0].node.process_pending_htlc_forwards();
2308 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2309 assert_eq!(msg_events.len(), 0);
2310 } else if test == AutoRetry::FailTimeout {
2311 #[cfg(not(feature = "no-std"))] {
2312 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2313 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2314 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2315 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2317 // Advance the time so the second attempt fails due to timeout.
2318 SinceEpoch::advance(Duration::from_secs(61));
2320 // Make sure we don't retry again.
2321 nodes[0].node.process_pending_htlc_forwards();
2322 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2323 assert_eq!(msg_events.len(), 0);
2325 let mut events = nodes[0].node.get_and_clear_pending_events();
2326 assert_eq!(events.len(), 1);
2328 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2329 assert_eq!(payment_hash, *ev_payment_hash);
2330 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2331 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2333 _ => panic!("Unexpected event"),
2336 } else if test == AutoRetry::FailOnRestart {
2337 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2338 // attempts remaining prior to restart.
2339 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2340 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2341 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2343 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2344 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2345 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2347 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2348 nodes[0].node.process_pending_htlc_forwards();
2349 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2351 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2352 let node_encoded = nodes[0].node.encode();
2353 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2354 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2356 let mut events = nodes[0].node.get_and_clear_pending_events();
2357 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2358 // Make sure we don't retry again.
2359 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2360 assert_eq!(msg_events.len(), 0);
2362 let mut events = nodes[0].node.get_and_clear_pending_events();
2363 assert_eq!(events.len(), 1);
2365 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2366 assert_eq!(payment_hash, *ev_payment_hash);
2367 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2368 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2370 _ => panic!("Unexpected event"),
2372 } else if test == AutoRetry::FailOnRetry {
2373 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2374 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2375 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2377 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2378 // fail to find a route.
2379 nodes[0].node.process_pending_htlc_forwards();
2380 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2381 assert_eq!(msg_events.len(), 0);
2383 let mut events = nodes[0].node.get_and_clear_pending_events();
2384 assert_eq!(events.len(), 1);
2386 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2387 assert_eq!(payment_hash, *ev_payment_hash);
2388 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2389 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2391 _ => panic!("Unexpected event"),
2397 fn auto_retry_partial_failure() {
2398 // Test that we'll retry appropriately on send partial failure and retry partial failure.
2399 let chanmon_cfgs = create_chanmon_cfgs(2);
2400 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2401 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2402 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2404 // Open three channels, the first has plenty of liquidity, the second and third have ~no
2405 // available liquidity, causing any outbound payments routed over it to fail immediately.
2406 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2407 let chan_2_id = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 989_000_000).0.contents.short_channel_id;
2408 let chan_3_id = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 989_000_000).0.contents.short_channel_id;
2410 // Marshall data to send the payment
2411 let amt_msat = 10_000_000;
2412 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2413 #[cfg(feature = "std")]
2414 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2415 #[cfg(not(feature = "std"))]
2416 let payment_expiry_secs = 60 * 60;
2417 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2418 invoice_features.set_variable_length_onion_required();
2419 invoice_features.set_payment_secret_required();
2420 invoice_features.set_basic_mpp_optional();
2421 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2422 .with_expiry_time(payment_expiry_secs as u64)
2423 .with_bolt11_features(invoice_features).unwrap();
2424 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2425 route_params.max_total_routing_fee_msat = None;
2427 // Configure the initial send, retry1 and retry2's paths.
2428 let send_route = Route {
2430 Path { hops: vec![RouteHop {
2431 pubkey: nodes[1].node.get_our_node_id(),
2432 node_features: nodes[1].node.node_features(),
2433 short_channel_id: chan_1_id,
2434 channel_features: nodes[1].node.channel_features(),
2435 fee_msat: amt_msat / 2,
2436 cltv_expiry_delta: 100,
2437 maybe_announced_channel: true,
2438 }], blinded_tail: None },
2439 Path { hops: vec![RouteHop {
2440 pubkey: nodes[1].node.get_our_node_id(),
2441 node_features: nodes[1].node.node_features(),
2442 short_channel_id: chan_2_id,
2443 channel_features: nodes[1].node.channel_features(),
2444 fee_msat: amt_msat / 2,
2445 cltv_expiry_delta: 100,
2446 maybe_announced_channel: true,
2447 }], blinded_tail: None },
2449 route_params: Some(route_params.clone()),
2451 let retry_1_route = Route {
2453 Path { hops: vec![RouteHop {
2454 pubkey: nodes[1].node.get_our_node_id(),
2455 node_features: nodes[1].node.node_features(),
2456 short_channel_id: chan_1_id,
2457 channel_features: nodes[1].node.channel_features(),
2458 fee_msat: amt_msat / 4,
2459 cltv_expiry_delta: 100,
2460 maybe_announced_channel: true,
2461 }], blinded_tail: None },
2462 Path { hops: vec![RouteHop {
2463 pubkey: nodes[1].node.get_our_node_id(),
2464 node_features: nodes[1].node.node_features(),
2465 short_channel_id: chan_3_id,
2466 channel_features: nodes[1].node.channel_features(),
2467 fee_msat: amt_msat / 4,
2468 cltv_expiry_delta: 100,
2469 maybe_announced_channel: true,
2470 }], blinded_tail: None },
2472 route_params: Some(route_params.clone()),
2474 let retry_2_route = Route {
2476 Path { hops: vec![RouteHop {
2477 pubkey: nodes[1].node.get_our_node_id(),
2478 node_features: nodes[1].node.node_features(),
2479 short_channel_id: chan_1_id,
2480 channel_features: nodes[1].node.channel_features(),
2481 fee_msat: amt_msat / 4,
2482 cltv_expiry_delta: 100,
2483 maybe_announced_channel: true,
2484 }], blinded_tail: None },
2486 route_params: Some(route_params.clone()),
2488 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2489 let mut payment_params = route_params.payment_params.clone();
2490 payment_params.previously_failed_channels.push(chan_2_id);
2492 let mut retry_1_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 2);
2493 retry_1_params.max_total_routing_fee_msat = None;
2494 nodes[0].router.expect_find_route(retry_1_params, Ok(retry_1_route));
2496 let mut payment_params = route_params.payment_params.clone();
2497 payment_params.previously_failed_channels.push(chan_3_id);
2498 let mut retry_2_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 4);
2499 retry_2_params.max_total_routing_fee_msat = None;
2500 nodes[0].router.expect_find_route(retry_2_params, Ok(retry_2_route));
2502 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2503 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2504 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2505 let payment_failed_events = nodes[0].node.get_and_clear_pending_events();
2506 assert_eq!(payment_failed_events.len(), 2);
2507 match payment_failed_events[0] {
2508 Event::PaymentPathFailed { .. } => {},
2509 _ => panic!("Unexpected event"),
2511 match payment_failed_events[1] {
2512 Event::PaymentPathFailed { .. } => {},
2513 _ => panic!("Unexpected event"),
2516 // Pass the first part of the payment along the path.
2517 check_added_monitors!(nodes[0], 1); // only one HTLC actually made it out
2518 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2520 // Only one HTLC/channel update actually made it out
2521 assert_eq!(msg_events.len(), 1);
2522 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2524 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2525 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2526 check_added_monitors!(nodes[1], 1);
2527 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2529 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2530 check_added_monitors!(nodes[0], 1);
2531 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2533 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2534 check_added_monitors!(nodes[0], 1);
2535 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2537 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2538 check_added_monitors!(nodes[1], 1);
2540 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2541 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2542 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2543 check_added_monitors!(nodes[1], 1);
2544 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2546 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2547 check_added_monitors!(nodes[0], 1);
2549 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2550 check_added_monitors!(nodes[0], 1);
2551 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2553 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2554 check_added_monitors!(nodes[1], 1);
2556 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2557 nodes[1].node.process_pending_htlc_forwards();
2558 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2559 nodes[1].node.claim_funds(payment_preimage);
2560 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2561 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2562 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2564 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2565 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
2566 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2567 check_added_monitors!(nodes[0], 1);
2568 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2570 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2571 check_added_monitors!(nodes[1], 4);
2572 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2574 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2575 check_added_monitors!(nodes[1], 1);
2576 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2578 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2579 check_added_monitors!(nodes[0], 1);
2580 expect_payment_path_successful!(nodes[0]);
2582 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2583 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2584 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2585 check_added_monitors!(nodes[0], 1);
2586 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2588 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2589 check_added_monitors!(nodes[1], 1);
2591 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2592 check_added_monitors!(nodes[1], 1);
2593 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2595 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2596 check_added_monitors!(nodes[0], 1);
2597 let events = nodes[0].node.get_and_clear_pending_events();
2598 assert_eq!(events.len(), 2);
2599 if let Event::PaymentPathSuccessful { .. } = events[0] {} else { panic!(); }
2600 if let Event::PaymentPathSuccessful { .. } = events[1] {} else { panic!(); }
2604 fn auto_retry_zero_attempts_send_error() {
2605 let chanmon_cfgs = create_chanmon_cfgs(2);
2606 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2607 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2608 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2610 // Open a single channel that does not have sufficient liquidity for the payment we want to
2612 let chan_id = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 989_000_000).0.contents.short_channel_id;
2614 // Marshall data to send the payment
2615 let amt_msat = 10_000_000;
2616 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(amt_msat), None);
2617 #[cfg(feature = "std")]
2618 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2619 #[cfg(not(feature = "std"))]
2620 let payment_expiry_secs = 60 * 60;
2621 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2622 invoice_features.set_variable_length_onion_required();
2623 invoice_features.set_payment_secret_required();
2624 invoice_features.set_basic_mpp_optional();
2625 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2626 .with_expiry_time(payment_expiry_secs as u64)
2627 .with_bolt11_features(invoice_features).unwrap();
2628 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2630 // Override the route search to return a route, rather than failing at the route-finding step.
2631 let send_route = Route {
2633 Path { hops: vec![RouteHop {
2634 pubkey: nodes[1].node.get_our_node_id(),
2635 node_features: nodes[1].node.node_features(),
2636 short_channel_id: chan_id,
2637 channel_features: nodes[1].node.channel_features(),
2639 cltv_expiry_delta: 100,
2640 maybe_announced_channel: true,
2641 }], blinded_tail: None },
2643 route_params: Some(route_params.clone()),
2645 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2647 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2648 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2649 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2650 let events = nodes[0].node.get_and_clear_pending_events();
2651 assert_eq!(events.len(), 2);
2652 if let Event::PaymentPathFailed { .. } = events[0] { } else { panic!(); }
2653 if let Event::PaymentFailed { .. } = events[1] { } else { panic!(); }
2654 check_added_monitors!(nodes[0], 0);
2658 fn fails_paying_after_rejected_by_payee() {
2659 let chanmon_cfgs = create_chanmon_cfgs(2);
2660 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2661 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2662 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2664 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2666 // Marshall data to send the payment
2667 let amt_msat = 20_000;
2668 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2669 #[cfg(feature = "std")]
2670 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2671 #[cfg(not(feature = "std"))]
2672 let payment_expiry_secs = 60 * 60;
2673 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2674 invoice_features.set_variable_length_onion_required();
2675 invoice_features.set_payment_secret_required();
2676 invoice_features.set_basic_mpp_optional();
2677 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2678 .with_expiry_time(payment_expiry_secs as u64)
2679 .with_bolt11_features(invoice_features).unwrap();
2680 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2682 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2683 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2684 check_added_monitors!(nodes[0], 1);
2685 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2686 assert_eq!(events.len(), 1);
2687 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2688 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2689 check_added_monitors!(nodes[1], 0);
2690 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2691 expect_pending_htlcs_forwardable!(nodes[1]);
2692 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2694 nodes[1].node.fail_htlc_backwards(&payment_hash);
2695 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2696 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2700 fn retry_multi_path_single_failed_payment() {
2701 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2702 let chanmon_cfgs = create_chanmon_cfgs(2);
2703 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2704 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2705 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2707 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2708 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2710 let amt_msat = 100_010_000;
2712 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2713 #[cfg(feature = "std")]
2714 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2715 #[cfg(not(feature = "std"))]
2716 let payment_expiry_secs = 60 * 60;
2717 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2718 invoice_features.set_variable_length_onion_required();
2719 invoice_features.set_payment_secret_required();
2720 invoice_features.set_basic_mpp_optional();
2721 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2722 .with_expiry_time(payment_expiry_secs as u64)
2723 .with_bolt11_features(invoice_features).unwrap();
2724 let mut route_params = RouteParameters::from_payment_params_and_value(
2725 payment_params.clone(), amt_msat);
2726 route_params.max_total_routing_fee_msat = None;
2728 let chans = nodes[0].node.list_usable_channels();
2729 let mut route = Route {
2731 Path { hops: vec![RouteHop {
2732 pubkey: nodes[1].node.get_our_node_id(),
2733 node_features: nodes[1].node.node_features(),
2734 short_channel_id: chans[0].short_channel_id.unwrap(),
2735 channel_features: nodes[1].node.channel_features(),
2737 cltv_expiry_delta: 100,
2738 maybe_announced_channel: true,
2739 }], blinded_tail: None },
2740 Path { hops: vec![RouteHop {
2741 pubkey: nodes[1].node.get_our_node_id(),
2742 node_features: nodes[1].node.node_features(),
2743 short_channel_id: chans[1].short_channel_id.unwrap(),
2744 channel_features: nodes[1].node.channel_features(),
2745 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2746 cltv_expiry_delta: 100,
2747 maybe_announced_channel: true,
2748 }], blinded_tail: None },
2750 route_params: Some(route_params.clone()),
2752 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2753 // On retry, split the payment across both channels.
2754 route.paths[0].hops[0].fee_msat = 50_000_001;
2755 route.paths[1].hops[0].fee_msat = 50_000_000;
2756 let mut pay_params = route.route_params.clone().unwrap().payment_params;
2757 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2759 // Note that the second request here requests the amount we originally failed to send,
2760 // not the amount remaining on the full payment, which should be changed.
2761 let mut retry_params = RouteParameters::from_payment_params_and_value(pay_params, 100_000_001);
2762 retry_params.max_total_routing_fee_msat = None;
2763 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2766 let scorer = chanmon_cfgs[0].scorer.read().unwrap();
2767 // The initial send attempt, 2 paths
2768 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2769 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2770 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2771 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2772 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2775 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2776 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2777 let events = nodes[0].node.get_and_clear_pending_events();
2778 assert_eq!(events.len(), 1);
2780 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2781 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2782 short_channel_id: Some(expected_scid), .. } =>
2784 assert_eq!(payment_hash, ev_payment_hash);
2785 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2787 _ => panic!("Unexpected event"),
2789 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2790 assert_eq!(htlc_msgs.len(), 2);
2791 check_added_monitors!(nodes[0], 2);
2795 fn immediate_retry_on_failure() {
2796 // Tests that we can/will retry immediately after a failure
2797 let chanmon_cfgs = create_chanmon_cfgs(2);
2798 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2799 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2800 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2802 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2803 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2805 let amt_msat = 100_000_001;
2806 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2807 #[cfg(feature = "std")]
2808 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2809 #[cfg(not(feature = "std"))]
2810 let payment_expiry_secs = 60 * 60;
2811 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2812 invoice_features.set_variable_length_onion_required();
2813 invoice_features.set_payment_secret_required();
2814 invoice_features.set_basic_mpp_optional();
2815 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2816 .with_expiry_time(payment_expiry_secs as u64)
2817 .with_bolt11_features(invoice_features).unwrap();
2818 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2820 let chans = nodes[0].node.list_usable_channels();
2821 let mut route = Route {
2823 Path { hops: vec![RouteHop {
2824 pubkey: nodes[1].node.get_our_node_id(),
2825 node_features: nodes[1].node.node_features(),
2826 short_channel_id: chans[0].short_channel_id.unwrap(),
2827 channel_features: nodes[1].node.channel_features(),
2828 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2829 cltv_expiry_delta: 100,
2830 maybe_announced_channel: true,
2831 }], blinded_tail: None },
2833 route_params: Some(RouteParameters::from_payment_params_and_value(
2834 PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV),
2837 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2838 // On retry, split the payment across both channels.
2839 route.paths.push(route.paths[0].clone());
2840 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2841 route.paths[0].hops[0].fee_msat = 50_000_000;
2842 route.paths[1].hops[0].fee_msat = 50_000_001;
2843 let mut pay_params = route_params.payment_params.clone();
2844 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2845 nodes[0].router.expect_find_route(
2846 RouteParameters::from_payment_params_and_value(pay_params, amt_msat),
2849 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2850 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2851 let events = nodes[0].node.get_and_clear_pending_events();
2852 assert_eq!(events.len(), 1);
2854 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2855 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2856 short_channel_id: Some(expected_scid), .. } =>
2858 assert_eq!(payment_hash, ev_payment_hash);
2859 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2861 _ => panic!("Unexpected event"),
2863 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2864 assert_eq!(htlc_msgs.len(), 2);
2865 check_added_monitors!(nodes[0], 2);
2869 fn no_extra_retries_on_back_to_back_fail() {
2870 // In a previous release, we had a race where we may exceed the payment retry count if we
2871 // get two failures in a row with the second indicating that all paths had failed (this field,
2872 // `all_paths_failed`, has since been removed).
2873 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2874 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2875 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2876 // pending which we will see later. Thus, when we previously removed the retry tracking map
2877 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2878 // retry entry even though more events for the same payment were still pending. This led to
2879 // us retrying a payment again even though we'd already given up on it.
2881 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2882 // is used to remove the payment retry counter entries instead. This tests for the specific
2883 // excess-retry case while also testing `PaymentFailed` generation.
2885 let chanmon_cfgs = create_chanmon_cfgs(3);
2886 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2887 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2888 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2890 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2891 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2893 let amt_msat = 200_000_000;
2894 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2895 #[cfg(feature = "std")]
2896 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2897 #[cfg(not(feature = "std"))]
2898 let payment_expiry_secs = 60 * 60;
2899 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2900 invoice_features.set_variable_length_onion_required();
2901 invoice_features.set_payment_secret_required();
2902 invoice_features.set_basic_mpp_optional();
2903 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2904 .with_expiry_time(payment_expiry_secs as u64)
2905 .with_bolt11_features(invoice_features).unwrap();
2906 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2907 route_params.max_total_routing_fee_msat = None;
2909 let mut route = Route {
2911 Path { hops: vec![RouteHop {
2912 pubkey: nodes[1].node.get_our_node_id(),
2913 node_features: nodes[1].node.node_features(),
2914 short_channel_id: chan_1_scid,
2915 channel_features: nodes[1].node.channel_features(),
2916 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2917 cltv_expiry_delta: 100,
2918 maybe_announced_channel: true,
2920 pubkey: nodes[2].node.get_our_node_id(),
2921 node_features: nodes[2].node.node_features(),
2922 short_channel_id: chan_2_scid,
2923 channel_features: nodes[2].node.channel_features(),
2924 fee_msat: 100_000_000,
2925 cltv_expiry_delta: 100,
2926 maybe_announced_channel: true,
2927 }], blinded_tail: None },
2928 Path { hops: vec![RouteHop {
2929 pubkey: nodes[1].node.get_our_node_id(),
2930 node_features: nodes[1].node.node_features(),
2931 short_channel_id: chan_1_scid,
2932 channel_features: nodes[1].node.channel_features(),
2933 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2934 cltv_expiry_delta: 100,
2935 maybe_announced_channel: true,
2937 pubkey: nodes[2].node.get_our_node_id(),
2938 node_features: nodes[2].node.node_features(),
2939 short_channel_id: chan_2_scid,
2940 channel_features: nodes[2].node.channel_features(),
2941 fee_msat: 100_000_000,
2942 cltv_expiry_delta: 100,
2943 maybe_announced_channel: true,
2944 }], blinded_tail: None }
2946 route_params: Some(RouteParameters::from_payment_params_and_value(
2947 PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV),
2950 route.route_params.as_mut().unwrap().max_total_routing_fee_msat = None;
2951 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2952 let mut second_payment_params = route_params.payment_params.clone();
2953 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2954 // On retry, we'll only return one path
2955 route.paths.remove(1);
2956 route.paths[0].hops[1].fee_msat = amt_msat;
2957 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat);
2958 retry_params.max_total_routing_fee_msat = None;
2959 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2961 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2962 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2963 let htlc_updates = SendEvent::from_node(&nodes[0]);
2964 check_added_monitors!(nodes[0], 1);
2965 assert_eq!(htlc_updates.msgs.len(), 1);
2967 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2968 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2969 check_added_monitors!(nodes[1], 1);
2970 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2972 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2973 check_added_monitors!(nodes[0], 1);
2974 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2976 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2977 check_added_monitors!(nodes[0], 1);
2978 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2980 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2981 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2982 check_added_monitors!(nodes[1], 1);
2983 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2985 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2986 check_added_monitors!(nodes[1], 1);
2987 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2989 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2990 check_added_monitors!(nodes[0], 1);
2992 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2993 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2994 check_added_monitors!(nodes[0], 1);
2995 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2997 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2998 check_added_monitors!(nodes[1], 1);
2999 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3001 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
3002 check_added_monitors!(nodes[1], 1);
3003 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3005 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
3006 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
3007 check_added_monitors!(nodes[0], 1);
3009 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
3010 check_added_monitors!(nodes[0], 1);
3011 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3013 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
3014 check_added_monitors!(nodes[1], 1);
3015 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
3016 check_added_monitors!(nodes[1], 1);
3017 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3019 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
3020 check_added_monitors!(nodes[0], 1);
3022 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
3023 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
3026 // Previously, we retried payments in an event consumer, which would retry each
3027 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
3028 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
3029 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
3030 // by adding the `PaymentFailed` event.
3032 // Because we now retry payments as a batch, we simply return a single-path route in the
3033 // second, batched, request, have that fail, ensure the payment was abandoned.
3034 let mut events = nodes[0].node.get_and_clear_pending_events();
3035 assert_eq!(events.len(), 3);
3037 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3038 assert_eq!(payment_hash, ev_payment_hash);
3039 assert_eq!(payment_failed_permanently, false);
3041 _ => panic!("Unexpected event"),
3044 Event::PendingHTLCsForwardable { .. } => {},
3045 _ => panic!("Unexpected event"),
3048 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3049 assert_eq!(payment_hash, ev_payment_hash);
3050 assert_eq!(payment_failed_permanently, false);
3052 _ => panic!("Unexpected event"),
3055 nodes[0].node.process_pending_htlc_forwards();
3056 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3057 check_added_monitors!(nodes[0], 1);
3059 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3060 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3061 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3062 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3063 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
3065 let mut events = nodes[0].node.get_and_clear_pending_events();
3066 assert_eq!(events.len(), 2);
3068 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3069 assert_eq!(payment_hash, ev_payment_hash);
3070 assert_eq!(payment_failed_permanently, false);
3072 _ => panic!("Unexpected event"),
3075 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
3076 assert_eq!(payment_hash, *ev_payment_hash);
3077 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
3078 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
3080 _ => panic!("Unexpected event"),
3085 fn test_simple_partial_retry() {
3086 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
3087 // full amount of the payment, rather than only the missing amount. Here we simply test for
3088 // this by sending a payment with two parts, failing one, and retrying the second. Note that
3089 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
3091 let chanmon_cfgs = create_chanmon_cfgs(3);
3092 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3093 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3094 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3096 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3097 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
3099 let amt_msat = 200_000_000;
3100 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3101 #[cfg(feature = "std")]
3102 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3103 #[cfg(not(feature = "std"))]
3104 let payment_expiry_secs = 60 * 60;
3105 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3106 invoice_features.set_variable_length_onion_required();
3107 invoice_features.set_payment_secret_required();
3108 invoice_features.set_basic_mpp_optional();
3109 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3110 .with_expiry_time(payment_expiry_secs as u64)
3111 .with_bolt11_features(invoice_features).unwrap();
3112 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
3113 route_params.max_total_routing_fee_msat = None;
3115 let mut route = Route {
3117 Path { hops: vec![RouteHop {
3118 pubkey: nodes[1].node.get_our_node_id(),
3119 node_features: nodes[1].node.node_features(),
3120 short_channel_id: chan_1_scid,
3121 channel_features: nodes[1].node.channel_features(),
3122 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
3123 cltv_expiry_delta: 100,
3124 maybe_announced_channel: true,
3126 pubkey: nodes[2].node.get_our_node_id(),
3127 node_features: nodes[2].node.node_features(),
3128 short_channel_id: chan_2_scid,
3129 channel_features: nodes[2].node.channel_features(),
3130 fee_msat: 100_000_000,
3131 cltv_expiry_delta: 100,
3132 maybe_announced_channel: true,
3133 }], blinded_tail: None },
3134 Path { hops: vec![RouteHop {
3135 pubkey: nodes[1].node.get_our_node_id(),
3136 node_features: nodes[1].node.node_features(),
3137 short_channel_id: chan_1_scid,
3138 channel_features: nodes[1].node.channel_features(),
3140 cltv_expiry_delta: 100,
3141 maybe_announced_channel: true,
3143 pubkey: nodes[2].node.get_our_node_id(),
3144 node_features: nodes[2].node.node_features(),
3145 short_channel_id: chan_2_scid,
3146 channel_features: nodes[2].node.channel_features(),
3147 fee_msat: 100_000_000,
3148 cltv_expiry_delta: 100,
3149 maybe_announced_channel: true,
3150 }], blinded_tail: None }
3152 route_params: Some(RouteParameters::from_payment_params_and_value(
3153 PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV),
3156 route.route_params.as_mut().unwrap().max_total_routing_fee_msat = None;
3157 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3158 let mut second_payment_params = route_params.payment_params.clone();
3159 second_payment_params.previously_failed_channels = vec![chan_2_scid];
3160 // On retry, we'll only be asked for one path (or 100k sats)
3161 route.paths.remove(0);
3162 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat / 2);
3163 retry_params.max_total_routing_fee_msat = None;
3164 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
3166 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3167 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
3168 let htlc_updates = SendEvent::from_node(&nodes[0]);
3169 check_added_monitors!(nodes[0], 1);
3170 assert_eq!(htlc_updates.msgs.len(), 1);
3172 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
3173 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
3174 check_added_monitors!(nodes[1], 1);
3175 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3177 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
3178 check_added_monitors!(nodes[0], 1);
3179 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
3181 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
3182 check_added_monitors!(nodes[0], 1);
3183 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3185 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
3186 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
3187 check_added_monitors!(nodes[1], 1);
3188 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3190 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
3191 check_added_monitors!(nodes[1], 1);
3192 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3194 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
3195 check_added_monitors!(nodes[0], 1);
3197 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3198 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
3199 check_added_monitors!(nodes[0], 1);
3200 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3202 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
3203 check_added_monitors!(nodes[1], 1);
3205 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
3206 check_added_monitors!(nodes[1], 1);
3208 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3210 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
3211 check_added_monitors!(nodes[0], 1);
3213 let mut events = nodes[0].node.get_and_clear_pending_events();
3214 assert_eq!(events.len(), 2);
3216 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3217 assert_eq!(payment_hash, ev_payment_hash);
3218 assert_eq!(payment_failed_permanently, false);
3220 _ => panic!("Unexpected event"),
3223 Event::PendingHTLCsForwardable { .. } => {},
3224 _ => panic!("Unexpected event"),
3227 nodes[0].node.process_pending_htlc_forwards();
3228 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3229 check_added_monitors!(nodes[0], 1);
3231 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3232 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3234 expect_pending_htlcs_forwardable!(nodes[1]);
3235 check_added_monitors!(nodes[1], 1);
3237 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3238 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
3239 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
3240 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
3242 expect_pending_htlcs_forwardable!(nodes[2]);
3243 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
3247 #[cfg(feature = "std")]
3248 fn test_threaded_payment_retries() {
3249 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
3250 // a single thread and would happily let multiple threads run retries at the same time. Because
3251 // retries are done by first calculating the amount we need to retry, then dropping the
3252 // relevant lock, then actually sending, we would happily let multiple threads retry the same
3253 // amount at the same time, overpaying our original HTLC!
3254 let chanmon_cfgs = create_chanmon_cfgs(4);
3255 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3256 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3257 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3259 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
3260 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
3261 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
3262 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
3264 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3265 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
3266 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
3267 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
3269 let amt_msat = 100_000_000;
3270 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3271 #[cfg(feature = "std")]
3272 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3273 #[cfg(not(feature = "std"))]
3274 let payment_expiry_secs = 60 * 60;
3275 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3276 invoice_features.set_variable_length_onion_required();
3277 invoice_features.set_payment_secret_required();
3278 invoice_features.set_basic_mpp_optional();
3279 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3280 .with_expiry_time(payment_expiry_secs as u64)
3281 .with_bolt11_features(invoice_features).unwrap();
3282 let mut route_params = RouteParameters {
3283 payment_params, final_value_msat: amt_msat, max_total_routing_fee_msat: Some(500_000),
3286 let mut route = Route {
3288 Path { hops: vec![RouteHop {
3289 pubkey: nodes[1].node.get_our_node_id(),
3290 node_features: nodes[1].node.node_features(),
3291 short_channel_id: chan_1_scid,
3292 channel_features: nodes[1].node.channel_features(),
3294 cltv_expiry_delta: 100,
3295 maybe_announced_channel: true,
3297 pubkey: nodes[3].node.get_our_node_id(),
3298 node_features: nodes[2].node.node_features(),
3299 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3300 channel_features: nodes[2].node.channel_features(),
3301 fee_msat: amt_msat / 1000,
3302 cltv_expiry_delta: 100,
3303 maybe_announced_channel: true,
3304 }], blinded_tail: None },
3305 Path { hops: vec![RouteHop {
3306 pubkey: nodes[2].node.get_our_node_id(),
3307 node_features: nodes[2].node.node_features(),
3308 short_channel_id: chan_3_scid,
3309 channel_features: nodes[2].node.channel_features(),
3311 cltv_expiry_delta: 100,
3312 maybe_announced_channel: true,
3314 pubkey: nodes[3].node.get_our_node_id(),
3315 node_features: nodes[3].node.node_features(),
3316 short_channel_id: chan_4_scid,
3317 channel_features: nodes[3].node.channel_features(),
3318 fee_msat: amt_msat - amt_msat / 1000,
3319 cltv_expiry_delta: 100,
3320 maybe_announced_channel: true,
3321 }], blinded_tail: None }
3323 route_params: Some(RouteParameters {
3324 payment_params: PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV),
3325 final_value_msat: amt_msat - amt_msat / 1000,
3326 max_total_routing_fee_msat: Some(500_000),
3329 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3331 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3332 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3333 check_added_monitors!(nodes[0], 2);
3334 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3335 assert_eq!(send_msg_events.len(), 2);
3336 send_msg_events.retain(|msg|
3337 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3338 // Drop the commitment update for nodes[2], we can just let that one sit pending
3340 *node_id == nodes[1].node.get_our_node_id()
3341 } else { panic!(); }
3344 // from here on out, the retry `RouteParameters` amount will be amt/1000
3345 route_params.final_value_msat /= 1000;
3348 let end_time = Instant::now() + Duration::from_secs(1);
3349 macro_rules! thread_body { () => { {
3350 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3351 let node_ref = NodePtr::from_node(&nodes[0]);
3353 let node_a = unsafe { &*node_ref.0 };
3354 while Instant::now() < end_time {
3355 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3356 // Ignore if we have any pending events, just always pretend we just got a
3357 // PendingHTLCsForwardable
3358 node_a.node.process_pending_htlc_forwards();
3362 let mut threads = Vec::new();
3363 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3365 // Back in the main thread, poll pending messages and make sure that we never have more than
3366 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3367 // there are HTLC messages shoved in while its running. This allows us to test that we never
3368 // generate an additional update_add_htlc until we've fully failed the first.
3369 let mut previously_failed_channels = Vec::new();
3371 assert_eq!(send_msg_events.len(), 1);
3372 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3373 assert_eq!(send_event.msgs.len(), 1);
3375 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3376 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3378 // Note that we only push one route into `expect_find_route` at a time, because that's all
3379 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3380 // we should still ultimately fail for the same reason - because we're trying to send too
3381 // many HTLCs at once.
3382 let mut new_route_params = route_params.clone();
3383 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3384 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3385 new_route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 100_000);
3386 route.paths[0].hops[1].short_channel_id += 1;
3387 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3389 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3390 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3391 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3392 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3393 // This races with our other threads which may generate an add-HTLCs commitment update via
3394 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3395 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3396 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3397 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3399 let cur_time = Instant::now();
3400 if cur_time > end_time {
3401 for thread in threads.drain(..) { thread.join().unwrap(); }
3404 // Make sure we have some events to handle when we go around...
3405 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3406 nodes[0].node.process_pending_htlc_forwards();
3407 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3408 check_added_monitors!(nodes[0], 2);
3410 if cur_time > end_time {
3416 fn do_no_missing_sent_on_reload(persist_manager_with_payment: bool, at_midpoint: bool) {
3417 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3418 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3419 // it was last persisted.
3420 let chanmon_cfgs = create_chanmon_cfgs(2);
3421 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3422 let (persister_a, persister_b, persister_c);
3423 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3424 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3425 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3426 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3428 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3430 let mut nodes_0_serialized = Vec::new();
3431 if !persist_manager_with_payment {
3432 nodes_0_serialized = nodes[0].node.encode();
3435 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3437 if persist_manager_with_payment {
3438 nodes_0_serialized = nodes[0].node.encode();
3441 nodes[1].node.claim_funds(our_payment_preimage);
3442 check_added_monitors!(nodes[1], 1);
3443 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3446 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3447 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3448 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3449 check_added_monitors!(nodes[0], 1);
3451 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3452 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
3453 commitment_signed_dance!(nodes[0], nodes[1], htlc_fulfill_updates.commitment_signed, false);
3454 // Ignore the PaymentSent event which is now pending on nodes[0] - if we were to handle it we'd
3455 // be expected to ignore the eventual conflicting PaymentFailed, but by not looking at it we
3456 // expect to get the PaymentSent again later.
3457 check_added_monitors(&nodes[0], 0);
3460 // The ChannelMonitor should always be the latest version, as we're required to persist it
3461 // during the commitment signed handling.
3462 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3463 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3465 let events = nodes[0].node.get_and_clear_pending_events();
3466 assert_eq!(events.len(), 2);
3467 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3468 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3469 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3470 // the double-claim that would otherwise appear at the end of this test.
3471 nodes[0].node.timer_tick_occurred();
3472 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3473 assert_eq!(as_broadcasted_txn.len(), 1);
3475 // Ensure that, even after some time, if we restart we still include *something* in the current
3476 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3477 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3478 // A naive implementation of the fix here would wipe the pending payments set, causing a
3479 // failure event when we restart.
3480 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3482 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3483 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);
3484 let events = nodes[0].node.get_and_clear_pending_events();
3485 assert!(events.is_empty());
3487 // Ensure that we don't generate any further events even after the channel-closing commitment
3488 // transaction is confirmed on-chain.
3489 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3490 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3492 let events = nodes[0].node.get_and_clear_pending_events();
3493 assert!(events.is_empty());
3495 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3496 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);
3497 let events = nodes[0].node.get_and_clear_pending_events();
3498 assert!(events.is_empty());
3499 check_added_monitors(&nodes[0], 1);
3503 fn no_missing_sent_on_midpoint_reload() {
3504 do_no_missing_sent_on_reload(false, true);
3505 do_no_missing_sent_on_reload(true, true);
3509 fn no_missing_sent_on_reload() {
3510 do_no_missing_sent_on_reload(false, false);
3511 do_no_missing_sent_on_reload(true, false);
3514 fn do_claim_from_closed_chan(fail_payment: bool) {
3515 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3516 // received had been closed between when the HTLC was received and when we went to claim it.
3517 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3518 // presumably the sender may retry later. Long ago it also reduced total code in the claim
3521 // However, this doesn't make sense if you're trying to do an atomic swap or some other
3522 // protocol that requires atomicity with some other action - if your money got claimed
3523 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3524 // is an over-optimization - there should be a very, very low likelihood that a channel closes
3525 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3526 // Since we now have code to handle this anyway we should allow it.
3528 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3529 // CLTVs on the paths to different value resulting in a different claim deadline.
3530 let chanmon_cfgs = create_chanmon_cfgs(4);
3531 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3532 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3533 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3535 create_announced_chan_between_nodes(&nodes, 0, 1);
3536 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3537 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3538 create_announced_chan_between_nodes(&nodes, 2, 3);
3540 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3541 let mut route_params = RouteParameters::from_payment_params_and_value(
3542 PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3543 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
3545 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3546 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3547 // Make sure the route is ordered as the B->D path before C->D
3548 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3549 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3551 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3552 // the HTLC is being relayed.
3553 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3554 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3555 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3557 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3558 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3559 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3560 check_added_monitors(&nodes[0], 2);
3561 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3562 send_msgs.sort_by(|a, _| {
3564 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3565 let node_b_id = nodes[1].node.get_our_node_id();
3566 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3569 assert_eq!(send_msgs.len(), 2);
3570 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3571 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3572 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3573 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3575 match receive_event.unwrap() {
3576 Event::PaymentClaimable { claim_deadline, .. } => {
3577 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3582 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3584 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3585 - if fail_payment { 0 } else { 2 });
3587 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3588 // and expire both immediately, though, by connecting another 4 blocks.
3589 let reason = HTLCDestination::FailedPayment { payment_hash };
3590 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3591 connect_blocks(&nodes[3], 4);
3592 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3593 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3595 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3596 check_closed_event!(&nodes[1], 1, ClosureReason::HolderForceClosed, false,
3597 [nodes[3].node.get_our_node_id()], 1000000);
3598 check_closed_broadcast(&nodes[1], 1, true);
3599 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3600 assert_eq!(bs_tx.len(), 1);
3602 mine_transaction(&nodes[3], &bs_tx[0]);
3603 check_added_monitors(&nodes[3], 1);
3604 check_closed_broadcast(&nodes[3], 1, true);
3605 check_closed_event!(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false,
3606 [nodes[1].node.get_our_node_id()], 1000000);
3608 nodes[3].node.claim_funds(payment_preimage);
3609 check_added_monitors(&nodes[3], 2);
3610 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3612 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3613 assert_eq!(ds_tx.len(), 1);
3614 check_spends!(&ds_tx[0], &bs_tx[0]);
3616 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3617 check_added_monitors(&nodes[1], 1);
3618 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3620 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3621 check_added_monitors(&nodes[1], 1);
3622 assert_eq!(bs_claims.len(), 1);
3623 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3624 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3625 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3626 } else { panic!(); }
3628 expect_payment_sent!(nodes[0], payment_preimage);
3630 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3631 assert_eq!(ds_claim_msgs.len(), 1);
3632 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3633 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3634 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3635 check_added_monitors(&nodes[2], 1);
3636 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3637 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3639 } else { panic!(); };
3641 assert_eq!(cs_claim_msgs.len(), 1);
3642 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3643 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3644 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3645 } else { panic!(); }
3647 expect_payment_path_successful!(nodes[0]);
3652 fn claim_from_closed_chan() {
3653 do_claim_from_closed_chan(true);
3654 do_claim_from_closed_chan(false);
3658 fn test_custom_tlvs_basic() {
3659 do_test_custom_tlvs(false, false, false);
3660 do_test_custom_tlvs(true, false, false);
3664 fn test_custom_tlvs_explicit_claim() {
3665 // Test that when receiving even custom TLVs the user must explicitly accept in case they
3667 do_test_custom_tlvs(false, true, false);
3668 do_test_custom_tlvs(false, true, true);
3671 fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) {
3672 let chanmon_cfgs = create_chanmon_cfgs(2);
3673 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3674 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None; 2]);
3675 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3677 create_announced_chan_between_nodes(&nodes, 0, 1);
3679 let amt_msat = 100_000;
3680 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat);
3681 let payment_id = PaymentId(our_payment_hash.0);
3682 let custom_tlvs = vec![
3683 (if even_tlvs { 5482373482 } else { 5482373483 }, vec![1, 2, 3, 4]),
3684 (5482373487, vec![0x42u8; 16]),
3686 let onion_fields = RecipientOnionFields {
3687 payment_secret: if spontaneous { None } else { Some(our_payment_secret) },
3688 payment_metadata: None,
3689 custom_tlvs: custom_tlvs.clone()
3692 nodes[0].node.send_spontaneous_payment(&route, Some(our_payment_preimage), onion_fields, payment_id).unwrap();
3694 nodes[0].node.send_payment_with_route(&route, our_payment_hash, onion_fields, payment_id).unwrap();
3696 check_added_monitors(&nodes[0], 1);
3698 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3699 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
3700 let mut payment_event = SendEvent::from_event(ev);
3702 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3703 check_added_monitors!(&nodes[1], 0);
3704 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3705 expect_pending_htlcs_forwardable!(nodes[1]);
3707 let events = nodes[1].node.get_and_clear_pending_events();
3708 assert_eq!(events.len(), 1);
3710 Event::PaymentClaimable { ref onion_fields, .. } => {
3711 assert_eq!(onion_fields.clone().unwrap().custom_tlvs().clone(), custom_tlvs);
3713 _ => panic!("Unexpected event"),
3716 match (known_tlvs, even_tlvs) {
3718 nodes[1].node.claim_funds_with_known_custom_tlvs(our_payment_preimage);
3719 let expected_total_fee_msat = pass_claimed_payment_along_route(&nodes[0], &[&[&nodes[1]]], &[0; 1], false, our_payment_preimage);
3720 expect_payment_sent!(&nodes[0], our_payment_preimage, Some(expected_total_fee_msat));
3723 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3726 nodes[1].node.claim_funds(our_payment_preimage);
3727 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3728 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], expected_destinations);
3729 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, our_payment_hash, PaymentFailureReason::RecipientRejected);
3735 fn test_retry_custom_tlvs() {
3736 // Test that custom TLVs are successfully sent on retries
3737 let chanmon_cfgs = create_chanmon_cfgs(3);
3738 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3739 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3740 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3742 create_announced_chan_between_nodes(&nodes, 0, 1);
3743 let (chan_2_update, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 2, 1);
3746 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3748 let amt_msat = 1_000_000;
3749 let (route, payment_hash, payment_preimage, payment_secret) =
3750 get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
3752 // Initiate the payment
3753 let payment_id = PaymentId(payment_hash.0);
3754 let mut route_params = route.route_params.clone().unwrap();
3756 let custom_tlvs = vec![((1 << 16) + 1, vec![0x42u8; 16])];
3757 let onion_fields = RecipientOnionFields::secret_only(payment_secret);
3758 let onion_fields = onion_fields.with_custom_tlvs(custom_tlvs.clone()).unwrap();
3760 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3761 nodes[0].node.send_payment(payment_hash, onion_fields,
3762 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3763 check_added_monitors!(nodes[0], 1); // one monitor per path
3765 // Add the HTLC along the first hop.
3766 let htlc_updates = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
3767 let msgs::CommitmentUpdate { update_add_htlcs, commitment_signed, .. } = htlc_updates;
3768 assert_eq!(update_add_htlcs.len(), 1);
3769 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_htlcs[0]);
3770 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
3772 // Attempt to forward the payment and complete the path's failure.
3773 expect_pending_htlcs_forwardable!(&nodes[1]);
3774 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1],
3775 vec![HTLCDestination::NextHopChannel {
3776 node_id: Some(nodes[2].node.get_our_node_id()),
3777 channel_id: chan_2_id
3779 check_added_monitors!(nodes[1], 1);
3781 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3782 let msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } = htlc_updates;
3783 assert_eq!(update_fail_htlcs.len(), 1);
3784 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3785 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
3787 let mut events = nodes[0].node.get_and_clear_pending_events();
3789 Event::PendingHTLCsForwardable { .. } => {},
3790 _ => panic!("Unexpected event")
3793 expect_payment_failed_conditions_event(events, payment_hash, false,
3794 PaymentFailedConditions::new().mpp_parts_remain());
3796 // Rebalance the channel so the retry of the payment can succeed.
3797 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3799 // Retry the payment and make sure it succeeds
3800 route_params.payment_params.previously_failed_channels.push(chan_2_update.contents.short_channel_id);
3801 nodes[0].router.expect_find_route(route_params, Ok(route));
3802 nodes[0].node.process_pending_htlc_forwards();
3803 check_added_monitors!(nodes[0], 1);
3804 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3805 assert_eq!(events.len(), 1);
3806 let payment_claimable = pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000,
3807 payment_hash, Some(payment_secret), events.pop().unwrap(), true, None).unwrap();
3808 match payment_claimable {
3809 Event::PaymentClaimable { onion_fields, .. } => {
3810 assert_eq!(onion_fields.unwrap().custom_tlvs(), &custom_tlvs);
3812 _ => panic!("Unexpected event"),
3814 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
3818 fn test_custom_tlvs_consistency() {
3819 let even_type_1 = 1 << 16;
3820 let odd_type_1 = (1 << 16)+ 1;
3821 let even_type_2 = (1 << 16) + 2;
3822 let odd_type_2 = (1 << 16) + 3;
3823 let value_1 = || vec![1, 2, 3, 4];
3824 let differing_value_1 = || vec![1, 2, 3, 5];
3825 let value_2 = || vec![42u8; 16];
3827 // Drop missing odd tlvs
3828 do_test_custom_tlvs_consistency(
3829 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3830 vec![(odd_type_1, value_1())],
3831 Some(vec![(odd_type_1, value_1())]),
3833 // Drop non-matching odd tlvs
3834 do_test_custom_tlvs_consistency(
3835 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3836 vec![(odd_type_1, differing_value_1()), (odd_type_2, value_2())],
3837 Some(vec![(odd_type_2, value_2())]),
3839 // Fail missing even tlvs
3840 do_test_custom_tlvs_consistency(
3841 vec![(odd_type_1, value_1()), (even_type_2, value_2())],
3842 vec![(odd_type_1, value_1())],
3845 // Fail non-matching even tlvs
3846 do_test_custom_tlvs_consistency(
3847 vec![(even_type_1, value_1()), (odd_type_2, value_2())],
3848 vec![(even_type_1, differing_value_1()), (odd_type_2, value_2())],
3853 fn do_test_custom_tlvs_consistency(first_tlvs: Vec<(u64, Vec<u8>)>, second_tlvs: Vec<(u64, Vec<u8>)>,
3854 expected_receive_tlvs: Option<Vec<(u64, Vec<u8>)>>) {
3856 let chanmon_cfgs = create_chanmon_cfgs(4);
3857 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3858 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3859 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3861 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
3862 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
3863 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
3864 let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
3866 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3867 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
3868 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
3869 assert_eq!(route.paths.len(), 2);
3870 route.paths.sort_by(|path_a, _| {
3871 // Sort the path so that the path through nodes[1] comes first
3872 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3873 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
3876 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
3877 let payment_id = PaymentId([42; 32]);
3878 let amt_msat = 15_000_000;
3881 let onion_fields = RecipientOnionFields {
3882 payment_secret: Some(our_payment_secret),
3883 payment_metadata: None,
3884 custom_tlvs: first_tlvs
3886 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
3887 onion_fields.clone(), payment_id, &route).unwrap();
3888 let cur_height = nodes[0].best_block_info().1;
3889 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
3890 onion_fields.clone(), amt_msat, cur_height, payment_id,
3891 &None, session_privs[0]).unwrap();
3892 check_added_monitors!(nodes[0], 1);
3895 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3896 assert_eq!(events.len(), 1);
3897 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, our_payment_hash,
3898 Some(our_payment_secret), events.pop().unwrap(), false, None);
3900 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
3903 let onion_fields = RecipientOnionFields {
3904 payment_secret: Some(our_payment_secret),
3905 payment_metadata: None,
3906 custom_tlvs: second_tlvs
3908 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
3909 onion_fields.clone(), amt_msat, cur_height, payment_id, &None, session_privs[1]).unwrap();
3910 check_added_monitors!(nodes[0], 1);
3913 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3914 assert_eq!(events.len(), 1);
3915 let payment_event = SendEvent::from_event(events.pop().unwrap());
3917 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3918 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
3920 expect_pending_htlcs_forwardable!(nodes[2]);
3921 check_added_monitors!(nodes[2], 1);
3923 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
3924 assert_eq!(events.len(), 1);
3925 let payment_event = SendEvent::from_event(events.pop().unwrap());
3927 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
3928 check_added_monitors!(nodes[3], 0);
3929 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
3931 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3932 nodes[3].node.process_pending_htlc_forwards();
3934 if let Some(expected_tlvs) = expected_receive_tlvs {
3935 // Claim and match expected
3936 let events = nodes[3].node.get_and_clear_pending_events();
3937 assert_eq!(events.len(), 1);
3939 Event::PaymentClaimable { ref onion_fields, .. } => {
3940 assert_eq!(onion_fields.clone().unwrap().custom_tlvs, expected_tlvs);
3942 _ => panic!("Unexpected event"),
3945 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]],
3946 false, our_payment_preimage);
3947 expect_payment_sent(&nodes[0], our_payment_preimage, Some(Some(2000)), true, true);
3950 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3951 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], expected_destinations);
3952 check_added_monitors!(nodes[3], 1);
3954 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
3955 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
3956 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
3958 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![
3959 HTLCDestination::NextHopChannel {
3960 node_id: Some(nodes[3].node.get_our_node_id()),
3961 channel_id: chan_2_3.2
3963 check_added_monitors!(nodes[2], 1);
3965 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
3966 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
3967 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
3969 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true,
3970 PaymentFailedConditions::new().mpp_parts_remain());
3974 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3975 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3976 // another results in the HTLC being rejected.
3978 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3979 // first of which we'll deliver and the second of which we'll fail and then re-send with
3980 // modified payment metadata, which will in turn result in it being failed by the recipient.
3981 let chanmon_cfgs = create_chanmon_cfgs(4);
3982 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3984 let new_chain_monitor;
3986 let mut config = test_default_channel_config();
3987 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3988 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3989 let nodes_0_deserialized;
3991 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3993 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3994 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3995 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3996 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3998 // Pay more than half of each channel's max, requiring MPP
3999 let amt_msat = 750_000_000;
4000 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
4001 let payment_id = PaymentId(payment_hash.0);
4002 let payment_metadata = vec![44, 49, 52, 142];
4004 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
4005 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
4006 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
4008 // Send the MPP payment, delivering the updated commitment state to nodes[1].
4009 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
4010 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata), custom_tlvs: vec![],
4011 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
4012 check_added_monitors!(nodes[0], 2);
4014 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
4015 assert_eq!(send_events.len(), 2);
4016 let first_send = SendEvent::from_event(send_events.pop().unwrap());
4017 let second_send = SendEvent::from_event(send_events.pop().unwrap());
4019 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
4020 (&first_send, &second_send)
4022 (&second_send, &first_send)
4024 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
4025 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
4027 expect_pending_htlcs_forwardable!(nodes[1]);
4028 check_added_monitors(&nodes[1], 1);
4029 let b_forward_ev = SendEvent::from_node(&nodes[1]);
4030 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
4031 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
4033 expect_pending_htlcs_forwardable!(nodes[3]);
4035 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
4036 // will result in nodes[2] failing the HTLC back.
4037 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4038 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
4040 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
4041 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
4043 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
4044 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
4045 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
4047 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
4048 assert_eq!(payment_fail_retryable_evs.len(), 2);
4049 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
4050 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
4052 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
4053 // stored for our payment.
4055 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
4058 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
4059 // the payment state.
4061 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
4062 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
4063 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
4064 persister, new_chain_monitor, nodes_0_deserialized);
4065 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4066 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
4068 let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
4069 reconnect_args.send_channel_ready = (true, true);
4070 reconnect_nodes(reconnect_args);
4072 // Create a new channel between C and D as A will refuse to retry on the existing one because
4074 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
4076 // Now retry the failed HTLC.
4077 nodes[0].node.process_pending_htlc_forwards();
4078 check_added_monitors(&nodes[0], 1);
4079 let as_resend = SendEvent::from_node(&nodes[0]);
4080 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
4081 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
4083 expect_pending_htlcs_forwardable!(nodes[2]);
4084 check_added_monitors(&nodes[2], 1);
4085 let cs_forward = SendEvent::from_node(&nodes[2]);
4086 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
4087 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
4089 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
4090 // the payment metadata was modified, failing only the one modified HTLC and retaining the
4093 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
4094 nodes[3].node.process_pending_htlc_forwards();
4095 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
4096 &[HTLCDestination::FailedPayment {payment_hash}]);
4097 nodes[3].node.process_pending_htlc_forwards();
4099 check_added_monitors(&nodes[3], 1);
4100 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
4102 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
4103 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
4104 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
4105 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
4107 expect_pending_htlcs_forwardable!(nodes[3]);
4108 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
4109 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
4114 fn test_payment_metadata_consistency() {
4115 do_test_payment_metadata_consistency(true, true);
4116 do_test_payment_metadata_consistency(true, false);
4117 do_test_payment_metadata_consistency(false, true);
4118 do_test_payment_metadata_consistency(false, false);