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};
15 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::sign::EntropySource;
17 use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason, PaymentPurpose};
18 use crate::ln::channel::{EXPIRE_PREV_CONFIG_TICKS, commit_tx_fee_msat, get_holder_selected_channel_reserve_satoshis, ANCHOR_OUTPUT_VALUE_SATOSHI};
19 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, RecentPaymentDetails, RecipientOnionFields, HTLCForwardInfo, PendingHTLCRouting, PendingAddHTLCInfo};
20 use crate::ln::features::{Bolt11InvoiceFeatures, ChannelTypeFeatures};
22 use crate::ln::types::{ChannelId, PaymentHash, PaymentSecret, PaymentPreimage};
23 use crate::ln::msgs::ChannelMessageHandler;
24 use crate::ln::onion_utils;
25 use crate::ln::outbound_payment::{IDEMPOTENCY_TIMEOUT_TICKS, Retry};
26 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
27 use crate::routing::router::{get_route, Path, PaymentParameters, Route, Router, RouteHint, RouteHintHop, RouteHop, RouteParameters, find_route};
28 use crate::routing::scoring::ChannelUsage;
29 use crate::util::config::UserConfig;
30 use crate::util::test_utils;
31 use crate::util::errors::APIError;
32 use crate::util::ser::Writeable;
33 use crate::util::string::UntrustedString;
35 use bitcoin::hashes::Hash;
36 use bitcoin::hashes::sha256::Hash as Sha256;
37 use bitcoin::network::Network;
38 use bitcoin::secp256k1::{Secp256k1, SecretKey};
40 use crate::prelude::*;
42 use crate::ln::functional_test_utils;
43 use crate::ln::functional_test_utils::*;
44 use crate::routing::gossip::NodeId;
46 #[cfg(feature = "std")]
48 crate::util::time::tests::SinceEpoch,
49 std::time::{SystemTime, Instant, Duration},
54 let chanmon_cfgs = create_chanmon_cfgs(4);
55 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
56 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
57 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
59 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
60 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
61 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
62 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
64 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
65 let path = route.paths[0].clone();
66 route.paths.push(path);
67 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
68 route.paths[0].hops[0].short_channel_id = chan_1_id;
69 route.paths[0].hops[1].short_channel_id = chan_3_id;
70 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
71 route.paths[1].hops[0].short_channel_id = chan_2_id;
72 route.paths[1].hops[1].short_channel_id = chan_4_id;
73 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
74 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
79 let chanmon_cfgs = create_chanmon_cfgs(4);
80 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
81 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
82 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
84 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
85 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
86 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
87 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
89 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
91 let amt_msat = 1_000_000;
92 let max_total_routing_fee_msat = 50_000;
93 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
94 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
95 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(
96 nodes[0], nodes[3], payment_params, amt_msat, Some(max_total_routing_fee_msat));
97 let path = route.paths[0].clone();
98 route.paths.push(path);
99 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
100 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
101 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
102 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
103 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
104 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
106 // Initiate the MPP payment.
107 let payment_id = PaymentId(payment_hash.0);
108 let mut route_params = route.route_params.clone().unwrap();
110 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
111 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
112 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
113 check_added_monitors!(nodes[0], 2); // one monitor per path
114 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
115 assert_eq!(events.len(), 2);
117 // Pass half of the payment along the success path.
118 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
119 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
121 // Add the HTLC along the first hop.
122 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
123 let send_event = SendEvent::from_event(fail_path_msgs_1);
124 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
125 commitment_signed_dance!(nodes[2], nodes[0], &send_event.commitment_msg, false);
127 // Attempt to forward the payment and complete the 2nd path's failure.
128 expect_pending_htlcs_forwardable!(&nodes[2]);
129 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 }]);
130 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
131 assert!(htlc_updates.update_add_htlcs.is_empty());
132 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
133 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
134 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
135 check_added_monitors!(nodes[2], 1);
136 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
137 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
138 let mut events = nodes[0].node.get_and_clear_pending_events();
140 Event::PendingHTLCsForwardable { .. } => {},
141 _ => panic!("Unexpected event")
144 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
146 // Rebalance the channel so the second half of the payment can succeed.
147 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
149 // Retry the second half of the payment and make sure it succeeds.
150 route.paths.remove(0);
151 route_params.final_value_msat = 1_000_000;
152 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
153 // Check the remaining max total routing fee for the second attempt is 50_000 - 1_000 msat fee
154 // used by the first path
155 route_params.max_total_routing_fee_msat = Some(max_total_routing_fee_msat - 1_000);
156 route.route_params = Some(route_params.clone());
157 nodes[0].router.expect_find_route(route_params, Ok(route));
158 nodes[0].node.process_pending_htlc_forwards();
159 check_added_monitors!(nodes[0], 1);
160 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
161 assert_eq!(events.len(), 1);
162 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
163 claim_payment_along_route(
164 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], payment_preimage)
169 fn mpp_retry_overpay() {
170 // We create an MPP scenario with two paths in which we need to overpay to reach
171 // htlc_minimum_msat. We then fail the overpaid path and check that on retry our
172 // max_total_routing_fee_msat only accounts for the path's fees, but not for the fees overpaid
173 // in the first attempt.
174 let chanmon_cfgs = create_chanmon_cfgs(4);
175 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
176 let mut user_config = test_default_channel_config();
177 user_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
178 let mut limited_config_1 = user_config.clone();
179 limited_config_1.channel_handshake_config.our_htlc_minimum_msat = 35_000_000;
180 let mut limited_config_2 = user_config.clone();
181 limited_config_2.channel_handshake_config.our_htlc_minimum_msat = 34_500_000;
182 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
183 &[Some(user_config), Some(limited_config_1), Some(limited_config_2), Some(user_config)]);
184 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
186 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 40_000, 0);
187 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 40_000, 0);
188 let (_chan_3_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 40_000, 0);
189 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes_with_value(&nodes, 3, 2, 40_000, 0);
191 let amt_msat = 70_000_000;
192 let max_total_routing_fee_msat = Some(1_000_000);
194 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
195 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
196 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(
197 nodes[0], nodes[3], payment_params, amt_msat, max_total_routing_fee_msat);
199 // Check we overpay on the second path which we're about to fail.
200 assert_eq!(chan_1_update.contents.fee_proportional_millionths, 0);
201 let overpaid_amount_1 = route.paths[0].fee_msat() as u32 - chan_1_update.contents.fee_base_msat;
202 assert_eq!(overpaid_amount_1, 0);
204 assert_eq!(chan_2_update.contents.fee_proportional_millionths, 0);
205 let overpaid_amount_2 = route.paths[1].fee_msat() as u32 - chan_2_update.contents.fee_base_msat;
207 let total_overpaid_amount = overpaid_amount_1 + overpaid_amount_2;
209 // Initiate the payment.
210 let payment_id = PaymentId(payment_hash.0);
211 let mut route_params = route.route_params.clone().unwrap();
213 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
214 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
215 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
216 check_added_monitors!(nodes[0], 2); // one monitor per path
217 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
218 assert_eq!(events.len(), 2);
220 // Pass half of the payment along the success path.
221 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
222 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, payment_hash,
223 Some(payment_secret), success_path_msgs, false, None);
225 // Add the HTLC along the first hop.
226 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
227 let send_event = SendEvent::from_event(fail_path_msgs_1);
228 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
229 commitment_signed_dance!(nodes[2], nodes[0], &send_event.commitment_msg, false);
231 // Attempt to forward the payment and complete the 2nd path's failure.
232 expect_pending_htlcs_forwardable!(&nodes[2]);
233 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[2],
234 vec![HTLCDestination::NextHopChannel {
235 node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_4_id
238 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
239 assert!(htlc_updates.update_add_htlcs.is_empty());
240 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
241 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
242 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
243 check_added_monitors!(nodes[2], 1);
244 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(),
245 &htlc_updates.update_fail_htlcs[0]);
246 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
247 let mut events = nodes[0].node.get_and_clear_pending_events();
249 Event::PendingHTLCsForwardable { .. } => {},
250 _ => panic!("Unexpected event")
253 expect_payment_failed_conditions_event(events, payment_hash, false,
254 PaymentFailedConditions::new().mpp_parts_remain());
256 // Rebalance the channel so the second half of the payment can succeed.
257 send_payment(&nodes[3], &vec!(&nodes[2])[..], 38_000_000);
259 // Retry the second half of the payment and make sure it succeeds.
260 let first_path_value = route.paths[0].final_value_msat();
261 assert_eq!(first_path_value, 36_000_000);
263 route.paths.remove(0);
264 route_params.final_value_msat -= first_path_value;
265 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
266 // Check the remaining max total routing fee for the second attempt accounts only for 1_000 msat
267 // base fee, but not for overpaid value of the first try.
268 route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 1000);
270 route.route_params = Some(route_params.clone());
271 nodes[0].router.expect_find_route(route_params, Ok(route));
272 nodes[0].node.process_pending_htlc_forwards();
274 check_added_monitors!(nodes[0], 1);
275 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
276 assert_eq!(events.len(), 1);
277 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], amt_msat, payment_hash,
278 Some(payment_secret), events.pop().unwrap(), true, None);
280 // Can't use claim_payment_along_route as it doesn't support overpayment, so we break out the
281 // individual steps here.
282 nodes[3].node.claim_funds(payment_preimage);
283 let extra_fees = vec![0, total_overpaid_amount];
284 let expected_route = &[&[&nodes[1], &nodes[3]][..], &[&nodes[2], &nodes[3]][..]];
285 let args = ClaimAlongRouteArgs::new(&nodes[0], &expected_route[..], payment_preimage)
286 .with_expected_min_htlc_overpay(extra_fees);
287 let expected_total_fee_msat = pass_claimed_payment_along_route(args);
288 expect_payment_sent!(&nodes[0], payment_preimage, Some(expected_total_fee_msat));
291 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
292 let chanmon_cfgs = create_chanmon_cfgs(4);
293 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
294 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
295 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
297 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
298 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
299 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
300 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
302 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
303 let path = route.paths[0].clone();
304 route.paths.push(path);
305 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
306 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
307 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
308 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
309 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
310 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
312 // Initiate the MPP payment.
313 nodes[0].node.send_payment_with_route(&route, payment_hash,
314 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
315 check_added_monitors!(nodes[0], 2); // one monitor per path
316 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
317 assert_eq!(events.len(), 2);
319 // Pass half of the payment along the first path.
320 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
321 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
323 if send_partial_mpp {
324 // Time out the partial MPP
325 for _ in 0..MPP_TIMEOUT_TICKS {
326 nodes[3].node.timer_tick_occurred();
329 // Failed HTLC from node 3 -> 1
330 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
331 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
332 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
333 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
334 check_added_monitors!(nodes[3], 1);
335 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
337 // Failed HTLC from node 1 -> 0
338 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 }]);
339 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
340 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
341 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
342 check_added_monitors!(nodes[1], 1);
343 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
345 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
347 // Pass half of the payment along the second path.
348 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
349 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
351 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
352 for _ in 0..MPP_TIMEOUT_TICKS {
353 nodes[3].node.timer_tick_occurred();
356 claim_payment_along_route(
357 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], payment_preimage)
363 fn mpp_receive_timeout() {
364 do_mpp_receive_timeout(true);
365 do_mpp_receive_timeout(false);
369 fn test_keysend_payments() {
370 do_test_keysend_payments(false, false);
371 do_test_keysend_payments(false, true);
372 do_test_keysend_payments(true, false);
373 do_test_keysend_payments(true, true);
376 fn do_test_keysend_payments(public_node: bool, with_retry: bool) {
377 let chanmon_cfgs = create_chanmon_cfgs(2);
378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
380 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
383 create_announced_chan_between_nodes(&nodes, 0, 1);
385 create_chan_between_nodes(&nodes[0], &nodes[1]);
387 let payer_pubkey = nodes[0].node.get_our_node_id();
388 let payee_pubkey = nodes[1].node.get_our_node_id();
389 let route_params = RouteParameters::from_payment_params_and_value(
390 PaymentParameters::for_keysend(payee_pubkey, 40, false), 10000);
392 let network_graph = nodes[0].network_graph;
393 let channels = nodes[0].node.list_usable_channels();
394 let first_hops = channels.iter().collect::<Vec<_>>();
395 let first_hops = if public_node { None } else { Some(first_hops.as_slice()) };
397 let scorer = test_utils::TestScorer::new();
398 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
399 let route = find_route(
400 &payer_pubkey, &route_params, &network_graph, first_hops,
401 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
405 let test_preimage = PaymentPreimage([42; 32]);
407 nodes[0].node.send_spontaneous_payment_with_retry(Some(test_preimage),
408 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0),
409 route_params, Retry::Attempts(1)).unwrap()
411 nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
412 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap()
415 check_added_monitors!(nodes[0], 1);
416 let send_event = SendEvent::from_node(&nodes[0]);
417 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
418 do_commitment_signed_dance(&nodes[1], &nodes[0], &send_event.commitment_msg, false, false);
419 expect_pending_htlcs_forwardable!(nodes[1]);
420 // Previously, a refactor caused us to stop including the payment preimage in the onion which
421 // is sent as a part of keysend payments. Thus, to be extra careful here, we scope the preimage
422 // above to demonstrate that we have no way to get the preimage at this point except by
423 // extracting it from the onion nodes[1] received.
424 let event = nodes[1].node.get_and_clear_pending_events();
425 assert_eq!(event.len(), 1);
426 if let Event::PaymentClaimable { purpose: PaymentPurpose::SpontaneousPayment(preimage), .. } = event[0] {
427 claim_payment(&nodes[0], &[&nodes[1]], preimage);
432 fn test_mpp_keysend() {
433 let mut mpp_keysend_config = test_default_channel_config();
434 mpp_keysend_config.accept_mpp_keysend = true;
435 let chanmon_cfgs = create_chanmon_cfgs(4);
436 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
437 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
438 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
440 create_announced_chan_between_nodes(&nodes, 0, 1);
441 create_announced_chan_between_nodes(&nodes, 0, 2);
442 create_announced_chan_between_nodes(&nodes, 1, 3);
443 create_announced_chan_between_nodes(&nodes, 2, 3);
444 let network_graph = nodes[0].network_graph;
446 let payer_pubkey = nodes[0].node.get_our_node_id();
447 let payee_pubkey = nodes[3].node.get_our_node_id();
448 let recv_value = 15_000_000;
449 let route_params = RouteParameters::from_payment_params_and_value(
450 PaymentParameters::for_keysend(payee_pubkey, 40, true), recv_value);
451 let scorer = test_utils::TestScorer::new();
452 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
453 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger,
454 &scorer, &Default::default(), &random_seed_bytes).unwrap();
456 let payment_preimage = PaymentPreimage([42; 32]);
457 let payment_secret = PaymentSecret(payment_preimage.0);
458 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
459 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_preimage.0)).unwrap();
460 check_added_monitors!(nodes[0], 2);
462 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
463 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
464 assert_eq!(events.len(), 2);
466 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
467 pass_along_path(&nodes[0], expected_route[0], recv_value, payment_hash.clone(),
468 Some(payment_secret), ev.clone(), false, Some(payment_preimage));
470 let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
471 pass_along_path(&nodes[0], expected_route[1], recv_value, payment_hash.clone(),
472 Some(payment_secret), ev.clone(), true, Some(payment_preimage));
473 claim_payment_along_route(
474 ClaimAlongRouteArgs::new(&nodes[0], expected_route, payment_preimage)
479 fn test_reject_mpp_keysend_htlc() {
480 // This test enforces that we reject MPP keysend HTLCs if our config states we don't support
481 // MPP keysend. When receiving a payment, if we don't support MPP keysend we'll reject the
482 // payment if it's keysend and has a payment secret, never reaching our payment validation
483 // logic. To check that we enforce rejecting MPP keysends in our payment logic, here we send
484 // keysend payments without payment secrets, then modify them by adding payment secrets in the
485 // final node in between receiving the HTLCs and actually processing them.
486 let mut reject_mpp_keysend_cfg = test_default_channel_config();
487 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
489 let chanmon_cfgs = create_chanmon_cfgs(4);
490 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
491 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(reject_mpp_keysend_cfg)]);
492 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
493 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
494 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
495 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
496 let (update_a, _, chan_4_channel_id, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
497 let chan_4_id = update_a.contents.short_channel_id;
499 let (mut route, payment_hash, payment_preimage, _) = get_route_and_payment_hash!(nodes[0], nodes[3], amount);
501 // Pay along nodes[1]
502 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
503 route.paths[0].hops[0].short_channel_id = chan_1_id;
504 route.paths[0].hops[1].short_channel_id = chan_3_id;
506 let payment_id_0 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
507 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_0).unwrap();
508 check_added_monitors!(nodes[0], 1);
510 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
511 let update_add_0 = update_0.update_add_htlcs[0].clone();
512 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
513 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
514 expect_pending_htlcs_forwardable!(nodes[1]);
516 check_added_monitors!(&nodes[1], 1);
517 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[3].node.get_our_node_id());
518 let update_add_1 = update_1.update_add_htlcs[0].clone();
519 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
520 commitment_signed_dance!(nodes[3], nodes[1], update_1.commitment_signed, false, true);
522 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
523 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
524 for f in pending_forwards.iter_mut() {
526 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
527 match forward_info.routing {
528 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
529 *payment_data = Some(msgs::FinalOnionHopData {
530 payment_secret: PaymentSecret([42; 32]),
531 total_msat: amount * 2,
534 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
541 expect_pending_htlcs_forwardable!(nodes[3]);
543 // Pay along nodes[2]
544 route.paths[0].hops[0].pubkey = nodes[2].node.get_our_node_id();
545 route.paths[0].hops[0].short_channel_id = chan_2_id;
546 route.paths[0].hops[1].short_channel_id = chan_4_id;
548 let payment_id_1 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
549 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
550 check_added_monitors!(nodes[0], 1);
552 let update_2 = get_htlc_update_msgs!(nodes[0], nodes[2].node.get_our_node_id());
553 let update_add_2 = update_2.update_add_htlcs[0].clone();
554 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_2);
555 commitment_signed_dance!(nodes[2], nodes[0], &update_2.commitment_signed, false, true);
556 expect_pending_htlcs_forwardable!(nodes[2]);
558 check_added_monitors!(&nodes[2], 1);
559 let update_3 = get_htlc_update_msgs!(nodes[2], nodes[3].node.get_our_node_id());
560 let update_add_3 = update_3.update_add_htlcs[0].clone();
561 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &update_add_3);
562 commitment_signed_dance!(nodes[3], nodes[2], update_3.commitment_signed, false, true);
564 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
565 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
566 for f in pending_forwards.iter_mut() {
568 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
569 match forward_info.routing {
570 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
571 *payment_data = Some(msgs::FinalOnionHopData {
572 payment_secret: PaymentSecret([42; 32]),
573 total_msat: amount * 2,
576 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
583 expect_pending_htlcs_forwardable!(nodes[3]);
584 check_added_monitors!(nodes[3], 1);
586 // Fail back along nodes[2]
587 let update_fail_0 = get_htlc_update_msgs!(&nodes[3], &nodes[2].node.get_our_node_id());
588 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &update_fail_0.update_fail_htlcs[0]);
589 commitment_signed_dance!(nodes[2], nodes[3], update_fail_0.commitment_signed, false);
590 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 }]);
591 check_added_monitors!(nodes[2], 1);
593 let update_fail_1 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
594 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_1.update_fail_htlcs[0]);
595 commitment_signed_dance!(nodes[0], nodes[2], update_fail_1.commitment_signed, false);
597 expect_payment_failed_conditions(&nodes[0], payment_hash, true, PaymentFailedConditions::new());
598 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
603 fn no_pending_leak_on_initial_send_failure() {
604 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
605 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
606 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
607 // pending payment forever and never time it out.
608 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
609 // try, and then check that no pending payment is being tracked.
610 let chanmon_cfgs = create_chanmon_cfgs(2);
611 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
612 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
613 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
615 create_announced_chan_between_nodes(&nodes, 0, 1);
617 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
619 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
620 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
622 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
623 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
624 ), true, APIError::ChannelUnavailable { ref err },
625 assert_eq!(err, "Peer for first hop currently disconnected"));
627 assert!(!nodes[0].node.has_pending_payments());
630 fn do_retry_with_no_persist(confirm_before_reload: bool) {
631 // If we send a pending payment and `send_payment` returns success, we should always either
632 // return a payment failure event or a payment success event, and on failure the payment should
635 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
636 // always persisted asynchronously), the ChannelManager has to reload some payment data from
637 // ChannelMonitor(s) in some cases. This tests that reloading.
639 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
640 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
641 // which has separate codepaths for "commitment transaction already confirmed" and not.
642 let chanmon_cfgs = create_chanmon_cfgs(3);
643 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
645 let new_chain_monitor;
646 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
647 let nodes_0_deserialized;
648 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
650 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
651 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
653 // Serialize the ChannelManager prior to sending payments
654 let nodes_0_serialized = nodes[0].node.encode();
656 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
658 let amt_msat = 1_000_000;
659 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
660 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
661 let route_params = route.route_params.unwrap().clone();
662 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
663 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
664 check_added_monitors!(nodes[0], 1);
666 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
667 assert_eq!(events.len(), 1);
668 let payment_event = SendEvent::from_event(events.pop().unwrap());
669 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
671 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
672 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
673 // which would prevent retry.
674 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
675 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
677 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
678 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
679 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
680 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
682 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
684 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
685 if confirm_before_reload {
686 mine_transaction(&nodes[0], &as_commitment_tx);
687 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
690 // The ChannelMonitor should always be the latest version, as we're required to persist it
691 // during the `commitment_signed_dance!()`.
692 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
693 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
695 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
696 // force-close the channel.
697 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
698 assert!(nodes[0].node.list_channels().is_empty());
699 assert!(nodes[0].node.has_pending_payments());
700 nodes[0].node.timer_tick_occurred();
701 if !confirm_before_reload {
702 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
703 assert_eq!(as_broadcasted_txn.len(), 1);
704 assert_eq!(as_broadcasted_txn[0].txid(), as_commitment_tx.txid());
706 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
708 check_added_monitors!(nodes[0], 1);
710 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
711 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
712 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
714 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
716 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
717 // error, as the channel has hit the chain.
718 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
719 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
721 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
722 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
723 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
724 assert_eq!(as_err.len(), 2);
726 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
727 assert_eq!(node_id, nodes[1].node.get_our_node_id());
728 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
729 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 {}",
730 &nodes[1].node.get_our_node_id())) }, [nodes[0].node.get_our_node_id()], 100000);
731 check_added_monitors!(nodes[1], 1);
732 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
734 _ => panic!("Unexpected event"),
736 check_closed_broadcast!(nodes[1], false);
738 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
739 // we close in a moment.
740 nodes[2].node.claim_funds(payment_preimage_1);
741 check_added_monitors!(nodes[2], 1);
742 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
744 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
745 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
746 check_added_monitors!(nodes[1], 1);
747 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
748 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, true, false);
750 if confirm_before_reload {
751 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
752 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
755 // Create a new channel on which to retry the payment before we fail the payment via the
756 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
757 // connecting several blocks while creating the channel (implying time has passed).
758 create_announced_chan_between_nodes(&nodes, 0, 1);
759 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
761 mine_transaction(&nodes[1], &as_commitment_tx);
762 let bs_htlc_claim_txn = {
763 let mut txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
764 assert_eq!(txn.len(), 2);
765 check_spends!(txn[0], funding_tx);
766 check_spends!(txn[1], as_commitment_tx);
770 if !confirm_before_reload {
771 mine_transaction(&nodes[0], &as_commitment_tx);
772 let txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
773 assert_eq!(txn.len(), 1);
774 assert_eq!(txn[0].txid(), as_commitment_tx.txid());
776 mine_transaction(&nodes[0], &bs_htlc_claim_txn);
777 expect_payment_sent(&nodes[0], payment_preimage_1, None, true, false);
778 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
779 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
780 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
781 assert_eq!(txn.len(), 2);
782 (txn.remove(0), txn.remove(0))
784 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
785 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
786 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn.input[0].previous_output {
787 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
789 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
791 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
792 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
794 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
795 // reloaded) via a route over the new channel, which work without issue and eventually be
796 // received and claimed at the recipient just like any other payment.
797 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
799 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
800 // and not the original fee. We also update node[1]'s relevant config as
801 // do_claim_payment_along_route expects us to never overpay.
803 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
804 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
805 .unwrap().lock().unwrap();
806 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
807 let mut new_config = channel.context().config();
808 new_config.forwarding_fee_base_msat += 100_000;
809 channel.context_mut().update_config(&new_config);
810 new_route.paths[0].hops[0].fee_msat += 100_000;
813 // Force expiration of the channel's previous config.
814 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
815 nodes[1].node.timer_tick_occurred();
818 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
819 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
820 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
821 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
822 check_added_monitors!(nodes[0], 1);
823 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
824 assert_eq!(events.len(), 1);
825 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
826 do_claim_payment_along_route(
827 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[2]]], payment_preimage)
829 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
833 fn retry_with_no_persist() {
834 do_retry_with_no_persist(true);
835 do_retry_with_no_persist(false);
838 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
839 // Test that an off-chain completed payment is not retryable on restart. This was previously
840 // broken for dust payments, but we test for both dust and non-dust payments.
842 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
844 let chanmon_cfgs = create_chanmon_cfgs(3);
845 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
847 let mut manually_accept_config = test_default_channel_config();
848 manually_accept_config.manually_accept_inbound_channels = true;
851 let first_new_chain_monitor;
852 let second_persister;
853 let second_new_chain_monitor;
855 let third_new_chain_monitor;
857 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
858 let first_nodes_0_deserialized;
859 let second_nodes_0_deserialized;
860 let third_nodes_0_deserialized;
862 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
864 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
865 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
866 confirm_transaction(&nodes[0], &funding_tx);
867 confirm_transaction(&nodes[1], &funding_tx);
868 // Ignore the announcement_signatures messages
869 nodes[0].node.get_and_clear_pending_msg_events();
870 nodes[1].node.get_and_clear_pending_msg_events();
871 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
873 // Serialize the ChannelManager prior to sending payments
874 let mut nodes_0_serialized = nodes[0].node.encode();
876 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
877 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 });
879 // The ChannelMonitor should always be the latest version, as we're required to persist it
880 // during the `commitment_signed_dance!()`.
881 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
883 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);
884 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
886 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
887 // force-close the channel.
888 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
889 nodes[0].node.timer_tick_occurred();
890 assert!(nodes[0].node.list_channels().is_empty());
891 assert!(nodes[0].node.has_pending_payments());
892 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
893 check_added_monitors!(nodes[0], 1);
895 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
896 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
898 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
900 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
901 // error, as the channel has hit the chain.
902 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
903 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
905 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
906 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
907 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
908 assert_eq!(as_err.len(), 2);
909 let bs_commitment_tx;
911 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
912 assert_eq!(node_id, nodes[1].node.get_our_node_id());
913 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
914 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())) }
915 , [nodes[0].node.get_our_node_id()], 100000);
916 check_added_monitors!(nodes[1], 1);
917 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
919 _ => panic!("Unexpected event"),
921 check_closed_broadcast!(nodes[1], false);
923 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
924 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
925 // incoming HTLCs with the same payment hash later.
926 nodes[2].node.fail_htlc_backwards(&payment_hash);
927 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
928 check_added_monitors!(nodes[2], 1);
930 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
931 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
932 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
933 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
934 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
936 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
937 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
938 // after the commitment transaction, so always connect the commitment transaction.
939 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
940 if nodes[0].connect_style.borrow().updates_best_block_first() {
941 let _ = nodes[0].tx_broadcaster.txn_broadcast();
943 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
945 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
946 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
947 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
948 assert_eq!(as_htlc_timeout.len(), 1);
949 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
951 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
952 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
954 if nodes[0].connect_style.borrow().updates_best_block_first() {
955 let _ = nodes[0].tx_broadcaster.txn_broadcast();
958 // Create a new channel on which to retry the payment before we fail the payment via the
959 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
960 // connecting several blocks while creating the channel (implying time has passed).
961 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
962 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
963 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
965 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
966 // confirming, we will fail as it's considered still-pending...
967 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
968 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
969 Err(PaymentSendFailure::DuplicatePayment) => {},
970 _ => panic!("Unexpected error")
972 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
974 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
975 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
976 // (which should also still work).
977 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
978 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
979 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
981 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
982 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
983 nodes_0_serialized = nodes[0].node.encode();
985 // After the payment failed, we're free to send it again.
986 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
987 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
988 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
990 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);
991 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
993 nodes[0].node.test_process_background_events();
994 check_added_monitors(&nodes[0], 1);
996 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
997 reconnect_args.send_channel_ready = (true, true);
998 reconnect_nodes(reconnect_args);
1000 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
1001 // the payment is not (spuriously) listed as still pending.
1002 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
1003 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
1004 check_added_monitors!(nodes[0], 1);
1005 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
1006 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1008 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
1009 Err(PaymentSendFailure::DuplicatePayment) => {},
1010 _ => panic!("Unexpected error")
1012 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1014 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1015 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
1016 nodes_0_serialized = nodes[0].node.encode();
1018 // Check that after reload we can send the payment again (though we shouldn't, since it was
1019 // claimed previously).
1020 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);
1021 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
1023 nodes[0].node.test_process_background_events();
1024 check_added_monitors(&nodes[0], 1);
1026 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1028 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
1029 Err(PaymentSendFailure::DuplicatePayment) => {},
1030 _ => panic!("Unexpected error")
1032 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1036 fn test_completed_payment_not_retryable_on_reload() {
1037 do_test_completed_payment_not_retryable_on_reload(true);
1038 do_test_completed_payment_not_retryable_on_reload(false);
1041 fn do_test_dup_htlc_onchain_doesnt_fail_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
1042 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
1043 // dropped. From there, the ChannelManager relies on the ChannelMonitor having a copy of the
1044 // relevant fail-/claim-back data and processes the HTLC fail/claim when the ChannelMonitor tells
1047 // If, due to an on-chain event, an HTLC is failed/claimed, we provide the
1048 // ChannelManager with the HTLC event without waiting for ChannelMonitor persistence.
1049 // This might generate duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event) on reload.
1050 let chanmon_cfgs = create_chanmon_cfgs(2);
1051 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1053 let new_chain_monitor;
1054 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1055 let nodes_0_deserialized;
1056 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1058 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
1059 let error_message = "Channel force-closed";
1061 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
1063 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
1064 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id(), error_message.to_string()).unwrap();
1065 check_closed_broadcast!(nodes[0], true);
1066 check_added_monitors!(nodes[0], 1);
1067 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, [nodes[1].node.get_our_node_id()], 100000);
1069 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1070 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
1072 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
1073 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
1074 let (commitment_tx, htlc_timeout_tx) = {
1075 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
1076 assert_eq!(txn.len(), 2);
1077 check_spends!(txn[0], funding_tx);
1078 check_spends!(txn[1], txn[0]);
1079 (txn.remove(0), txn.remove(0))
1082 nodes[1].node.claim_funds(payment_preimage);
1083 check_added_monitors!(nodes[1], 1);
1084 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
1086 mine_transaction(&nodes[1], &commitment_tx);
1087 check_closed_broadcast!(nodes[1], true);
1088 check_added_monitors!(nodes[1], 1);
1089 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
1090 let htlc_success_tx = {
1091 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
1092 assert_eq!(txn.len(), 1);
1093 check_spends!(txn[0], commitment_tx);
1097 mine_transaction(&nodes[0], &commitment_tx);
1099 if confirm_commitment_tx {
1100 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
1103 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { vec![htlc_timeout_tx] } else { vec![htlc_success_tx] });
1105 if payment_timeout {
1106 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
1107 connect_block(&nodes[0], &claim_block);
1108 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
1111 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
1112 // returning InProgress. This should cause the claim event to never make its way to the
1114 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
1116 if payment_timeout {
1117 connect_blocks(&nodes[0], 1);
1119 connect_block(&nodes[0], &claim_block);
1122 // Note that we skip persisting ChannelMonitors. We should still be generating the payment sent
1123 // event without ChannelMonitor persistence. If we reset to a previous state on reload, the block
1124 // should be replayed and we'll regenerate the event.
1126 // If we persist the ChannelManager here, we should get the PaymentSent event after
1128 let mut chan_manager_serialized = Vec::new();
1129 if !persist_manager_post_event {
1130 chan_manager_serialized = nodes[0].node.encode();
1133 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1134 if payment_timeout {
1135 expect_payment_failed!(nodes[0], payment_hash, false);
1137 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1140 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
1142 if persist_manager_post_event {
1143 chan_manager_serialized = nodes[0].node.encode();
1146 // Now reload nodes[0]...
1147 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
1149 if persist_manager_post_event {
1150 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1151 } else if payment_timeout {
1152 expect_payment_failed!(nodes[0], payment_hash, false);
1154 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1157 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
1158 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
1159 // payment events should kick in, leaving us with no pending events here.
1160 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
1161 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
1162 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1163 check_added_monitors(&nodes[0], 1);
1167 fn test_dup_htlc_onchain_doesnt_fail_on_reload() {
1168 do_test_dup_htlc_onchain_doesnt_fail_on_reload(true, true, true);
1169 do_test_dup_htlc_onchain_doesnt_fail_on_reload(true, true, false);
1170 do_test_dup_htlc_onchain_doesnt_fail_on_reload(true, false, false);
1171 do_test_dup_htlc_onchain_doesnt_fail_on_reload(false, true, true);
1172 do_test_dup_htlc_onchain_doesnt_fail_on_reload(false, true, false);
1173 do_test_dup_htlc_onchain_doesnt_fail_on_reload(false, false, false);
1177 fn test_fulfill_restart_failure() {
1178 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
1179 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
1180 // again, or fail it, giving us free money.
1182 // Of course probably they won't fail it and give us free money, but because we have code to
1183 // handle it, we should test the logic for it anyway. We do that here.
1184 let chanmon_cfgs = create_chanmon_cfgs(2);
1185 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1187 let new_chain_monitor;
1188 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1189 let nodes_1_deserialized;
1190 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1192 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1193 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
1195 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
1196 // pre-fulfill, which we do by serializing it here.
1197 let chan_manager_serialized = nodes[1].node.encode();
1198 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1200 nodes[1].node.claim_funds(payment_preimage);
1201 check_added_monitors!(nodes[1], 1);
1202 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1204 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1205 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1206 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
1208 // Now reload nodes[1]...
1209 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1211 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1212 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1214 nodes[1].node.fail_htlc_backwards(&payment_hash);
1215 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1216 check_added_monitors!(nodes[1], 1);
1217 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1218 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1219 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1220 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1221 // it had already considered the payment fulfilled, and now they just got free money.
1222 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1226 fn get_ldk_payment_preimage() {
1227 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1228 let chanmon_cfgs = create_chanmon_cfgs(2);
1229 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1230 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1231 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1232 create_announced_chan_between_nodes(&nodes, 0, 1);
1234 let amt_msat = 60_000;
1235 let expiry_secs = 60 * 60;
1236 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1238 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1239 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
1240 let scorer = test_utils::TestScorer::new();
1241 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1242 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1243 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
1244 let route = get_route( &nodes[0].node.get_our_node_id(), &route_params,
1245 &nodes[0].network_graph.read_only(),
1246 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()), nodes[0].logger,
1247 &scorer, &Default::default(), &random_seed_bytes).unwrap();
1248 nodes[0].node.send_payment_with_route(&route, payment_hash,
1249 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1250 check_added_monitors!(nodes[0], 1);
1252 // Make sure to use `get_payment_preimage`
1253 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1254 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1255 assert_eq!(events.len(), 1);
1256 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1257 claim_payment_along_route(
1258 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1]]], payment_preimage)
1263 fn sent_probe_is_probe_of_sending_node() {
1264 let chanmon_cfgs = create_chanmon_cfgs(3);
1265 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1266 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1267 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1269 create_announced_chan_between_nodes(&nodes, 0, 1);
1270 create_announced_chan_between_nodes(&nodes, 1, 2);
1272 // First check we refuse to build a single-hop probe
1273 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1274 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1276 // Then build an actual two-hop probing path
1277 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1279 match nodes[0].node.send_probe(route.paths[0].clone()) {
1280 Ok((payment_hash, payment_id)) => {
1281 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1282 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1283 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1288 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1289 check_added_monitors!(nodes[0], 1);
1293 fn successful_probe_yields_event() {
1294 let chanmon_cfgs = create_chanmon_cfgs(3);
1295 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1296 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1297 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1299 create_announced_chan_between_nodes(&nodes, 0, 1);
1300 create_announced_chan_between_nodes(&nodes, 1, 2);
1302 let recv_value = 100_000;
1303 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], recv_value);
1305 let res = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1307 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[2]]];
1309 send_probe_along_route(&nodes[0], expected_route);
1311 expect_probe_successful_events(&nodes[0], vec![res]);
1313 assert!(!nodes[0].node.has_pending_payments());
1317 fn failed_probe_yields_event() {
1318 let chanmon_cfgs = create_chanmon_cfgs(3);
1319 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1320 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1321 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1323 create_announced_chan_between_nodes(&nodes, 0, 1);
1324 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1326 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1328 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 9_998_000);
1330 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1332 // node[0] -- update_add_htlcs -> node[1]
1333 check_added_monitors!(nodes[0], 1);
1334 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1335 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1336 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1337 check_added_monitors!(nodes[1], 0);
1338 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1339 expect_pending_htlcs_forwardable!(nodes[1]);
1341 // node[0] <- update_fail_htlcs -- node[1]
1342 check_added_monitors!(nodes[1], 1);
1343 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1344 // Skip the PendingHTLCsForwardable event
1345 let _events = nodes[1].node.get_and_clear_pending_events();
1346 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1347 check_added_monitors!(nodes[0], 0);
1348 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1350 let mut events = nodes[0].node.get_and_clear_pending_events();
1351 assert_eq!(events.len(), 1);
1352 match events.drain(..).next().unwrap() {
1353 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1354 assert_eq!(payment_id, ev_pid);
1355 assert_eq!(payment_hash, ev_ph);
1359 assert!(!nodes[0].node.has_pending_payments());
1363 fn onchain_failed_probe_yields_event() {
1364 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1366 let chanmon_cfgs = create_chanmon_cfgs(3);
1367 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1368 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1369 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1371 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1372 create_announced_chan_between_nodes(&nodes, 1, 2);
1374 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1376 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1377 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 1_000);
1378 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1380 // node[0] -- update_add_htlcs -> node[1]
1381 check_added_monitors!(nodes[0], 1);
1382 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1383 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1384 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1385 check_added_monitors!(nodes[1], 0);
1386 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1387 expect_pending_htlcs_forwardable!(nodes[1]);
1389 check_added_monitors!(nodes[1], 1);
1390 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1392 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1393 // Node A, which after 6 confirmations should result in a probe failure event.
1394 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1395 confirm_transaction(&nodes[0], &bs_txn[0]);
1396 check_closed_broadcast!(&nodes[0], true);
1397 check_added_monitors!(nodes[0], 1);
1399 let mut events = nodes[0].node.get_and_clear_pending_events();
1400 assert_eq!(events.len(), 2);
1401 let mut found_probe_failed = false;
1402 for event in events.drain(..) {
1404 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1405 assert_eq!(payment_id, ev_pid);
1406 assert_eq!(payment_hash, ev_ph);
1407 found_probe_failed = true;
1409 Event::ChannelClosed { .. } => {},
1413 assert!(found_probe_failed);
1414 assert!(!nodes[0].node.has_pending_payments());
1418 fn preflight_probes_yield_event_skip_private_hop() {
1419 let chanmon_cfgs = create_chanmon_cfgs(5);
1420 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1422 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1423 let mut no_htlc_limit_config = test_default_channel_config();
1424 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1426 let user_configs = std::iter::repeat(no_htlc_limit_config).take(5).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1427 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &user_configs);
1428 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1430 // Setup channel topology:
1431 // N0 -(1M:0)- N1 -(1M:0)- N2 -(70k:0)- N3 -(50k:0)- N4
1433 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1434 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
1435 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 70_000, 0);
1436 create_unannounced_chan_between_nodes_with_value(&nodes, 3, 4, 50_000, 0);
1438 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1439 invoice_features.set_basic_mpp_optional();
1441 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
1442 .with_bolt11_features(invoice_features).unwrap();
1444 let recv_value = 50_000_000;
1445 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1446 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1448 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[2], &nodes[3]]];
1450 assert_eq!(res.len(), expected_route.len());
1452 send_probe_along_route(&nodes[0], expected_route);
1454 expect_probe_successful_events(&nodes[0], res.clone());
1456 assert!(!nodes[0].node.has_pending_payments());
1460 fn preflight_probes_yield_event() {
1461 let chanmon_cfgs = create_chanmon_cfgs(4);
1462 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1464 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1465 let mut no_htlc_limit_config = test_default_channel_config();
1466 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1468 let user_configs = std::iter::repeat(no_htlc_limit_config).take(4).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1469 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &user_configs);
1470 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1472 // Setup channel topology:
1473 // (1M:0)- N1 -(30k:0)
1477 // (1M:0)- N2 -(70k:0)
1479 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1480 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1481 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 30_000, 0);
1482 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 70_000, 0);
1484 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1485 invoice_features.set_basic_mpp_optional();
1487 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
1488 .with_bolt11_features(invoice_features).unwrap();
1490 let recv_value = 50_000_000;
1491 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1492 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1494 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
1496 assert_eq!(res.len(), expected_route.len());
1498 send_probe_along_route(&nodes[0], expected_route);
1500 expect_probe_successful_events(&nodes[0], res.clone());
1502 assert!(!nodes[0].node.has_pending_payments());
1506 fn preflight_probes_yield_event_and_skip() {
1507 let chanmon_cfgs = create_chanmon_cfgs(5);
1508 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1510 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1511 let mut no_htlc_limit_config = test_default_channel_config();
1512 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1514 let user_configs = std::iter::repeat(no_htlc_limit_config).take(5).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1515 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &user_configs);
1516 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1518 // Setup channel topology:
1519 // (30k:0)- N2 -(1M:0)
1521 // N0 -(100k:0)-> N1 N4
1523 // (70k:0)- N3 -(1M:0)
1525 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1526 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 30_000, 0);
1527 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 70_000, 0);
1528 create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 1_000_000, 0);
1529 create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0);
1531 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1532 invoice_features.set_basic_mpp_optional();
1534 let payment_params = PaymentParameters::from_node_id(nodes[4].node.get_our_node_id(), TEST_FINAL_CLTV)
1535 .with_bolt11_features(invoice_features).unwrap();
1537 let recv_value = 80_000_000;
1538 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1539 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1541 let expected_route : &[&[&Node]] = &[&[&nodes[1], &nodes[2], &nodes[4]]];
1543 // We check that only one probe was sent, the other one was skipped due to limited liquidity.
1544 assert_eq!(res.len(), 1);
1546 send_probe_along_route(&nodes[0], expected_route);
1548 expect_probe_successful_events(&nodes[0], res.clone());
1550 assert!(!nodes[0].node.has_pending_payments());
1554 fn claimed_send_payment_idempotent() {
1555 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1556 let chanmon_cfgs = create_chanmon_cfgs(2);
1557 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1558 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1559 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1561 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1563 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1564 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1566 macro_rules! check_send_rejected {
1568 // If we try to resend a new payment with a different payment_hash but with the same
1569 // payment_id, it should be rejected.
1570 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1571 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1573 Err(PaymentSendFailure::DuplicatePayment) => {},
1574 _ => panic!("Unexpected send result: {:?}", send_result),
1577 // Further, if we try to send a spontaneous payment with the same payment_id it should
1578 // also be rejected.
1579 let send_result = nodes[0].node.send_spontaneous_payment(
1580 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1582 Err(PaymentSendFailure::DuplicatePayment) => {},
1583 _ => panic!("Unexpected send result: {:?}", send_result),
1588 check_send_rejected!();
1590 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1591 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1592 // we must remain just as idempotent as we were before.
1593 do_claim_payment_along_route(
1594 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1]]], first_payment_preimage)
1597 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1598 nodes[0].node.timer_tick_occurred();
1601 check_send_rejected!();
1603 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1604 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1605 // the payment complete. However, they could have called `send_payment` while the event was
1606 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1607 // after the event is handled a duplicate payment should sitll be rejected.
1608 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1609 check_send_rejected!();
1611 // If relatively little time has passed, a duplicate payment should still fail.
1612 nodes[0].node.timer_tick_occurred();
1613 check_send_rejected!();
1615 // However, after some time has passed (at least more than the one timer tick above), a
1616 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1617 // references to the old payment data.
1618 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1619 nodes[0].node.timer_tick_occurred();
1622 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1623 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1624 check_added_monitors!(nodes[0], 1);
1625 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1626 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1630 fn abandoned_send_payment_idempotent() {
1631 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1633 let chanmon_cfgs = create_chanmon_cfgs(2);
1634 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1635 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1636 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1638 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1640 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1641 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1643 macro_rules! check_send_rejected {
1645 // If we try to resend a new payment with a different payment_hash but with the same
1646 // payment_id, it should be rejected.
1647 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1648 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1650 Err(PaymentSendFailure::DuplicatePayment) => {},
1651 _ => panic!("Unexpected send result: {:?}", send_result),
1654 // Further, if we try to send a spontaneous payment with the same payment_id it should
1655 // also be rejected.
1656 let send_result = nodes[0].node.send_spontaneous_payment(
1657 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1659 Err(PaymentSendFailure::DuplicatePayment) => {},
1660 _ => panic!("Unexpected send result: {:?}", send_result),
1665 check_send_rejected!();
1667 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1668 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1670 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1672 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1673 nodes[0].node.timer_tick_occurred();
1675 check_send_rejected!();
1677 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1679 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1680 // failed payment back.
1681 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1682 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1683 check_added_monitors!(nodes[0], 1);
1684 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1685 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1688 #[derive(PartialEq)]
1689 enum InterceptTest {
1696 fn test_trivial_inflight_htlc_tracking(){
1697 // In this test, we test three scenarios:
1698 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1699 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1700 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1701 let chanmon_cfgs = create_chanmon_cfgs(3);
1702 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1703 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1704 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1706 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1707 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1709 // Send and claim the payment. Inflight HTLCs should be empty.
1710 let (_, payment_hash, _, payment_id) = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1711 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1713 let mut node_0_per_peer_lock;
1714 let mut node_0_peer_state_lock;
1715 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1717 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1718 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1719 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1720 channel_1.context().get_short_channel_id().unwrap()
1722 assert_eq!(chan_1_used_liquidity, None);
1725 let mut node_1_per_peer_lock;
1726 let mut node_1_peer_state_lock;
1727 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1729 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1730 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1731 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1732 channel_2.context().get_short_channel_id().unwrap()
1735 assert_eq!(chan_2_used_liquidity, None);
1737 let pending_payments = nodes[0].node.list_recent_payments();
1738 assert_eq!(pending_payments.len(), 1);
1739 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash), payment_id });
1741 // Remove fulfilled payment
1742 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1743 nodes[0].node.timer_tick_occurred();
1746 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1747 let (payment_preimage, payment_hash, _, payment_id) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1748 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1750 let mut node_0_per_peer_lock;
1751 let mut node_0_peer_state_lock;
1752 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1754 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1755 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1756 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1757 channel_1.context().get_short_channel_id().unwrap()
1759 // First hop accounts for expected 1000 msat fee
1760 assert_eq!(chan_1_used_liquidity, Some(501000));
1763 let mut node_1_per_peer_lock;
1764 let mut node_1_peer_state_lock;
1765 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1767 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1768 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1769 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1770 channel_2.context().get_short_channel_id().unwrap()
1773 assert_eq!(chan_2_used_liquidity, Some(500000));
1775 let pending_payments = nodes[0].node.list_recent_payments();
1776 assert_eq!(pending_payments.len(), 1);
1777 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_id, payment_hash, total_msat: 500000 });
1779 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1780 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1782 // Remove fulfilled payment
1783 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1784 nodes[0].node.timer_tick_occurred();
1787 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1789 let mut node_0_per_peer_lock;
1790 let mut node_0_peer_state_lock;
1791 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1793 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1794 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1795 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1796 channel_1.context().get_short_channel_id().unwrap()
1798 assert_eq!(chan_1_used_liquidity, None);
1801 let mut node_1_per_peer_lock;
1802 let mut node_1_peer_state_lock;
1803 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1805 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1806 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1807 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1808 channel_2.context().get_short_channel_id().unwrap()
1810 assert_eq!(chan_2_used_liquidity, None);
1813 let pending_payments = nodes[0].node.list_recent_payments();
1814 assert_eq!(pending_payments.len(), 0);
1818 fn test_holding_cell_inflight_htlcs() {
1819 let chanmon_cfgs = create_chanmon_cfgs(2);
1820 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1821 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1822 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1823 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1825 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1826 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1828 // Queue up two payments - one will be delivered right away, one immediately goes into the
1829 // holding cell as nodes[0] is AwaitingRAA.
1831 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1832 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1833 check_added_monitors!(nodes[0], 1);
1834 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1835 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1836 check_added_monitors!(nodes[0], 0);
1839 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1842 let mut node_0_per_peer_lock;
1843 let mut node_0_peer_state_lock;
1844 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1846 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1847 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1848 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1849 channel.context().get_short_channel_id().unwrap()
1852 assert_eq!(used_liquidity, Some(2000000));
1855 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1856 nodes[0].node.get_and_clear_pending_msg_events();
1860 fn intercepted_payment() {
1861 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1862 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1863 // payment or (b) fail the payment.
1864 do_test_intercepted_payment(InterceptTest::Forward);
1865 do_test_intercepted_payment(InterceptTest::Fail);
1866 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1867 do_test_intercepted_payment(InterceptTest::Timeout);
1870 fn do_test_intercepted_payment(test: InterceptTest) {
1871 let chanmon_cfgs = create_chanmon_cfgs(3);
1872 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1874 let mut zero_conf_chan_config = test_default_channel_config();
1875 zero_conf_chan_config.manually_accept_inbound_channels = true;
1876 let mut intercept_forwards_config = test_default_channel_config();
1877 intercept_forwards_config.accept_intercept_htlcs = true;
1878 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1880 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1881 let scorer = test_utils::TestScorer::new();
1882 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1884 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1886 let amt_msat = 100_000;
1887 let intercept_scid = nodes[1].node.get_intercept_scid();
1888 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1889 .with_route_hints(vec![
1890 RouteHint(vec![RouteHintHop {
1891 src_node_id: nodes[1].node.get_our_node_id(),
1892 short_channel_id: intercept_scid,
1895 proportional_millionths: 0,
1897 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1898 htlc_minimum_msat: None,
1899 htlc_maximum_msat: None,
1902 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap();
1903 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
1904 let route = get_route(
1905 &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
1906 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
1909 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1910 nodes[0].node.send_payment_with_route(&route, payment_hash,
1911 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1912 let payment_event = {
1914 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1915 assert_eq!(added_monitors.len(), 1);
1916 added_monitors.clear();
1918 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1919 assert_eq!(events.len(), 1);
1920 SendEvent::from_event(events.remove(0))
1922 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1923 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1925 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1926 let events = nodes[1].node.get_and_clear_pending_events();
1927 assert_eq!(events.len(), 1);
1928 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1929 crate::events::Event::HTLCIntercepted {
1930 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1932 assert_eq!(pmt_hash, payment_hash);
1933 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1934 assert_eq!(short_channel_id, intercept_scid);
1935 (intercept_id, expected_outbound_amount_msat)
1940 // Check for unknown channel id error.
1941 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();
1942 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable {
1943 err: format!("Channel with id {} not found for the passed counterparty node_id {}",
1944 log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1946 if test == InterceptTest::Fail {
1947 // Ensure we can fail the intercepted payment back.
1948 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1949 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1950 nodes[1].node.process_pending_htlc_forwards();
1951 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1952 check_added_monitors!(&nodes[1], 1);
1953 assert!(update_fail.update_fail_htlcs.len() == 1);
1954 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1955 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1956 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1958 // Ensure the payment fails with the expected error.
1959 let fail_conditions = PaymentFailedConditions::new()
1960 .blamed_scid(intercept_scid)
1961 .blamed_chan_closed(true)
1962 .expected_htlc_error_data(0x4000 | 10, &[]);
1963 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1964 } else if test == InterceptTest::Forward {
1965 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1966 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
1967 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();
1968 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1969 err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
1970 temp_chan_id, nodes[2].node.get_our_node_id()) });
1971 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1973 // Open the just-in-time channel so the payment can then be forwarded.
1974 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1976 // Finally, forward the intercepted payment through and claim it.
1977 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1978 expect_pending_htlcs_forwardable!(nodes[1]);
1980 let payment_event = {
1982 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1983 assert_eq!(added_monitors.len(), 1);
1984 added_monitors.clear();
1986 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1987 assert_eq!(events.len(), 1);
1988 SendEvent::from_event(events.remove(0))
1990 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1991 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1992 expect_pending_htlcs_forwardable!(nodes[2]);
1994 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1995 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1996 do_claim_payment_along_route(
1997 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[2]]], payment_preimage)
1999 let events = nodes[0].node.get_and_clear_pending_events();
2000 assert_eq!(events.len(), 2);
2002 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
2003 assert_eq!(payment_preimage, *ev_preimage);
2004 assert_eq!(payment_hash, *ev_hash);
2005 assert_eq!(fee_paid_msat, &Some(1000));
2007 _ => panic!("Unexpected event")
2010 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
2011 assert_eq!(hash, Some(payment_hash));
2013 _ => panic!("Unexpected event")
2015 check_added_monitors(&nodes[0], 1);
2016 } else if test == InterceptTest::Timeout {
2017 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
2018 connect_block(&nodes[0], &block);
2019 connect_block(&nodes[1], &block);
2020 for _ in 0..TEST_FINAL_CLTV {
2021 block.header.prev_blockhash = block.block_hash();
2022 connect_block(&nodes[0], &block);
2023 connect_block(&nodes[1], &block);
2025 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
2026 check_added_monitors!(nodes[1], 1);
2027 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2028 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
2029 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
2030 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
2031 assert!(htlc_timeout_updates.update_fee.is_none());
2033 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
2034 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
2035 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
2037 // Check for unknown intercept id error.
2038 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
2039 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();
2040 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2041 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
2042 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2047 fn accept_underpaying_htlcs_config() {
2048 do_accept_underpaying_htlcs_config(1);
2049 do_accept_underpaying_htlcs_config(2);
2050 do_accept_underpaying_htlcs_config(3);
2053 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
2054 let chanmon_cfgs = create_chanmon_cfgs(3);
2055 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2056 let max_in_flight_percent = 10;
2057 let mut intercept_forwards_config = test_default_channel_config();
2058 intercept_forwards_config.accept_intercept_htlcs = true;
2059 intercept_forwards_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = max_in_flight_percent;
2060 let mut underpay_config = test_default_channel_config();
2061 underpay_config.channel_config.accept_underpaying_htlcs = true;
2062 underpay_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = max_in_flight_percent;
2063 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
2064 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2066 let amt_msat = 900_000;
2068 let mut chan_ids = Vec::new();
2069 for _ in 0..num_mpp_parts {
2070 // We choose the channel size so that there can be at most one part pending on each channel.
2071 let channel_size = amt_msat / 1000 / num_mpp_parts as u64 * 100 / max_in_flight_percent as u64 + 100;
2072 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_size, 0);
2073 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, channel_size, 0).0.channel_id;
2074 chan_ids.push(channel_id);
2077 // Send the initial payment.
2078 let skimmed_fee_msat = 20;
2079 let mut route_hints = Vec::new();
2080 for _ in 0..num_mpp_parts {
2081 route_hints.push(RouteHint(vec![RouteHintHop {
2082 src_node_id: nodes[1].node.get_our_node_id(),
2083 short_channel_id: nodes[1].node.get_intercept_scid(),
2086 proportional_millionths: 0,
2088 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
2089 htlc_minimum_msat: None,
2090 htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
2093 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2094 .with_route_hints(route_hints).unwrap()
2095 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap();
2096 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2097 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
2098 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2099 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2100 check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
2101 let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
2102 assert_eq!(events.len(), num_mpp_parts);
2104 // Forward the intercepted payments.
2105 for (idx, ev) in events.into_iter().enumerate() {
2106 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
2107 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
2109 let events = nodes[1].node.get_and_clear_pending_events();
2110 assert_eq!(events.len(), 1);
2111 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
2112 crate::events::Event::HTLCIntercepted {
2113 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
2115 assert_eq!(pmt_hash, payment_hash);
2116 (intercept_id, expected_outbound_amount_msat)
2120 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
2121 nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
2122 expect_pending_htlcs_forwardable!(nodes[1]);
2123 let payment_event = {
2125 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2126 assert_eq!(added_monitors.len(), 1);
2127 added_monitors.clear();
2129 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2130 assert_eq!(events.len(), 1);
2131 SendEvent::from_event(events.remove(0))
2133 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
2134 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
2135 if idx == num_mpp_parts - 1 {
2136 expect_pending_htlcs_forwardable!(nodes[2]);
2140 // Claim the payment and check that the skimmed fee is as expected.
2141 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
2142 let events = nodes[2].node.get_and_clear_pending_events();
2143 assert_eq!(events.len(), 1);
2145 crate::events::Event::PaymentClaimable {
2146 ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
2148 assert_eq!(payment_hash, payment_hash);
2149 assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
2150 assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
2151 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2153 crate::events::PaymentPurpose::Bolt11InvoicePayment {
2154 payment_preimage: ev_payment_preimage,
2155 payment_secret: ev_payment_secret,
2158 assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
2159 assert_eq!(payment_secret, *ev_payment_secret);
2164 _ => panic!("Unexpected event"),
2166 let mut expected_paths_vecs = Vec::new();
2167 let mut expected_paths = Vec::new();
2168 for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
2169 for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
2170 expected_paths[0].last().unwrap().node.claim_funds(payment_preimage);
2171 let args = ClaimAlongRouteArgs::new(&nodes[0], &expected_paths[..], payment_preimage)
2172 .with_expected_extra_fees(vec![skimmed_fee_msat as u32; num_mpp_parts]);
2173 let total_fee_msat = pass_claimed_payment_along_route(args);
2174 // The sender doesn't know that the penultimate hop took an extra fee.
2175 expect_payment_sent(&nodes[0], payment_preimage,
2176 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true, true);
2179 #[derive(PartialEq)]
2190 fn automatic_retries() {
2191 do_automatic_retries(AutoRetry::Success);
2192 do_automatic_retries(AutoRetry::Spontaneous);
2193 do_automatic_retries(AutoRetry::FailAttempts);
2194 do_automatic_retries(AutoRetry::FailTimeout);
2195 do_automatic_retries(AutoRetry::FailOnRestart);
2196 do_automatic_retries(AutoRetry::FailOnRetry);
2198 fn do_automatic_retries(test: AutoRetry) {
2199 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
2201 let chanmon_cfgs = create_chanmon_cfgs(3);
2202 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2204 let new_chain_monitor;
2206 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2207 let node_0_deserialized;
2209 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2210 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2211 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2213 // Marshall data to send the payment
2214 #[cfg(feature = "std")]
2215 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2216 #[cfg(not(feature = "std"))]
2217 let payment_expiry_secs = 60 * 60;
2218 let amt_msat = 1000;
2219 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2220 invoice_features.set_variable_length_onion_required();
2221 invoice_features.set_payment_secret_required();
2222 invoice_features.set_basic_mpp_optional();
2223 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2224 .with_expiry_time(payment_expiry_secs as u64)
2225 .with_bolt11_features(invoice_features).unwrap();
2226 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2227 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
2229 macro_rules! pass_failed_attempt_with_retry_along_path {
2230 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
2231 // Send a payment attempt that fails due to lack of liquidity on the second hop
2232 check_added_monitors!(nodes[0], 1);
2233 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2234 let mut update_add = update_0.update_add_htlcs[0].clone();
2235 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
2236 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
2237 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2238 nodes[1].node.process_pending_htlc_forwards();
2239 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
2240 vec![HTLCDestination::NextHopChannel {
2241 node_id: Some(nodes[2].node.get_our_node_id()),
2242 channel_id: $failing_channel_id,
2244 nodes[1].node.process_pending_htlc_forwards();
2245 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2246 check_added_monitors!(&nodes[1], 1);
2247 assert!(update_1.update_fail_htlcs.len() == 1);
2248 let fail_msg = update_1.update_fail_htlcs[0].clone();
2249 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
2250 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
2252 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
2253 let mut events = nodes[0].node.get_and_clear_pending_events();
2254 assert_eq!(events.len(), 2);
2256 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2257 assert_eq!(payment_hash, ev_payment_hash);
2258 assert_eq!(payment_failed_permanently, false);
2260 _ => panic!("Unexpected event"),
2262 if $expect_pending_htlcs_forwardable {
2264 Event::PendingHTLCsForwardable { .. } => {},
2265 _ => panic!("Unexpected event"),
2269 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
2270 assert_eq!(payment_hash, ev_payment_hash);
2272 _ => panic!("Unexpected event"),
2278 if test == AutoRetry::Success {
2279 // Test that we can succeed on the first retry.
2280 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2281 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2282 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2284 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2285 // attempt, since the initial second hop channel will be excluded from pathfinding
2286 create_announced_chan_between_nodes(&nodes, 1, 2);
2288 // We retry payments in `process_pending_htlc_forwards`
2289 nodes[0].node.process_pending_htlc_forwards();
2290 check_added_monitors!(nodes[0], 1);
2291 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2292 assert_eq!(msg_events.len(), 1);
2293 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
2294 claim_payment_along_route(
2295 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[2]]], payment_preimage)
2297 } else if test == AutoRetry::Spontaneous {
2298 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
2299 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
2300 Retry::Attempts(1)).unwrap();
2301 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2303 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2304 // attempt, since the initial second hop channel will be excluded from pathfinding
2305 create_announced_chan_between_nodes(&nodes, 1, 2);
2307 // We retry payments in `process_pending_htlc_forwards`
2308 nodes[0].node.process_pending_htlc_forwards();
2309 check_added_monitors!(nodes[0], 1);
2310 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2311 assert_eq!(msg_events.len(), 1);
2312 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2313 claim_payment_along_route(
2314 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[2]]], payment_preimage)
2316 } else if test == AutoRetry::FailAttempts {
2317 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2318 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2319 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2320 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2322 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2323 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2324 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2326 // We retry payments in `process_pending_htlc_forwards`
2327 nodes[0].node.process_pending_htlc_forwards();
2328 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2330 // Ensure we won't retry a second time.
2331 nodes[0].node.process_pending_htlc_forwards();
2332 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2333 assert_eq!(msg_events.len(), 0);
2334 } else if test == AutoRetry::FailTimeout {
2335 #[cfg(feature = "std")] {
2336 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2337 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2338 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2339 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2341 // Advance the time so the second attempt fails due to timeout.
2342 SinceEpoch::advance(Duration::from_secs(61));
2344 // Make sure we don't retry again.
2345 nodes[0].node.process_pending_htlc_forwards();
2346 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2347 assert_eq!(msg_events.len(), 0);
2349 let mut events = nodes[0].node.get_and_clear_pending_events();
2350 assert_eq!(events.len(), 1);
2352 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2353 assert_eq!(payment_hash, *ev_payment_hash);
2354 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2355 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2357 _ => panic!("Unexpected event"),
2360 } else if test == AutoRetry::FailOnRestart {
2361 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2362 // attempts remaining prior to restart.
2363 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2364 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2365 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2367 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2368 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2369 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2371 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2372 nodes[0].node.process_pending_htlc_forwards();
2373 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2375 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2376 let node_encoded = nodes[0].node.encode();
2377 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2378 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2380 let mut events = nodes[0].node.get_and_clear_pending_events();
2381 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2382 // Make sure we don't retry again.
2383 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2384 assert_eq!(msg_events.len(), 0);
2386 let mut events = nodes[0].node.get_and_clear_pending_events();
2387 assert_eq!(events.len(), 1);
2389 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2390 assert_eq!(payment_hash, *ev_payment_hash);
2391 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2392 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2394 _ => panic!("Unexpected event"),
2396 } else if test == AutoRetry::FailOnRetry {
2397 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2398 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2399 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2401 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2402 // fail to find a route.
2403 nodes[0].node.process_pending_htlc_forwards();
2404 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2405 assert_eq!(msg_events.len(), 0);
2407 let mut events = nodes[0].node.get_and_clear_pending_events();
2408 assert_eq!(events.len(), 1);
2410 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2411 assert_eq!(payment_hash, *ev_payment_hash);
2412 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2413 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2415 _ => panic!("Unexpected event"),
2421 fn auto_retry_partial_failure() {
2422 // Test that we'll retry appropriately on send partial failure and retry partial failure.
2423 let chanmon_cfgs = create_chanmon_cfgs(2);
2424 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2425 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2426 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2428 // Open three channels, the first has plenty of liquidity, the second and third have ~no
2429 // available liquidity, causing any outbound payments routed over it to fail immediately.
2430 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2431 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;
2432 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;
2434 // Marshall data to send the payment
2435 let amt_msat = 10_000_000;
2436 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2437 #[cfg(feature = "std")]
2438 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2439 #[cfg(not(feature = "std"))]
2440 let payment_expiry_secs = 60 * 60;
2441 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2442 invoice_features.set_variable_length_onion_required();
2443 invoice_features.set_payment_secret_required();
2444 invoice_features.set_basic_mpp_optional();
2445 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2446 .with_expiry_time(payment_expiry_secs as u64)
2447 .with_bolt11_features(invoice_features).unwrap();
2449 // Configure the initial send path
2450 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2451 route_params.max_total_routing_fee_msat = None;
2453 let send_route = Route {
2455 Path { hops: vec![RouteHop {
2456 pubkey: nodes[1].node.get_our_node_id(),
2457 node_features: nodes[1].node.node_features(),
2458 short_channel_id: chan_1_id,
2459 channel_features: nodes[1].node.channel_features(),
2460 fee_msat: amt_msat / 2,
2461 cltv_expiry_delta: 100,
2462 maybe_announced_channel: true,
2463 }], blinded_tail: None },
2464 Path { hops: vec![RouteHop {
2465 pubkey: nodes[1].node.get_our_node_id(),
2466 node_features: nodes[1].node.node_features(),
2467 short_channel_id: chan_2_id,
2468 channel_features: nodes[1].node.channel_features(),
2469 fee_msat: amt_msat / 2,
2470 cltv_expiry_delta: 100,
2471 maybe_announced_channel: true,
2472 }], blinded_tail: None },
2474 route_params: Some(route_params.clone()),
2476 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2478 // Configure the retry1 paths
2479 let mut payment_params = route_params.payment_params.clone();
2480 payment_params.previously_failed_channels.push(chan_2_id);
2481 let mut retry_1_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 2);
2482 retry_1_params.max_total_routing_fee_msat = None;
2484 let retry_1_route = Route {
2486 Path { hops: vec![RouteHop {
2487 pubkey: nodes[1].node.get_our_node_id(),
2488 node_features: nodes[1].node.node_features(),
2489 short_channel_id: chan_1_id,
2490 channel_features: nodes[1].node.channel_features(),
2491 fee_msat: amt_msat / 4,
2492 cltv_expiry_delta: 100,
2493 maybe_announced_channel: true,
2494 }], blinded_tail: None },
2495 Path { hops: vec![RouteHop {
2496 pubkey: nodes[1].node.get_our_node_id(),
2497 node_features: nodes[1].node.node_features(),
2498 short_channel_id: chan_3_id,
2499 channel_features: nodes[1].node.channel_features(),
2500 fee_msat: amt_msat / 4,
2501 cltv_expiry_delta: 100,
2502 maybe_announced_channel: true,
2503 }], blinded_tail: None },
2505 route_params: Some(retry_1_params.clone()),
2507 nodes[0].router.expect_find_route(retry_1_params.clone(), Ok(retry_1_route));
2509 // Configure the retry2 path
2510 let mut payment_params = retry_1_params.payment_params.clone();
2511 payment_params.previously_failed_channels.push(chan_3_id);
2512 let mut retry_2_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 4);
2513 retry_2_params.max_total_routing_fee_msat = None;
2515 let retry_2_route = Route {
2517 Path { hops: vec![RouteHop {
2518 pubkey: nodes[1].node.get_our_node_id(),
2519 node_features: nodes[1].node.node_features(),
2520 short_channel_id: chan_1_id,
2521 channel_features: nodes[1].node.channel_features(),
2522 fee_msat: amt_msat / 4,
2523 cltv_expiry_delta: 100,
2524 maybe_announced_channel: true,
2525 }], blinded_tail: None },
2527 route_params: Some(retry_2_params.clone()),
2529 nodes[0].router.expect_find_route(retry_2_params, Ok(retry_2_route));
2531 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2532 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2533 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2534 let payment_failed_events = nodes[0].node.get_and_clear_pending_events();
2535 assert_eq!(payment_failed_events.len(), 2);
2536 match payment_failed_events[0] {
2537 Event::PaymentPathFailed { .. } => {},
2538 _ => panic!("Unexpected event"),
2540 match payment_failed_events[1] {
2541 Event::PaymentPathFailed { .. } => {},
2542 _ => panic!("Unexpected event"),
2545 // Pass the first part of the payment along the path.
2546 check_added_monitors!(nodes[0], 1); // only one HTLC actually made it out
2547 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2549 // Only one HTLC/channel update actually made it out
2550 assert_eq!(msg_events.len(), 1);
2551 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2553 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2554 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2555 check_added_monitors!(nodes[1], 1);
2556 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2558 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2559 check_added_monitors!(nodes[0], 1);
2560 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2562 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2563 check_added_monitors!(nodes[0], 1);
2564 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2566 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2567 check_added_monitors!(nodes[1], 1);
2569 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2570 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2571 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2572 check_added_monitors!(nodes[1], 1);
2573 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2575 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2576 check_added_monitors!(nodes[0], 1);
2578 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2579 check_added_monitors!(nodes[0], 1);
2580 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2582 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2583 check_added_monitors!(nodes[1], 1);
2585 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2586 nodes[1].node.process_pending_htlc_forwards();
2587 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2588 nodes[1].node.claim_funds(payment_preimage);
2589 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2590 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2591 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2593 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2594 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
2595 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2596 check_added_monitors!(nodes[0], 1);
2597 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2599 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2600 check_added_monitors!(nodes[1], 4);
2601 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2603 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2604 check_added_monitors!(nodes[1], 1);
2605 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2607 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2608 check_added_monitors!(nodes[0], 1);
2609 expect_payment_path_successful!(nodes[0]);
2611 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2612 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2613 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2614 check_added_monitors!(nodes[0], 1);
2615 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2617 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2618 check_added_monitors!(nodes[1], 1);
2620 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2621 check_added_monitors!(nodes[1], 1);
2622 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2624 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2625 check_added_monitors!(nodes[0], 1);
2626 let events = nodes[0].node.get_and_clear_pending_events();
2627 assert_eq!(events.len(), 2);
2628 if let Event::PaymentPathSuccessful { .. } = events[0] {} else { panic!(); }
2629 if let Event::PaymentPathSuccessful { .. } = events[1] {} else { panic!(); }
2633 fn auto_retry_zero_attempts_send_error() {
2634 let chanmon_cfgs = create_chanmon_cfgs(2);
2635 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2636 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2637 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2639 // Open a single channel that does not have sufficient liquidity for the payment we want to
2641 let chan_id = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 989_000_000).0.contents.short_channel_id;
2643 // Marshall data to send the payment
2644 let amt_msat = 10_000_000;
2645 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(amt_msat), None);
2646 #[cfg(feature = "std")]
2647 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2648 #[cfg(not(feature = "std"))]
2649 let payment_expiry_secs = 60 * 60;
2650 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2651 invoice_features.set_variable_length_onion_required();
2652 invoice_features.set_payment_secret_required();
2653 invoice_features.set_basic_mpp_optional();
2654 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2655 .with_expiry_time(payment_expiry_secs as u64)
2656 .with_bolt11_features(invoice_features).unwrap();
2657 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2659 // Override the route search to return a route, rather than failing at the route-finding step.
2660 let send_route = Route {
2662 Path { hops: vec![RouteHop {
2663 pubkey: nodes[1].node.get_our_node_id(),
2664 node_features: nodes[1].node.node_features(),
2665 short_channel_id: chan_id,
2666 channel_features: nodes[1].node.channel_features(),
2668 cltv_expiry_delta: 100,
2669 maybe_announced_channel: true,
2670 }], blinded_tail: None },
2672 route_params: Some(route_params.clone()),
2674 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2676 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2677 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2678 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2679 let events = nodes[0].node.get_and_clear_pending_events();
2680 assert_eq!(events.len(), 2);
2681 if let Event::PaymentPathFailed { .. } = events[0] { } else { panic!(); }
2682 if let Event::PaymentFailed { .. } = events[1] { } else { panic!(); }
2683 check_added_monitors!(nodes[0], 0);
2687 fn fails_paying_after_rejected_by_payee() {
2688 let chanmon_cfgs = create_chanmon_cfgs(2);
2689 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2690 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2691 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2693 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2695 // Marshall data to send the payment
2696 let amt_msat = 20_000;
2697 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2698 #[cfg(feature = "std")]
2699 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2700 #[cfg(not(feature = "std"))]
2701 let payment_expiry_secs = 60 * 60;
2702 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2703 invoice_features.set_variable_length_onion_required();
2704 invoice_features.set_payment_secret_required();
2705 invoice_features.set_basic_mpp_optional();
2706 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2707 .with_expiry_time(payment_expiry_secs as u64)
2708 .with_bolt11_features(invoice_features).unwrap();
2709 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2711 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2712 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2713 check_added_monitors!(nodes[0], 1);
2714 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2715 assert_eq!(events.len(), 1);
2716 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2717 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2718 check_added_monitors!(nodes[1], 0);
2719 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2720 expect_pending_htlcs_forwardable!(nodes[1]);
2721 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2723 nodes[1].node.fail_htlc_backwards(&payment_hash);
2724 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2725 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2729 fn retry_multi_path_single_failed_payment() {
2730 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2731 let chanmon_cfgs = create_chanmon_cfgs(2);
2732 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2733 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2734 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2736 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2737 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2739 let amt_msat = 100_010_000;
2741 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2742 #[cfg(feature = "std")]
2743 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2744 #[cfg(not(feature = "std"))]
2745 let payment_expiry_secs = 60 * 60;
2746 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2747 invoice_features.set_variable_length_onion_required();
2748 invoice_features.set_payment_secret_required();
2749 invoice_features.set_basic_mpp_optional();
2750 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2751 .with_expiry_time(payment_expiry_secs as u64)
2752 .with_bolt11_features(invoice_features).unwrap();
2753 let mut route_params = RouteParameters::from_payment_params_and_value(
2754 payment_params.clone(), amt_msat);
2755 route_params.max_total_routing_fee_msat = None;
2757 let chans = nodes[0].node.list_usable_channels();
2758 let mut route = Route {
2760 Path { hops: vec![RouteHop {
2761 pubkey: nodes[1].node.get_our_node_id(),
2762 node_features: nodes[1].node.node_features(),
2763 short_channel_id: chans[0].short_channel_id.unwrap(),
2764 channel_features: nodes[1].node.channel_features(),
2766 cltv_expiry_delta: 100,
2767 maybe_announced_channel: true,
2768 }], blinded_tail: None },
2769 Path { hops: vec![RouteHop {
2770 pubkey: nodes[1].node.get_our_node_id(),
2771 node_features: nodes[1].node.node_features(),
2772 short_channel_id: chans[1].short_channel_id.unwrap(),
2773 channel_features: nodes[1].node.channel_features(),
2774 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2775 cltv_expiry_delta: 100,
2776 maybe_announced_channel: true,
2777 }], blinded_tail: None },
2779 route_params: Some(route_params.clone()),
2781 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2782 // On retry, split the payment across both channels.
2783 route.paths[0].hops[0].fee_msat = 50_000_001;
2784 route.paths[1].hops[0].fee_msat = 50_000_000;
2785 let mut pay_params = route.route_params.clone().unwrap().payment_params;
2786 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2788 let mut retry_params = RouteParameters::from_payment_params_and_value(pay_params, 100_000_000);
2789 retry_params.max_total_routing_fee_msat = None;
2790 route.route_params = Some(retry_params.clone());
2791 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2794 let scorer = chanmon_cfgs[0].scorer.read().unwrap();
2795 // The initial send attempt, 2 paths
2796 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2797 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2798 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2799 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2800 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2803 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2804 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2805 let events = nodes[0].node.get_and_clear_pending_events();
2806 assert_eq!(events.len(), 1);
2808 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2809 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2810 short_channel_id: Some(expected_scid), .. } =>
2812 assert_eq!(payment_hash, ev_payment_hash);
2813 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2815 _ => panic!("Unexpected event"),
2817 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2818 assert_eq!(htlc_msgs.len(), 2);
2819 check_added_monitors!(nodes[0], 2);
2823 fn immediate_retry_on_failure() {
2824 // Tests that we can/will retry immediately after a failure
2825 let chanmon_cfgs = create_chanmon_cfgs(2);
2826 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2827 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2828 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2830 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2831 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2833 let amt_msat = 100_000_001;
2834 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2835 #[cfg(feature = "std")]
2836 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2837 #[cfg(not(feature = "std"))]
2838 let payment_expiry_secs = 60 * 60;
2839 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2840 invoice_features.set_variable_length_onion_required();
2841 invoice_features.set_payment_secret_required();
2842 invoice_features.set_basic_mpp_optional();
2843 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2844 .with_expiry_time(payment_expiry_secs as u64)
2845 .with_bolt11_features(invoice_features).unwrap();
2846 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2848 let chans = nodes[0].node.list_usable_channels();
2849 let mut route = Route {
2851 Path { hops: vec![RouteHop {
2852 pubkey: nodes[1].node.get_our_node_id(),
2853 node_features: nodes[1].node.node_features(),
2854 short_channel_id: chans[0].short_channel_id.unwrap(),
2855 channel_features: nodes[1].node.channel_features(),
2856 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2857 cltv_expiry_delta: 100,
2858 maybe_announced_channel: true,
2859 }], blinded_tail: None },
2861 route_params: Some(route_params.clone()),
2863 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2864 // On retry, split the payment across both channels.
2865 route.paths.push(route.paths[0].clone());
2866 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2867 route.paths[0].hops[0].fee_msat = 50_000_000;
2868 route.paths[1].hops[0].fee_msat = 50_000_001;
2869 let mut pay_params = route_params.payment_params.clone();
2870 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2871 let retry_params = RouteParameters::from_payment_params_and_value(pay_params, amt_msat);
2872 route.route_params = Some(retry_params.clone());
2873 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2875 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2876 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2877 let events = nodes[0].node.get_and_clear_pending_events();
2878 assert_eq!(events.len(), 1);
2880 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2881 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2882 short_channel_id: Some(expected_scid), .. } =>
2884 assert_eq!(payment_hash, ev_payment_hash);
2885 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2887 _ => panic!("Unexpected event"),
2889 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2890 assert_eq!(htlc_msgs.len(), 2);
2891 check_added_monitors!(nodes[0], 2);
2895 fn no_extra_retries_on_back_to_back_fail() {
2896 // In a previous release, we had a race where we may exceed the payment retry count if we
2897 // get two failures in a row with the second indicating that all paths had failed (this field,
2898 // `all_paths_failed`, has since been removed).
2899 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2900 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2901 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2902 // pending which we will see later. Thus, when we previously removed the retry tracking map
2903 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2904 // retry entry even though more events for the same payment were still pending. This led to
2905 // us retrying a payment again even though we'd already given up on it.
2907 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2908 // is used to remove the payment retry counter entries instead. This tests for the specific
2909 // excess-retry case while also testing `PaymentFailed` generation.
2911 let chanmon_cfgs = create_chanmon_cfgs(3);
2912 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2913 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2914 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2916 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2917 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2919 let amt_msat = 200_000_000;
2920 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2921 #[cfg(feature = "std")]
2922 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2923 #[cfg(not(feature = "std"))]
2924 let payment_expiry_secs = 60 * 60;
2925 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2926 invoice_features.set_variable_length_onion_required();
2927 invoice_features.set_payment_secret_required();
2928 invoice_features.set_basic_mpp_optional();
2929 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2930 .with_expiry_time(payment_expiry_secs as u64)
2931 .with_bolt11_features(invoice_features).unwrap();
2932 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2933 route_params.max_total_routing_fee_msat = None;
2935 let mut route = Route {
2937 Path { hops: vec![RouteHop {
2938 pubkey: nodes[1].node.get_our_node_id(),
2939 node_features: nodes[1].node.node_features(),
2940 short_channel_id: chan_1_scid,
2941 channel_features: nodes[1].node.channel_features(),
2942 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2943 cltv_expiry_delta: 100,
2944 maybe_announced_channel: true,
2946 pubkey: nodes[2].node.get_our_node_id(),
2947 node_features: nodes[2].node.node_features(),
2948 short_channel_id: chan_2_scid,
2949 channel_features: nodes[2].node.channel_features(),
2950 fee_msat: 100_000_000,
2951 cltv_expiry_delta: 100,
2952 maybe_announced_channel: true,
2953 }], blinded_tail: None },
2954 Path { hops: vec![RouteHop {
2955 pubkey: nodes[1].node.get_our_node_id(),
2956 node_features: nodes[1].node.node_features(),
2957 short_channel_id: chan_1_scid,
2958 channel_features: nodes[1].node.channel_features(),
2959 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2960 cltv_expiry_delta: 100,
2961 maybe_announced_channel: true,
2963 pubkey: nodes[2].node.get_our_node_id(),
2964 node_features: nodes[2].node.node_features(),
2965 short_channel_id: chan_2_scid,
2966 channel_features: nodes[2].node.channel_features(),
2967 fee_msat: 100_000_000,
2968 cltv_expiry_delta: 100,
2969 maybe_announced_channel: true,
2970 }], blinded_tail: None }
2972 route_params: Some(route_params.clone()),
2974 route.route_params.as_mut().unwrap().max_total_routing_fee_msat = None;
2975 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2976 let mut second_payment_params = route_params.payment_params.clone();
2977 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2978 // On retry, we'll only return one path
2979 route.paths.remove(1);
2980 route.paths[0].hops[1].fee_msat = amt_msat;
2981 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat);
2982 retry_params.max_total_routing_fee_msat = None;
2983 route.route_params = Some(retry_params.clone());
2984 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2986 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2987 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2988 let htlc_updates = SendEvent::from_node(&nodes[0]);
2989 check_added_monitors!(nodes[0], 1);
2990 assert_eq!(htlc_updates.msgs.len(), 1);
2992 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2993 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2994 check_added_monitors!(nodes[1], 1);
2995 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2997 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2998 check_added_monitors!(nodes[0], 1);
2999 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
3001 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
3002 check_added_monitors!(nodes[0], 1);
3003 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3005 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
3006 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
3007 check_added_monitors!(nodes[1], 1);
3008 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3010 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
3011 check_added_monitors!(nodes[1], 1);
3012 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3014 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
3015 check_added_monitors!(nodes[0], 1);
3017 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3018 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
3019 check_added_monitors!(nodes[0], 1);
3020 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3022 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
3023 check_added_monitors!(nodes[1], 1);
3024 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3026 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
3027 check_added_monitors!(nodes[1], 1);
3028 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3030 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
3031 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
3032 check_added_monitors!(nodes[0], 1);
3034 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
3035 check_added_monitors!(nodes[0], 1);
3036 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3038 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
3039 check_added_monitors!(nodes[1], 1);
3040 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
3041 check_added_monitors!(nodes[1], 1);
3042 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3044 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
3045 check_added_monitors!(nodes[0], 1);
3047 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
3048 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
3051 // Previously, we retried payments in an event consumer, which would retry each
3052 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
3053 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
3054 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
3055 // by adding the `PaymentFailed` event.
3057 // Because we now retry payments as a batch, we simply return a single-path route in the
3058 // second, batched, request, have that fail, ensure the payment was abandoned.
3059 let mut events = nodes[0].node.get_and_clear_pending_events();
3060 assert_eq!(events.len(), 3);
3062 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3063 assert_eq!(payment_hash, ev_payment_hash);
3064 assert_eq!(payment_failed_permanently, false);
3066 _ => panic!("Unexpected event"),
3069 Event::PendingHTLCsForwardable { .. } => {},
3070 _ => panic!("Unexpected event"),
3073 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3074 assert_eq!(payment_hash, ev_payment_hash);
3075 assert_eq!(payment_failed_permanently, false);
3077 _ => panic!("Unexpected event"),
3080 nodes[0].node.process_pending_htlc_forwards();
3081 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3082 check_added_monitors!(nodes[0], 1);
3084 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3085 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3086 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3087 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3088 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
3090 let mut events = nodes[0].node.get_and_clear_pending_events();
3091 assert_eq!(events.len(), 2);
3093 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3094 assert_eq!(payment_hash, ev_payment_hash);
3095 assert_eq!(payment_failed_permanently, false);
3097 _ => panic!("Unexpected event"),
3100 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
3101 assert_eq!(payment_hash, *ev_payment_hash);
3102 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
3103 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
3105 _ => panic!("Unexpected event"),
3110 fn test_simple_partial_retry() {
3111 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
3112 // full amount of the payment, rather than only the missing amount. Here we simply test for
3113 // this by sending a payment with two parts, failing one, and retrying the second. Note that
3114 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
3116 let chanmon_cfgs = create_chanmon_cfgs(3);
3117 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3118 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3119 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3121 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3122 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
3124 let amt_msat = 200_000_000;
3125 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3126 #[cfg(feature = "std")]
3127 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3128 #[cfg(not(feature = "std"))]
3129 let payment_expiry_secs = 60 * 60;
3130 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3131 invoice_features.set_variable_length_onion_required();
3132 invoice_features.set_payment_secret_required();
3133 invoice_features.set_basic_mpp_optional();
3134 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3135 .with_expiry_time(payment_expiry_secs as u64)
3136 .with_bolt11_features(invoice_features).unwrap();
3137 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
3138 route_params.max_total_routing_fee_msat = None;
3140 let mut route = Route {
3142 Path { hops: vec![RouteHop {
3143 pubkey: nodes[1].node.get_our_node_id(),
3144 node_features: nodes[1].node.node_features(),
3145 short_channel_id: chan_1_scid,
3146 channel_features: nodes[1].node.channel_features(),
3147 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
3148 cltv_expiry_delta: 100,
3149 maybe_announced_channel: true,
3151 pubkey: nodes[2].node.get_our_node_id(),
3152 node_features: nodes[2].node.node_features(),
3153 short_channel_id: chan_2_scid,
3154 channel_features: nodes[2].node.channel_features(),
3155 fee_msat: 100_000_000,
3156 cltv_expiry_delta: 100,
3157 maybe_announced_channel: true,
3158 }], blinded_tail: None },
3159 Path { hops: vec![RouteHop {
3160 pubkey: nodes[1].node.get_our_node_id(),
3161 node_features: nodes[1].node.node_features(),
3162 short_channel_id: chan_1_scid,
3163 channel_features: nodes[1].node.channel_features(),
3165 cltv_expiry_delta: 100,
3166 maybe_announced_channel: true,
3168 pubkey: nodes[2].node.get_our_node_id(),
3169 node_features: nodes[2].node.node_features(),
3170 short_channel_id: chan_2_scid,
3171 channel_features: nodes[2].node.channel_features(),
3172 fee_msat: 100_000_000,
3173 cltv_expiry_delta: 100,
3174 maybe_announced_channel: true,
3175 }], blinded_tail: None }
3177 route_params: Some(route_params.clone()),
3180 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3182 let mut second_payment_params = route_params.payment_params.clone();
3183 second_payment_params.previously_failed_channels = vec![chan_2_scid];
3184 // On retry, we'll only be asked for one path (or 100k sats)
3185 route.paths.remove(0);
3186 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat / 2);
3187 retry_params.max_total_routing_fee_msat = None;
3188 route.route_params = Some(retry_params.clone());
3189 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
3191 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3192 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
3193 let htlc_updates = SendEvent::from_node(&nodes[0]);
3194 check_added_monitors!(nodes[0], 1);
3195 assert_eq!(htlc_updates.msgs.len(), 1);
3197 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
3198 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
3199 check_added_monitors!(nodes[1], 1);
3200 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3202 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
3203 check_added_monitors!(nodes[0], 1);
3204 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
3206 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
3207 check_added_monitors!(nodes[0], 1);
3208 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3210 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
3211 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
3212 check_added_monitors!(nodes[1], 1);
3213 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3215 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
3216 check_added_monitors!(nodes[1], 1);
3217 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3219 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
3220 check_added_monitors!(nodes[0], 1);
3222 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3223 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
3224 check_added_monitors!(nodes[0], 1);
3225 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3227 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
3228 check_added_monitors!(nodes[1], 1);
3230 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
3231 check_added_monitors!(nodes[1], 1);
3233 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3235 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
3236 check_added_monitors!(nodes[0], 1);
3238 let mut events = nodes[0].node.get_and_clear_pending_events();
3239 assert_eq!(events.len(), 2);
3241 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3242 assert_eq!(payment_hash, ev_payment_hash);
3243 assert_eq!(payment_failed_permanently, false);
3245 _ => panic!("Unexpected event"),
3248 Event::PendingHTLCsForwardable { .. } => {},
3249 _ => panic!("Unexpected event"),
3252 nodes[0].node.process_pending_htlc_forwards();
3253 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3254 check_added_monitors!(nodes[0], 1);
3256 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3257 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3259 expect_pending_htlcs_forwardable!(nodes[1]);
3260 check_added_monitors!(nodes[1], 1);
3262 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3263 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
3264 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
3265 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
3267 expect_pending_htlcs_forwardable!(nodes[2]);
3268 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
3272 #[cfg(feature = "std")]
3273 fn test_threaded_payment_retries() {
3274 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
3275 // a single thread and would happily let multiple threads run retries at the same time. Because
3276 // retries are done by first calculating the amount we need to retry, then dropping the
3277 // relevant lock, then actually sending, we would happily let multiple threads retry the same
3278 // amount at the same time, overpaying our original HTLC!
3279 let chanmon_cfgs = create_chanmon_cfgs(4);
3280 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3281 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3282 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3284 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
3285 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
3286 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
3287 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
3289 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3290 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
3291 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
3292 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
3294 let amt_msat = 100_000_000;
3295 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3296 #[cfg(feature = "std")]
3297 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3298 #[cfg(not(feature = "std"))]
3299 let payment_expiry_secs = 60 * 60;
3300 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3301 invoice_features.set_variable_length_onion_required();
3302 invoice_features.set_payment_secret_required();
3303 invoice_features.set_basic_mpp_optional();
3304 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3305 .with_expiry_time(payment_expiry_secs as u64)
3306 .with_bolt11_features(invoice_features).unwrap();
3307 let mut route_params = RouteParameters {
3308 payment_params, final_value_msat: amt_msat, max_total_routing_fee_msat: Some(500_000),
3311 let mut route = Route {
3313 Path { hops: vec![RouteHop {
3314 pubkey: nodes[1].node.get_our_node_id(),
3315 node_features: nodes[1].node.node_features(),
3316 short_channel_id: chan_1_scid,
3317 channel_features: nodes[1].node.channel_features(),
3319 cltv_expiry_delta: 100,
3320 maybe_announced_channel: true,
3322 pubkey: nodes[3].node.get_our_node_id(),
3323 node_features: nodes[2].node.node_features(),
3324 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3325 channel_features: nodes[2].node.channel_features(),
3326 fee_msat: amt_msat / 1000,
3327 cltv_expiry_delta: 100,
3328 maybe_announced_channel: true,
3329 }], blinded_tail: None },
3330 Path { hops: vec![RouteHop {
3331 pubkey: nodes[2].node.get_our_node_id(),
3332 node_features: nodes[2].node.node_features(),
3333 short_channel_id: chan_3_scid,
3334 channel_features: nodes[2].node.channel_features(),
3336 cltv_expiry_delta: 100,
3337 maybe_announced_channel: true,
3339 pubkey: nodes[3].node.get_our_node_id(),
3340 node_features: nodes[3].node.node_features(),
3341 short_channel_id: chan_4_scid,
3342 channel_features: nodes[3].node.channel_features(),
3343 fee_msat: amt_msat - amt_msat / 1000,
3344 cltv_expiry_delta: 100,
3345 maybe_announced_channel: true,
3346 }], blinded_tail: None }
3348 route_params: Some(route_params.clone()),
3350 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3352 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3353 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3354 check_added_monitors!(nodes[0], 2);
3355 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3356 assert_eq!(send_msg_events.len(), 2);
3357 send_msg_events.retain(|msg|
3358 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3359 // Drop the commitment update for nodes[2], we can just let that one sit pending
3361 *node_id == nodes[1].node.get_our_node_id()
3362 } else { panic!(); }
3365 // from here on out, the retry `RouteParameters` amount will be amt/1000
3366 route_params.final_value_msat /= 1000;
3367 route.route_params = Some(route_params.clone());
3370 let end_time = Instant::now() + Duration::from_secs(1);
3371 macro_rules! thread_body { () => { {
3372 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3373 let node_ref = NodePtr::from_node(&nodes[0]);
3376 let node_a = unsafe { &*node_ref.0 };
3377 while Instant::now() < end_time {
3378 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3379 // Ignore if we have any pending events, just always pretend we just got a
3380 // PendingHTLCsForwardable
3381 node_a.node.process_pending_htlc_forwards();
3385 let mut threads = Vec::new();
3386 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3388 // Back in the main thread, poll pending messages and make sure that we never have more than
3389 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3390 // there are HTLC messages shoved in while its running. This allows us to test that we never
3391 // generate an additional update_add_htlc until we've fully failed the first.
3392 let mut previously_failed_channels = Vec::new();
3394 assert_eq!(send_msg_events.len(), 1);
3395 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3396 assert_eq!(send_event.msgs.len(), 1);
3398 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3399 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3401 // Note that we only push one route into `expect_find_route` at a time, because that's all
3402 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3403 // we should still ultimately fail for the same reason - because we're trying to send too
3404 // many HTLCs at once.
3405 let mut new_route_params = route_params.clone();
3406 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3407 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3408 new_route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 100_000);
3409 route.paths[0].hops[1].short_channel_id += 1;
3410 route.route_params = Some(new_route_params.clone());
3411 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3413 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3414 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3415 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3416 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3417 // This races with our other threads which may generate an add-HTLCs commitment update via
3418 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3419 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3420 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3421 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3423 let cur_time = Instant::now();
3424 if cur_time > end_time {
3425 for thread in threads.drain(..) { thread.join().unwrap(); }
3428 // Make sure we have some events to handle when we go around...
3429 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3430 nodes[0].node.process_pending_htlc_forwards();
3431 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3432 check_added_monitors!(nodes[0], 2);
3434 if cur_time > end_time {
3440 fn do_no_missing_sent_on_reload(persist_manager_with_payment: bool, at_midpoint: bool) {
3441 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3442 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3443 // it was last persisted.
3444 let chanmon_cfgs = create_chanmon_cfgs(2);
3445 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3446 let (persister_a, persister_b, persister_c);
3447 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3448 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3449 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3450 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3452 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3454 let mut nodes_0_serialized = Vec::new();
3455 if !persist_manager_with_payment {
3456 nodes_0_serialized = nodes[0].node.encode();
3459 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3461 if persist_manager_with_payment {
3462 nodes_0_serialized = nodes[0].node.encode();
3465 nodes[1].node.claim_funds(our_payment_preimage);
3466 check_added_monitors!(nodes[1], 1);
3467 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3470 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3471 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3472 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3473 check_added_monitors!(nodes[0], 1);
3475 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3476 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
3477 commitment_signed_dance!(nodes[0], nodes[1], htlc_fulfill_updates.commitment_signed, false);
3478 // Ignore the PaymentSent event which is now pending on nodes[0] - if we were to handle it we'd
3479 // be expected to ignore the eventual conflicting PaymentFailed, but by not looking at it we
3480 // expect to get the PaymentSent again later.
3481 check_added_monitors(&nodes[0], 0);
3484 // The ChannelMonitor should always be the latest version, as we're required to persist it
3485 // during the commitment signed handling.
3486 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3487 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3489 let events = nodes[0].node.get_and_clear_pending_events();
3490 assert_eq!(events.len(), 2);
3491 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3492 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3493 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3494 // the double-claim that would otherwise appear at the end of this test.
3495 nodes[0].node.timer_tick_occurred();
3496 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3497 assert_eq!(as_broadcasted_txn.len(), 1);
3499 // Ensure that, even after some time, if we restart we still include *something* in the current
3500 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3501 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3502 // A naive implementation of the fix here would wipe the pending payments set, causing a
3503 // failure event when we restart.
3504 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3506 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3507 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);
3508 let events = nodes[0].node.get_and_clear_pending_events();
3509 assert!(events.is_empty());
3511 // Ensure that we don't generate any further events even after the channel-closing commitment
3512 // transaction is confirmed on-chain.
3513 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3514 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3516 let events = nodes[0].node.get_and_clear_pending_events();
3517 assert!(events.is_empty());
3519 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3520 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);
3521 let events = nodes[0].node.get_and_clear_pending_events();
3522 assert!(events.is_empty());
3523 check_added_monitors(&nodes[0], 1);
3527 fn no_missing_sent_on_midpoint_reload() {
3528 do_no_missing_sent_on_reload(false, true);
3529 do_no_missing_sent_on_reload(true, true);
3533 fn no_missing_sent_on_reload() {
3534 do_no_missing_sent_on_reload(false, false);
3535 do_no_missing_sent_on_reload(true, false);
3538 fn do_claim_from_closed_chan(fail_payment: bool) {
3539 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3540 // received had been closed between when the HTLC was received and when we went to claim it.
3541 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3542 // presumably the sender may retry later. Long ago it also reduced total code in the claim
3545 // However, this doesn't make sense if you're trying to do an atomic swap or some other
3546 // protocol that requires atomicity with some other action - if your money got claimed
3547 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3548 // is an over-optimization - there should be a very, very low likelihood that a channel closes
3549 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3550 // Since we now have code to handle this anyway we should allow it.
3552 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3553 // CLTVs on the paths to different value resulting in a different claim deadline.
3554 let chanmon_cfgs = create_chanmon_cfgs(4);
3555 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3556 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3557 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3559 create_announced_chan_between_nodes(&nodes, 0, 1);
3560 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3561 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3562 create_announced_chan_between_nodes(&nodes, 2, 3);
3564 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3565 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3566 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
3567 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000_000);
3568 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3569 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3570 // Make sure the route is ordered as the B->D path before C->D
3571 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3572 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3574 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3575 // the HTLC is being relayed.
3576 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3577 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3578 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3580 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3581 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3582 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3583 check_added_monitors(&nodes[0], 2);
3584 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3585 send_msgs.sort_by(|a, _| {
3587 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3588 let node_b_id = nodes[1].node.get_our_node_id();
3589 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3592 assert_eq!(send_msgs.len(), 2);
3593 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3594 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3595 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3596 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3598 match receive_event.unwrap() {
3599 Event::PaymentClaimable { claim_deadline, .. } => {
3600 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3605 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3607 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3608 - if fail_payment { 0 } else { 2 });
3609 let error_message = "Channel force-closed";
3611 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3612 // and expire both immediately, though, by connecting another 4 blocks.
3613 let reason = HTLCDestination::FailedPayment { payment_hash };
3614 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3615 connect_blocks(&nodes[3], 4);
3616 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3617 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3619 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id(), error_message.to_string()).unwrap();
3620 check_closed_event!(&nodes[1], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, false,
3621 [nodes[3].node.get_our_node_id()], 1000000);
3622 check_closed_broadcast(&nodes[1], 1, true);
3623 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3624 assert_eq!(bs_tx.len(), 1);
3626 mine_transaction(&nodes[3], &bs_tx[0]);
3627 check_added_monitors(&nodes[3], 1);
3628 check_closed_broadcast(&nodes[3], 1, true);
3629 check_closed_event!(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false,
3630 [nodes[1].node.get_our_node_id()], 1000000);
3632 nodes[3].node.claim_funds(payment_preimage);
3633 check_added_monitors(&nodes[3], 2);
3634 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3636 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3637 assert_eq!(ds_tx.len(), 1);
3638 check_spends!(&ds_tx[0], &bs_tx[0]);
3640 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3641 check_added_monitors(&nodes[1], 1);
3642 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3644 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3645 check_added_monitors(&nodes[1], 1);
3646 assert_eq!(bs_claims.len(), 1);
3647 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3648 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3649 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3650 } else { panic!(); }
3652 expect_payment_sent!(nodes[0], payment_preimage);
3654 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3655 assert_eq!(ds_claim_msgs.len(), 1);
3656 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3657 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3658 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3659 check_added_monitors(&nodes[2], 1);
3660 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3661 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3663 } else { panic!(); };
3665 assert_eq!(cs_claim_msgs.len(), 1);
3666 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3667 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3668 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3669 } else { panic!(); }
3671 expect_payment_path_successful!(nodes[0]);
3676 fn claim_from_closed_chan() {
3677 do_claim_from_closed_chan(true);
3678 do_claim_from_closed_chan(false);
3682 fn test_custom_tlvs_basic() {
3683 do_test_custom_tlvs(false, false, false);
3684 do_test_custom_tlvs(true, false, false);
3688 fn test_custom_tlvs_explicit_claim() {
3689 // Test that when receiving even custom TLVs the user must explicitly accept in case they
3691 do_test_custom_tlvs(false, true, false);
3692 do_test_custom_tlvs(false, true, true);
3695 fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) {
3696 let chanmon_cfgs = create_chanmon_cfgs(2);
3697 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3698 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None; 2]);
3699 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3701 create_announced_chan_between_nodes(&nodes, 0, 1);
3703 let amt_msat = 100_000;
3704 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat);
3705 let payment_id = PaymentId(our_payment_hash.0);
3706 let custom_tlvs = vec![
3707 (if even_tlvs { 5482373482 } else { 5482373483 }, vec![1, 2, 3, 4]),
3708 (5482373487, vec![0x42u8; 16]),
3710 let onion_fields = RecipientOnionFields {
3711 payment_secret: if spontaneous { None } else { Some(our_payment_secret) },
3712 payment_metadata: None,
3713 custom_tlvs: custom_tlvs.clone()
3716 nodes[0].node.send_spontaneous_payment(&route, Some(our_payment_preimage), onion_fields, payment_id).unwrap();
3718 nodes[0].node.send_payment_with_route(&route, our_payment_hash, onion_fields, payment_id).unwrap();
3720 check_added_monitors(&nodes[0], 1);
3722 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3723 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
3724 let mut payment_event = SendEvent::from_event(ev);
3726 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3727 check_added_monitors!(&nodes[1], 0);
3728 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3729 expect_pending_htlcs_forwardable!(nodes[1]);
3731 let events = nodes[1].node.get_and_clear_pending_events();
3732 assert_eq!(events.len(), 1);
3734 Event::PaymentClaimable { ref onion_fields, .. } => {
3735 assert_eq!(onion_fields.clone().unwrap().custom_tlvs().clone(), custom_tlvs);
3737 _ => panic!("Unexpected event"),
3740 match (known_tlvs, even_tlvs) {
3742 nodes[1].node.claim_funds_with_known_custom_tlvs(our_payment_preimage);
3743 let expected_total_fee_msat = pass_claimed_payment_along_route(
3744 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1]]], our_payment_preimage)
3745 .with_custom_tlvs(custom_tlvs)
3747 expect_payment_sent!(&nodes[0], our_payment_preimage, Some(expected_total_fee_msat));
3750 claim_payment_along_route(
3751 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1]]], our_payment_preimage)
3752 .with_custom_tlvs(custom_tlvs)
3756 nodes[1].node.claim_funds(our_payment_preimage);
3757 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3758 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], expected_destinations);
3759 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, our_payment_hash, PaymentFailureReason::RecipientRejected);
3765 fn test_retry_custom_tlvs() {
3766 // Test that custom TLVs are successfully sent on retries
3767 let chanmon_cfgs = create_chanmon_cfgs(3);
3768 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3769 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3770 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3772 create_announced_chan_between_nodes(&nodes, 0, 1);
3773 let (chan_2_update, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 2, 1);
3776 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3778 let amt_msat = 1_000_000;
3779 let (mut route, payment_hash, payment_preimage, payment_secret) =
3780 get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
3782 // Initiate the payment
3783 let payment_id = PaymentId(payment_hash.0);
3784 let mut route_params = route.route_params.clone().unwrap();
3786 let custom_tlvs = vec![((1 << 16) + 1, vec![0x42u8; 16])];
3787 let onion_fields = RecipientOnionFields::secret_only(payment_secret);
3788 let onion_fields = onion_fields.with_custom_tlvs(custom_tlvs.clone()).unwrap();
3790 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3791 nodes[0].node.send_payment(payment_hash, onion_fields,
3792 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3793 check_added_monitors!(nodes[0], 1); // one monitor per path
3795 // Add the HTLC along the first hop.
3796 let htlc_updates = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
3797 let msgs::CommitmentUpdate { update_add_htlcs, commitment_signed, .. } = htlc_updates;
3798 assert_eq!(update_add_htlcs.len(), 1);
3799 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_htlcs[0]);
3800 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
3802 // Attempt to forward the payment and complete the path's failure.
3803 expect_pending_htlcs_forwardable!(&nodes[1]);
3804 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1],
3805 vec![HTLCDestination::NextHopChannel {
3806 node_id: Some(nodes[2].node.get_our_node_id()),
3807 channel_id: chan_2_id
3809 check_added_monitors!(nodes[1], 1);
3811 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3812 let msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } = htlc_updates;
3813 assert_eq!(update_fail_htlcs.len(), 1);
3814 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3815 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
3817 let mut events = nodes[0].node.get_and_clear_pending_events();
3819 Event::PendingHTLCsForwardable { .. } => {},
3820 _ => panic!("Unexpected event")
3823 expect_payment_failed_conditions_event(events, payment_hash, false,
3824 PaymentFailedConditions::new().mpp_parts_remain());
3826 // Rebalance the channel so the retry of the payment can succeed.
3827 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3829 // Retry the payment and make sure it succeeds
3830 route_params.payment_params.previously_failed_channels.push(chan_2_update.contents.short_channel_id);
3831 route.route_params = Some(route_params.clone());
3832 nodes[0].router.expect_find_route(route_params, Ok(route));
3833 nodes[0].node.process_pending_htlc_forwards();
3834 check_added_monitors!(nodes[0], 1);
3835 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3836 assert_eq!(events.len(), 1);
3837 let path = &[&nodes[1], &nodes[2]];
3838 let args = PassAlongPathArgs::new(&nodes[0], path, 1_000_000, payment_hash, events.pop().unwrap())
3839 .with_payment_secret(payment_secret)
3840 .with_custom_tlvs(custom_tlvs.clone());
3841 do_pass_along_path(args);
3842 claim_payment_along_route(
3843 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[2]]], payment_preimage)
3844 .with_custom_tlvs(custom_tlvs)
3849 fn test_custom_tlvs_consistency() {
3850 let even_type_1 = 1 << 16;
3851 let odd_type_1 = (1 << 16)+ 1;
3852 let even_type_2 = (1 << 16) + 2;
3853 let odd_type_2 = (1 << 16) + 3;
3854 let value_1 = || vec![1, 2, 3, 4];
3855 let differing_value_1 = || vec![1, 2, 3, 5];
3856 let value_2 = || vec![42u8; 16];
3858 // Drop missing odd tlvs
3859 do_test_custom_tlvs_consistency(
3860 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3861 vec![(odd_type_1, value_1())],
3862 Some(vec![(odd_type_1, value_1())]),
3864 // Drop non-matching odd tlvs
3865 do_test_custom_tlvs_consistency(
3866 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3867 vec![(odd_type_1, differing_value_1()), (odd_type_2, value_2())],
3868 Some(vec![(odd_type_2, value_2())]),
3870 // Fail missing even tlvs
3871 do_test_custom_tlvs_consistency(
3872 vec![(odd_type_1, value_1()), (even_type_2, value_2())],
3873 vec![(odd_type_1, value_1())],
3876 // Fail non-matching even tlvs
3877 do_test_custom_tlvs_consistency(
3878 vec![(even_type_1, value_1()), (odd_type_2, value_2())],
3879 vec![(even_type_1, differing_value_1()), (odd_type_2, value_2())],
3884 fn do_test_custom_tlvs_consistency(first_tlvs: Vec<(u64, Vec<u8>)>, second_tlvs: Vec<(u64, Vec<u8>)>,
3885 expected_receive_tlvs: Option<Vec<(u64, Vec<u8>)>>) {
3887 let chanmon_cfgs = create_chanmon_cfgs(4);
3888 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3889 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3890 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3892 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
3893 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
3894 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
3895 let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
3897 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3898 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
3899 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
3900 assert_eq!(route.paths.len(), 2);
3901 route.paths.sort_by(|path_a, _| {
3902 // Sort the path so that the path through nodes[1] comes first
3903 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3904 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
3907 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
3908 let payment_id = PaymentId([42; 32]);
3909 let amt_msat = 15_000_000;
3912 let onion_fields = RecipientOnionFields {
3913 payment_secret: Some(our_payment_secret),
3914 payment_metadata: None,
3915 custom_tlvs: first_tlvs
3917 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
3918 onion_fields.clone(), payment_id, &route).unwrap();
3919 let cur_height = nodes[0].best_block_info().1;
3920 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
3921 onion_fields.clone(), amt_msat, cur_height, payment_id,
3922 &None, session_privs[0]).unwrap();
3923 check_added_monitors!(nodes[0], 1);
3926 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3927 assert_eq!(events.len(), 1);
3928 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, our_payment_hash,
3929 Some(our_payment_secret), events.pop().unwrap(), false, None);
3931 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
3934 let onion_fields = RecipientOnionFields {
3935 payment_secret: Some(our_payment_secret),
3936 payment_metadata: None,
3937 custom_tlvs: second_tlvs
3939 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
3940 onion_fields.clone(), amt_msat, cur_height, payment_id, &None, session_privs[1]).unwrap();
3941 check_added_monitors!(nodes[0], 1);
3944 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3945 assert_eq!(events.len(), 1);
3946 let payment_event = SendEvent::from_event(events.pop().unwrap());
3948 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3949 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
3951 expect_pending_htlcs_forwardable!(nodes[2]);
3952 check_added_monitors!(nodes[2], 1);
3954 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
3955 assert_eq!(events.len(), 1);
3956 let payment_event = SendEvent::from_event(events.pop().unwrap());
3958 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
3959 check_added_monitors!(nodes[3], 0);
3960 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
3962 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3963 nodes[3].node.process_pending_htlc_forwards();
3965 if let Some(expected_tlvs) = expected_receive_tlvs {
3966 // Claim and match expected
3967 let events = nodes[3].node.get_and_clear_pending_events();
3968 assert_eq!(events.len(), 1);
3970 Event::PaymentClaimable { ref onion_fields, .. } => {
3971 assert_eq!(onion_fields.clone().unwrap().custom_tlvs, expected_tlvs);
3973 _ => panic!("Unexpected event"),
3976 do_claim_payment_along_route(
3977 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], our_payment_preimage)
3978 .with_custom_tlvs(expected_tlvs)
3980 expect_payment_sent(&nodes[0], our_payment_preimage, Some(Some(2000)), true, true);
3983 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3984 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], expected_destinations);
3985 check_added_monitors!(nodes[3], 1);
3987 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
3988 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
3989 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
3991 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![
3992 HTLCDestination::NextHopChannel {
3993 node_id: Some(nodes[3].node.get_our_node_id()),
3994 channel_id: chan_2_3.2
3996 check_added_monitors!(nodes[2], 1);
3998 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
3999 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
4000 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
4002 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true,
4003 PaymentFailedConditions::new().mpp_parts_remain());
4007 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
4008 // Check that a payment metadata received on one HTLC that doesn't match the one received on
4009 // another results in the HTLC being rejected.
4011 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
4012 // first of which we'll deliver and the second of which we'll fail and then re-send with
4013 // modified payment metadata, which will in turn result in it being failed by the recipient.
4014 let chanmon_cfgs = create_chanmon_cfgs(4);
4015 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4017 let new_chain_monitor;
4019 let mut config = test_default_channel_config();
4020 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
4021 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
4022 let nodes_0_deserialized;
4024 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4026 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
4027 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
4028 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
4029 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
4031 // Pay more than half of each channel's max, requiring MPP
4032 let amt_msat = 750_000_000;
4033 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
4034 let payment_id = PaymentId(payment_hash.0);
4035 let payment_metadata = vec![44, 49, 52, 142];
4037 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
4038 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
4039 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
4041 // Send the MPP payment, delivering the updated commitment state to nodes[1].
4042 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
4043 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata), custom_tlvs: vec![],
4044 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
4045 check_added_monitors!(nodes[0], 2);
4047 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
4048 assert_eq!(send_events.len(), 2);
4049 let first_send = SendEvent::from_event(send_events.pop().unwrap());
4050 let second_send = SendEvent::from_event(send_events.pop().unwrap());
4052 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
4053 (&first_send, &second_send)
4055 (&second_send, &first_send)
4057 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
4058 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
4060 expect_pending_htlcs_forwardable!(nodes[1]);
4061 check_added_monitors(&nodes[1], 1);
4062 let b_forward_ev = SendEvent::from_node(&nodes[1]);
4063 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
4064 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
4066 expect_pending_htlcs_forwardable!(nodes[3]);
4068 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
4069 // will result in nodes[2] failing the HTLC back.
4070 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4071 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
4073 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
4074 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
4076 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
4077 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
4078 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
4080 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
4081 assert_eq!(payment_fail_retryable_evs.len(), 2);
4082 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
4083 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
4085 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
4086 // stored for our payment.
4088 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
4091 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
4092 // the payment state.
4094 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
4095 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
4096 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
4097 persister, new_chain_monitor, nodes_0_deserialized);
4098 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4099 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
4101 let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
4102 reconnect_args.send_channel_ready = (true, true);
4103 reconnect_nodes(reconnect_args);
4105 // Create a new channel between C and D as A will refuse to retry on the existing one because
4107 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0);
4109 // Now retry the failed HTLC.
4110 nodes[0].node.process_pending_htlc_forwards();
4111 check_added_monitors(&nodes[0], 1);
4112 let as_resend = SendEvent::from_node(&nodes[0]);
4113 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
4114 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
4116 expect_pending_htlcs_forwardable!(nodes[2]);
4117 check_added_monitors(&nodes[2], 1);
4118 let cs_forward = SendEvent::from_node(&nodes[2]);
4119 let cd_channel_used = cs_forward.msgs[0].channel_id;
4120 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
4121 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
4123 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
4124 // the payment metadata was modified, failing only the one modified HTLC and retaining the
4127 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
4128 nodes[3].node.process_pending_htlc_forwards();
4129 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
4130 &[HTLCDestination::FailedPayment {payment_hash}]);
4131 nodes[3].node.process_pending_htlc_forwards();
4133 check_added_monitors(&nodes[3], 1);
4134 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
4136 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
4137 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
4138 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
4139 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: cd_channel_used }]);
4141 expect_pending_htlcs_forwardable!(nodes[3]);
4142 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
4143 claim_payment_along_route(
4144 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], payment_preimage)
4150 fn test_payment_metadata_consistency() {
4151 do_test_payment_metadata_consistency(true, true);
4152 do_test_payment_metadata_consistency(true, false);
4153 do_test_payment_metadata_consistency(false, true);
4154 do_test_payment_metadata_consistency(false, false);
4158 fn test_htlc_forward_considers_anchor_outputs_value() {
4161 // 1) Forwarding nodes don't forward HTLCs that would cause their balance to dip below the
4162 // reserve when considering the value of anchor outputs.
4164 // 2) Recipients of `update_add_htlc` properly reject HTLCs that would cause the initiator's
4165 // balance to dip below the reserve when considering the value of anchor outputs.
4166 let mut config = test_default_channel_config();
4167 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
4168 config.manually_accept_inbound_channels = true;
4169 config.channel_config.forwarding_fee_base_msat = 0;
4170 config.channel_config.forwarding_fee_proportional_millionths = 0;
4172 // Set up a test network of three nodes that replicates a production failure leading to the
4173 // discovery of this bug.
4174 let chanmon_cfgs = create_chanmon_cfgs(3);
4175 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4176 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(config)]);
4177 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4179 const CHAN_AMT: u64 = 1_000_000;
4180 const PUSH_MSAT: u64 = 900_000_000;
4181 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, CHAN_AMT, 500_000_000);
4182 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, CHAN_AMT, PUSH_MSAT);
4184 let channel_reserve_msat = get_holder_selected_channel_reserve_satoshis(CHAN_AMT, &config) * 1000;
4185 let commitment_fee_msat = commit_tx_fee_msat(
4186 *nodes[1].fee_estimator.sat_per_kw.lock().unwrap(), 2, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()
4188 let anchor_outpus_value_msat = ANCHOR_OUTPUT_VALUE_SATOSHI * 2 * 1000;
4189 let sendable_balance_msat = CHAN_AMT * 1000 - PUSH_MSAT - channel_reserve_msat - commitment_fee_msat - anchor_outpus_value_msat;
4190 let channel_details = nodes[1].node.list_channels().into_iter().find(|channel| channel.channel_id == chan_id_2).unwrap();
4191 assert!(sendable_balance_msat >= channel_details.next_outbound_htlc_minimum_msat);
4192 assert!(sendable_balance_msat <= channel_details.next_outbound_htlc_limit_msat);
4194 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], sendable_balance_msat);
4195 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], sendable_balance_msat);
4197 // Send out an HTLC that would cause the forwarding node to dip below its reserve when
4198 // considering the value of anchor outputs.
4199 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(
4200 nodes[0], nodes[2], sendable_balance_msat + anchor_outpus_value_msat
4202 nodes[0].node.send_payment_with_route(
4203 &route, payment_hash, RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
4205 check_added_monitors!(nodes[0], 1);
4207 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4208 assert_eq!(events.len(), 1);
4209 let mut update_add_htlc = if let MessageSendEvent::UpdateHTLCs { updates, .. } = events.pop().unwrap() {
4210 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
4211 check_added_monitors(&nodes[1], 0);
4212 commitment_signed_dance!(nodes[1], nodes[0], &updates.commitment_signed, false);
4213 updates.update_add_htlcs[0].clone()
4215 panic!("Unexpected event");
4218 // The forwarding node should reject forwarding it as expected.
4219 expect_pending_htlcs_forwardable!(nodes[1]);
4220 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1], vec![HTLCDestination::NextHopChannel {
4221 node_id: Some(nodes[2].node.get_our_node_id()),
4222 channel_id: chan_id_2
4224 check_added_monitors(&nodes[1], 1);
4226 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
4227 assert_eq!(events.len(), 1);
4228 if let MessageSendEvent::UpdateHTLCs { updates, .. } = events.pop().unwrap() {
4229 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4230 check_added_monitors(&nodes[0], 0);
4231 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4233 panic!("Unexpected event");
4236 expect_payment_failed!(nodes[0], payment_hash, false);
4238 // Assume that the forwarding node did forward it, and make sure the recipient rejects it as an
4239 // invalid update and closes the channel.
4240 update_add_htlc.channel_id = chan_id_2;
4241 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
4242 check_closed_event(&nodes[2], 1, ClosureReason::ProcessingError {
4243 err: "Remote HTLC add would put them under remote reserve value".to_owned()
4244 }, false, &[nodes[1].node.get_our_node_id()], 1_000_000);
4245 check_closed_broadcast(&nodes[2], 1, true);
4246 check_added_monitors(&nodes[2], 1);
4250 fn peel_payment_onion_custom_tlvs() {
4251 let chanmon_cfgs = create_chanmon_cfgs(2);
4252 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4253 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4254 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4255 create_announced_chan_between_nodes(&nodes, 0, 1);
4256 let secp_ctx = Secp256k1::new();
4258 let amt_msat = 1000;
4259 let payment_params = PaymentParameters::for_keysend(nodes[1].node.get_our_node_id(),
4260 TEST_FINAL_CLTV, false);
4261 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
4262 let route = functional_test_utils::get_route(&nodes[0], &route_params).unwrap();
4263 let mut recipient_onion = RecipientOnionFields::spontaneous_empty()
4264 .with_custom_tlvs(vec![(414141, vec![42; 1200])]).unwrap();
4265 let prng_seed = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
4266 let session_priv = SecretKey::from_slice(&prng_seed[..]).expect("RNG is busted");
4267 let keysend_preimage = PaymentPreimage([42; 32]);
4268 let payment_hash = PaymentHash(Sha256::hash(&keysend_preimage.0).to_byte_array());
4270 let (onion_routing_packet, first_hop_msat, cltv_expiry) = onion_utils::create_payment_onion(
4271 &secp_ctx, &route.paths[0], &session_priv, amt_msat, &recipient_onion,
4272 nodes[0].best_block_info().1, &payment_hash, &Some(keysend_preimage), prng_seed
4275 let update_add = msgs::UpdateAddHTLC {
4276 channel_id: ChannelId([0; 32]),
4278 amount_msat: first_hop_msat,
4281 skimmed_fee_msat: None,
4282 onion_routing_packet,
4283 blinding_point: None,
4285 let peeled_onion = crate::ln::onion_payment::peel_payment_onion(
4286 &update_add, &&chanmon_cfgs[1].keys_manager, &&chanmon_cfgs[1].logger, &secp_ctx,
4287 nodes[1].best_block_info().1, true, false
4289 assert_eq!(peeled_onion.incoming_amt_msat, Some(amt_msat));
4290 match peeled_onion.routing {
4291 PendingHTLCRouting::ReceiveKeysend {
4292 payment_data, payment_metadata, custom_tlvs, ..
4294 #[cfg(not(c_bindings))]
4295 assert_eq!(&custom_tlvs, recipient_onion.custom_tlvs());
4297 assert_eq!(custom_tlvs, recipient_onion.custom_tlvs());
4298 assert!(payment_metadata.is_none());
4299 assert!(payment_data.is_none());
4306 fn test_non_strict_forwarding() {
4307 let chanmon_cfgs = create_chanmon_cfgs(3);
4308 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4309 let mut config = test_default_channel_config();
4310 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
4311 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(config)]);
4312 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4314 // Create a routing node with two outbound channels, each of which can forward 2 payments of
4316 let payment_value = 1_500_000;
4317 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
4318 let (chan_update_1, _, channel_id_1, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 4_950, 0);
4319 let (chan_update_2, _, channel_id_2, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 5_000, 0);
4321 // Create a route once.
4322 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
4323 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap();
4324 let route_params = RouteParameters::from_payment_params_and_value(payment_params, payment_value);
4325 let route = functional_test_utils::get_route(&nodes[0], &route_params).unwrap();
4327 // Send 4 payments over the same route.
4329 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(payment_value), None);
4330 nodes[0].node.send_payment_with_route(&route, payment_hash,
4331 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
4332 check_added_monitors!(nodes[0], 1);
4333 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4334 assert_eq!(msg_events.len(), 1);
4335 let mut send_event = SendEvent::from_event(msg_events.remove(0));
4336 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
4337 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
4339 expect_pending_htlcs_forwardable!(nodes[1]);
4340 check_added_monitors!(nodes[1], 1);
4341 msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4342 assert_eq!(msg_events.len(), 1);
4343 send_event = SendEvent::from_event(msg_events.remove(0));
4344 // The HTLC will be forwarded over the most appropriate channel with the corresponding peer,
4345 // applying non-strict forwarding.
4346 // The channel with the least amount of outbound liquidity will be used to maximize the
4347 // probability of being able to successfully forward a subsequent HTLC.
4348 assert_eq!(send_event.msgs[0].channel_id, if i < 2 {
4353 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
4354 commitment_signed_dance!(nodes[2], nodes[1], &send_event.commitment_msg, false);
4356 expect_pending_htlcs_forwardable!(nodes[2]);
4357 let events = nodes[2].node.get_and_clear_pending_events();
4358 assert_eq!(events.len(), 1);
4359 assert!(matches!(events[0], Event::PaymentClaimable { .. }));
4361 claim_payment_along_route(
4362 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[2]]], payment_preimage)
4366 // Send a 5th payment which will fail.
4367 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(payment_value), None);
4368 nodes[0].node.send_payment_with_route(&route, payment_hash,
4369 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
4370 check_added_monitors!(nodes[0], 1);
4371 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4372 assert_eq!(msg_events.len(), 1);
4373 let mut send_event = SendEvent::from_event(msg_events.remove(0));
4374 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
4375 commitment_signed_dance!(nodes[1], nodes[0], &send_event.commitment_msg, false);
4377 expect_pending_htlcs_forwardable!(nodes[1]);
4378 check_added_monitors!(nodes[1], 1);
4379 let routed_scid = route.paths[0].hops[1].short_channel_id;
4380 let routed_channel_id = match routed_scid {
4381 scid if scid == chan_update_1.contents.short_channel_id => channel_id_1,
4382 scid if scid == chan_update_2.contents.short_channel_id => channel_id_2,
4383 _ => panic!("Unexpected short channel id in route"),
4385 // The failure to forward will refer to the channel given in the onion.
4386 expect_pending_htlcs_forwardable_conditions(nodes[1].node.get_and_clear_pending_events(),
4387 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: routed_channel_id }]);
4389 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4390 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4391 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
4392 let events = nodes[0].node.get_and_clear_pending_events();
4393 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().blamed_scid(routed_scid));