1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test the payment retry logic in ChannelManager, including various edge-cases around
11 //! serialization ordering between ChannelManager/ChannelMonitors and ensuring we can still retry
12 //! payments thereafter.
14 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
15 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::sign::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason, PaymentPurpose};
19 use crate::ln::channel::{EXPIRE_PREV_CONFIG_TICKS, commit_tx_fee_msat, get_holder_selected_channel_reserve_satoshis, ANCHOR_OUTPUT_VALUE_SATOSHI};
20 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, RecentPaymentDetails, RecipientOnionFields, HTLCForwardInfo, PendingHTLCRouting, PendingAddHTLCInfo};
21 use crate::ln::features::{Bolt11InvoiceFeatures, ChannelTypeFeatures};
22 use crate::ln::{msgs, 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::constants::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(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
167 fn mpp_retry_overpay() {
168 // We create an MPP scenario with two paths in which we need to overpay to reach
169 // htlc_minimum_msat. We then fail the overpaid path and check that on retry our
170 // max_total_routing_fee_msat only accounts for the path's fees, but not for the fees overpaid
171 // in the first attempt.
172 let chanmon_cfgs = create_chanmon_cfgs(4);
173 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
174 let mut user_config = test_default_channel_config();
175 user_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
176 let mut limited_config_1 = user_config.clone();
177 limited_config_1.channel_handshake_config.our_htlc_minimum_msat = 35_000_000;
178 let mut limited_config_2 = user_config.clone();
179 limited_config_2.channel_handshake_config.our_htlc_minimum_msat = 34_500_000;
180 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
181 &[Some(user_config), Some(limited_config_1), Some(limited_config_2), Some(user_config)]);
182 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
184 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 40_000, 0);
185 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 40_000, 0);
186 let (_chan_3_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 40_000, 0);
187 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes_with_value(&nodes, 3, 2, 40_000, 0);
189 let amt_msat = 70_000_000;
190 let max_total_routing_fee_msat = Some(1_000_000);
192 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
193 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
194 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(
195 nodes[0], nodes[3], payment_params, amt_msat, max_total_routing_fee_msat);
197 // Check we overpay on the second path which we're about to fail.
198 assert_eq!(chan_1_update.contents.fee_proportional_millionths, 0);
199 let overpaid_amount_1 = route.paths[0].fee_msat() as u32 - chan_1_update.contents.fee_base_msat;
200 assert_eq!(overpaid_amount_1, 0);
202 assert_eq!(chan_2_update.contents.fee_proportional_millionths, 0);
203 let overpaid_amount_2 = route.paths[1].fee_msat() as u32 - chan_2_update.contents.fee_base_msat;
205 let total_overpaid_amount = overpaid_amount_1 + overpaid_amount_2;
207 // Initiate the payment.
208 let payment_id = PaymentId(payment_hash.0);
209 let mut route_params = route.route_params.clone().unwrap();
211 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
212 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
213 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
214 check_added_monitors!(nodes[0], 2); // one monitor per path
215 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
216 assert_eq!(events.len(), 2);
218 // Pass half of the payment along the success path.
219 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
220 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, payment_hash,
221 Some(payment_secret), success_path_msgs, false, None);
223 // Add the HTLC along the first hop.
224 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
225 let send_event = SendEvent::from_event(fail_path_msgs_1);
226 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
227 commitment_signed_dance!(nodes[2], nodes[0], &send_event.commitment_msg, false);
229 // Attempt to forward the payment and complete the 2nd path's failure.
230 expect_pending_htlcs_forwardable!(&nodes[2]);
231 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[2],
232 vec![HTLCDestination::NextHopChannel {
233 node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_4_id
236 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
237 assert!(htlc_updates.update_add_htlcs.is_empty());
238 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
239 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
240 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
241 check_added_monitors!(nodes[2], 1);
242 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(),
243 &htlc_updates.update_fail_htlcs[0]);
244 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
245 let mut events = nodes[0].node.get_and_clear_pending_events();
247 Event::PendingHTLCsForwardable { .. } => {},
248 _ => panic!("Unexpected event")
251 expect_payment_failed_conditions_event(events, payment_hash, false,
252 PaymentFailedConditions::new().mpp_parts_remain());
254 // Rebalance the channel so the second half of the payment can succeed.
255 send_payment(&nodes[3], &vec!(&nodes[2])[..], 38_000_000);
257 // Retry the second half of the payment and make sure it succeeds.
258 let first_path_value = route.paths[0].final_value_msat();
259 assert_eq!(first_path_value, 36_000_000);
261 route.paths.remove(0);
262 route_params.final_value_msat -= first_path_value;
263 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
264 // Check the remaining max total routing fee for the second attempt accounts only for 1_000 msat
265 // base fee, but not for overpaid value of the first try.
266 route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 1000);
268 route.route_params = Some(route_params.clone());
269 nodes[0].router.expect_find_route(route_params, Ok(route));
270 nodes[0].node.process_pending_htlc_forwards();
272 check_added_monitors!(nodes[0], 1);
273 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
274 assert_eq!(events.len(), 1);
275 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], amt_msat, payment_hash,
276 Some(payment_secret), events.pop().unwrap(), true, None);
278 // Can't use claim_payment_along_route as it doesn't support overpayment, so we break out the
279 // individual steps here.
280 nodes[3].node.claim_funds(payment_preimage);
281 let extra_fees = vec![0, total_overpaid_amount];
282 let expected_route = &[&[&nodes[1], &nodes[3]][..], &[&nodes[2], &nodes[3]][..]];
283 let args = ClaimAlongRouteArgs::new(&nodes[0], &expected_route[..], payment_preimage)
284 .with_expected_min_htlc_overpay(extra_fees);
285 let expected_total_fee_msat = pass_claimed_payment_along_route(args);
286 expect_payment_sent!(&nodes[0], payment_preimage, Some(expected_total_fee_msat));
289 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
290 let chanmon_cfgs = create_chanmon_cfgs(4);
291 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
292 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
293 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
295 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
296 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
297 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
298 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
300 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
301 let path = route.paths[0].clone();
302 route.paths.push(path);
303 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
304 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
305 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
306 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
307 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
308 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
310 // Initiate the MPP payment.
311 nodes[0].node.send_payment_with_route(&route, payment_hash,
312 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
313 check_added_monitors!(nodes[0], 2); // one monitor per path
314 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
315 assert_eq!(events.len(), 2);
317 // Pass half of the payment along the first path.
318 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
319 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
321 if send_partial_mpp {
322 // Time out the partial MPP
323 for _ in 0..MPP_TIMEOUT_TICKS {
324 nodes[3].node.timer_tick_occurred();
327 // Failed HTLC from node 3 -> 1
328 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
329 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
330 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
331 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
332 check_added_monitors!(nodes[3], 1);
333 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
335 // Failed HTLC from node 1 -> 0
336 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 }]);
337 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
338 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
339 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
340 check_added_monitors!(nodes[1], 1);
341 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
343 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
345 // Pass half of the payment along the second path.
346 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
347 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
349 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
350 for _ in 0..MPP_TIMEOUT_TICKS {
351 nodes[3].node.timer_tick_occurred();
354 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
359 fn mpp_receive_timeout() {
360 do_mpp_receive_timeout(true);
361 do_mpp_receive_timeout(false);
365 fn test_keysend_payments() {
366 do_test_keysend_payments(false, false);
367 do_test_keysend_payments(false, true);
368 do_test_keysend_payments(true, false);
369 do_test_keysend_payments(true, true);
372 fn do_test_keysend_payments(public_node: bool, with_retry: bool) {
373 let chanmon_cfgs = create_chanmon_cfgs(2);
374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
376 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
379 create_announced_chan_between_nodes(&nodes, 0, 1);
381 create_chan_between_nodes(&nodes[0], &nodes[1]);
383 let payer_pubkey = nodes[0].node.get_our_node_id();
384 let payee_pubkey = nodes[1].node.get_our_node_id();
385 let route_params = RouteParameters::from_payment_params_and_value(
386 PaymentParameters::for_keysend(payee_pubkey, 40, false), 10000);
388 let network_graph = nodes[0].network_graph;
389 let channels = nodes[0].node.list_usable_channels();
390 let first_hops = channels.iter().collect::<Vec<_>>();
391 let first_hops = if public_node { None } else { Some(first_hops.as_slice()) };
393 let scorer = test_utils::TestScorer::new();
394 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
395 let route = find_route(
396 &payer_pubkey, &route_params, &network_graph, first_hops,
397 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
401 let test_preimage = PaymentPreimage([42; 32]);
403 nodes[0].node.send_spontaneous_payment_with_retry(Some(test_preimage),
404 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0),
405 route_params, Retry::Attempts(1)).unwrap()
407 nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
408 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap()
411 check_added_monitors!(nodes[0], 1);
412 let send_event = SendEvent::from_node(&nodes[0]);
413 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
414 do_commitment_signed_dance(&nodes[1], &nodes[0], &send_event.commitment_msg, false, false);
415 expect_pending_htlcs_forwardable!(nodes[1]);
416 // Previously, a refactor caused us to stop including the payment preimage in the onion which
417 // is sent as a part of keysend payments. Thus, to be extra careful here, we scope the preimage
418 // above to demonstrate that we have no way to get the preimage at this point except by
419 // extracting it from the onion nodes[1] received.
420 let event = nodes[1].node.get_and_clear_pending_events();
421 assert_eq!(event.len(), 1);
422 if let Event::PaymentClaimable { purpose: PaymentPurpose::SpontaneousPayment(preimage), .. } = event[0] {
423 claim_payment(&nodes[0], &[&nodes[1]], preimage);
428 fn test_mpp_keysend() {
429 let mut mpp_keysend_config = test_default_channel_config();
430 mpp_keysend_config.accept_mpp_keysend = true;
431 let chanmon_cfgs = create_chanmon_cfgs(4);
432 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
433 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
434 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
436 create_announced_chan_between_nodes(&nodes, 0, 1);
437 create_announced_chan_between_nodes(&nodes, 0, 2);
438 create_announced_chan_between_nodes(&nodes, 1, 3);
439 create_announced_chan_between_nodes(&nodes, 2, 3);
440 let network_graph = nodes[0].network_graph;
442 let payer_pubkey = nodes[0].node.get_our_node_id();
443 let payee_pubkey = nodes[3].node.get_our_node_id();
444 let recv_value = 15_000_000;
445 let route_params = RouteParameters::from_payment_params_and_value(
446 PaymentParameters::for_keysend(payee_pubkey, 40, true), recv_value);
447 let scorer = test_utils::TestScorer::new();
448 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
449 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger,
450 &scorer, &Default::default(), &random_seed_bytes).unwrap();
452 let payment_preimage = PaymentPreimage([42; 32]);
453 let payment_secret = PaymentSecret(payment_preimage.0);
454 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
455 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_preimage.0)).unwrap();
456 check_added_monitors!(nodes[0], 2);
458 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
459 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
460 assert_eq!(events.len(), 2);
462 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
463 pass_along_path(&nodes[0], expected_route[0], recv_value, payment_hash.clone(),
464 Some(payment_secret), ev.clone(), false, Some(payment_preimage));
466 let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
467 pass_along_path(&nodes[0], expected_route[1], recv_value, payment_hash.clone(),
468 Some(payment_secret), ev.clone(), true, Some(payment_preimage));
469 claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
473 fn test_reject_mpp_keysend_htlc() {
474 // This test enforces that we reject MPP keysend HTLCs if our config states we don't support
475 // MPP keysend. When receiving a payment, if we don't support MPP keysend we'll reject the
476 // payment if it's keysend and has a payment secret, never reaching our payment validation
477 // logic. To check that we enforce rejecting MPP keysends in our payment logic, here we send
478 // keysend payments without payment secrets, then modify them by adding payment secrets in the
479 // final node in between receiving the HTLCs and actually processing them.
480 let mut reject_mpp_keysend_cfg = test_default_channel_config();
481 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
483 let chanmon_cfgs = create_chanmon_cfgs(4);
484 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
485 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(reject_mpp_keysend_cfg)]);
486 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
487 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
488 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
489 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
490 let (update_a, _, chan_4_channel_id, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
491 let chan_4_id = update_a.contents.short_channel_id;
493 let (mut route, payment_hash, payment_preimage, _) = get_route_and_payment_hash!(nodes[0], nodes[3], amount);
495 // Pay along nodes[1]
496 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
497 route.paths[0].hops[0].short_channel_id = chan_1_id;
498 route.paths[0].hops[1].short_channel_id = chan_3_id;
500 let payment_id_0 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
501 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_0).unwrap();
502 check_added_monitors!(nodes[0], 1);
504 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
505 let update_add_0 = update_0.update_add_htlcs[0].clone();
506 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
507 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
508 expect_pending_htlcs_forwardable!(nodes[1]);
510 check_added_monitors!(&nodes[1], 1);
511 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[3].node.get_our_node_id());
512 let update_add_1 = update_1.update_add_htlcs[0].clone();
513 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
514 commitment_signed_dance!(nodes[3], nodes[1], update_1.commitment_signed, false, true);
516 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
517 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
518 for f in pending_forwards.iter_mut() {
520 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
521 match forward_info.routing {
522 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
523 *payment_data = Some(msgs::FinalOnionHopData {
524 payment_secret: PaymentSecret([42; 32]),
525 total_msat: amount * 2,
528 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
535 expect_pending_htlcs_forwardable!(nodes[3]);
537 // Pay along nodes[2]
538 route.paths[0].hops[0].pubkey = nodes[2].node.get_our_node_id();
539 route.paths[0].hops[0].short_channel_id = chan_2_id;
540 route.paths[0].hops[1].short_channel_id = chan_4_id;
542 let payment_id_1 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
543 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
544 check_added_monitors!(nodes[0], 1);
546 let update_2 = get_htlc_update_msgs!(nodes[0], nodes[2].node.get_our_node_id());
547 let update_add_2 = update_2.update_add_htlcs[0].clone();
548 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_2);
549 commitment_signed_dance!(nodes[2], nodes[0], &update_2.commitment_signed, false, true);
550 expect_pending_htlcs_forwardable!(nodes[2]);
552 check_added_monitors!(&nodes[2], 1);
553 let update_3 = get_htlc_update_msgs!(nodes[2], nodes[3].node.get_our_node_id());
554 let update_add_3 = update_3.update_add_htlcs[0].clone();
555 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &update_add_3);
556 commitment_signed_dance!(nodes[3], nodes[2], update_3.commitment_signed, false, true);
558 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
559 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
560 for f in pending_forwards.iter_mut() {
562 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
563 match forward_info.routing {
564 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
565 *payment_data = Some(msgs::FinalOnionHopData {
566 payment_secret: PaymentSecret([42; 32]),
567 total_msat: amount * 2,
570 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
577 expect_pending_htlcs_forwardable!(nodes[3]);
578 check_added_monitors!(nodes[3], 1);
580 // Fail back along nodes[2]
581 let update_fail_0 = get_htlc_update_msgs!(&nodes[3], &nodes[2].node.get_our_node_id());
582 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &update_fail_0.update_fail_htlcs[0]);
583 commitment_signed_dance!(nodes[2], nodes[3], update_fail_0.commitment_signed, false);
584 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 }]);
585 check_added_monitors!(nodes[2], 1);
587 let update_fail_1 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
588 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_1.update_fail_htlcs[0]);
589 commitment_signed_dance!(nodes[0], nodes[2], update_fail_1.commitment_signed, false);
591 expect_payment_failed_conditions(&nodes[0], payment_hash, true, PaymentFailedConditions::new());
592 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
597 fn no_pending_leak_on_initial_send_failure() {
598 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
599 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
600 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
601 // pending payment forever and never time it out.
602 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
603 // try, and then check that no pending payment is being tracked.
604 let chanmon_cfgs = create_chanmon_cfgs(2);
605 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
606 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
607 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
609 create_announced_chan_between_nodes(&nodes, 0, 1);
611 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
613 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
614 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
616 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
617 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
618 ), true, APIError::ChannelUnavailable { ref err },
619 assert_eq!(err, "Peer for first hop currently disconnected"));
621 assert!(!nodes[0].node.has_pending_payments());
624 fn do_retry_with_no_persist(confirm_before_reload: bool) {
625 // If we send a pending payment and `send_payment` returns success, we should always either
626 // return a payment failure event or a payment success event, and on failure the payment should
629 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
630 // always persisted asynchronously), the ChannelManager has to reload some payment data from
631 // ChannelMonitor(s) in some cases. This tests that reloading.
633 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
634 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
635 // which has separate codepaths for "commitment transaction already confirmed" and not.
636 let chanmon_cfgs = create_chanmon_cfgs(3);
637 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
639 let new_chain_monitor;
640 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
641 let nodes_0_deserialized;
642 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
644 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
645 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
647 // Serialize the ChannelManager prior to sending payments
648 let nodes_0_serialized = nodes[0].node.encode();
650 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
652 let amt_msat = 1_000_000;
653 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
654 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
655 let route_params = route.route_params.unwrap().clone();
656 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
657 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
658 check_added_monitors!(nodes[0], 1);
660 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
661 assert_eq!(events.len(), 1);
662 let payment_event = SendEvent::from_event(events.pop().unwrap());
663 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
665 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
666 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
667 // which would prevent retry.
668 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
669 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
671 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
672 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
673 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
674 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
676 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
678 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
679 if confirm_before_reload {
680 mine_transaction(&nodes[0], &as_commitment_tx);
681 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
684 // The ChannelMonitor should always be the latest version, as we're required to persist it
685 // during the `commitment_signed_dance!()`.
686 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
687 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
689 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
690 // force-close the channel.
691 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
692 assert!(nodes[0].node.list_channels().is_empty());
693 assert!(nodes[0].node.has_pending_payments());
694 nodes[0].node.timer_tick_occurred();
695 if !confirm_before_reload {
696 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
697 assert_eq!(as_broadcasted_txn.len(), 1);
698 assert_eq!(as_broadcasted_txn[0].txid(), as_commitment_tx.txid());
700 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
702 check_added_monitors!(nodes[0], 1);
704 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
705 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
706 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
708 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
710 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
711 // error, as the channel has hit the chain.
712 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
713 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
715 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
716 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
717 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
718 assert_eq!(as_err.len(), 2);
720 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
721 assert_eq!(node_id, nodes[1].node.get_our_node_id());
722 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
723 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 {}",
724 &nodes[1].node.get_our_node_id())) }, [nodes[0].node.get_our_node_id()], 100000);
725 check_added_monitors!(nodes[1], 1);
726 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
728 _ => panic!("Unexpected event"),
730 check_closed_broadcast!(nodes[1], false);
732 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
733 // we close in a moment.
734 nodes[2].node.claim_funds(payment_preimage_1);
735 check_added_monitors!(nodes[2], 1);
736 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
738 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
739 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
740 check_added_monitors!(nodes[1], 1);
741 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
742 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, true, false);
744 if confirm_before_reload {
745 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
746 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
749 // Create a new channel on which to retry the payment before we fail the payment via the
750 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
751 // connecting several blocks while creating the channel (implying time has passed).
752 create_announced_chan_between_nodes(&nodes, 0, 1);
753 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
755 mine_transaction(&nodes[1], &as_commitment_tx);
756 let bs_htlc_claim_txn = {
757 let mut txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
758 assert_eq!(txn.len(), 2);
759 check_spends!(txn[0], funding_tx);
760 check_spends!(txn[1], as_commitment_tx);
764 if !confirm_before_reload {
765 mine_transaction(&nodes[0], &as_commitment_tx);
766 let txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
767 assert_eq!(txn.len(), 1);
768 assert_eq!(txn[0].txid(), as_commitment_tx.txid());
770 mine_transaction(&nodes[0], &bs_htlc_claim_txn);
771 expect_payment_sent(&nodes[0], payment_preimage_1, None, true, false);
772 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
773 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
774 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
775 assert_eq!(txn.len(), 2);
776 (txn.remove(0), txn.remove(0))
778 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
779 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
780 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn.input[0].previous_output {
781 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
783 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
785 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
786 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
788 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
789 // reloaded) via a route over the new channel, which work without issue and eventually be
790 // received and claimed at the recipient just like any other payment.
791 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
793 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
794 // and not the original fee. We also update node[1]'s relevant config as
795 // do_claim_payment_along_route expects us to never overpay.
797 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
798 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
799 .unwrap().lock().unwrap();
800 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
801 let mut new_config = channel.context().config();
802 new_config.forwarding_fee_base_msat += 100_000;
803 channel.context_mut().update_config(&new_config);
804 new_route.paths[0].hops[0].fee_msat += 100_000;
807 // Force expiration of the channel's previous config.
808 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
809 nodes[1].node.timer_tick_occurred();
812 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
813 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
814 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
815 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
816 check_added_monitors!(nodes[0], 1);
817 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
818 assert_eq!(events.len(), 1);
819 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
820 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
821 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
825 fn retry_with_no_persist() {
826 do_retry_with_no_persist(true);
827 do_retry_with_no_persist(false);
830 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
831 // Test that an off-chain completed payment is not retryable on restart. This was previously
832 // broken for dust payments, but we test for both dust and non-dust payments.
834 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
836 let chanmon_cfgs = create_chanmon_cfgs(3);
837 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
839 let mut manually_accept_config = test_default_channel_config();
840 manually_accept_config.manually_accept_inbound_channels = true;
843 let first_new_chain_monitor;
844 let second_persister;
845 let second_new_chain_monitor;
847 let third_new_chain_monitor;
849 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
850 let first_nodes_0_deserialized;
851 let second_nodes_0_deserialized;
852 let third_nodes_0_deserialized;
854 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
856 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
857 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
858 confirm_transaction(&nodes[0], &funding_tx);
859 confirm_transaction(&nodes[1], &funding_tx);
860 // Ignore the announcement_signatures messages
861 nodes[0].node.get_and_clear_pending_msg_events();
862 nodes[1].node.get_and_clear_pending_msg_events();
863 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
865 // Serialize the ChannelManager prior to sending payments
866 let mut nodes_0_serialized = nodes[0].node.encode();
868 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
869 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 });
871 // The ChannelMonitor should always be the latest version, as we're required to persist it
872 // during the `commitment_signed_dance!()`.
873 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
875 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);
876 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
878 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
879 // force-close the channel.
880 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
881 nodes[0].node.timer_tick_occurred();
882 assert!(nodes[0].node.list_channels().is_empty());
883 assert!(nodes[0].node.has_pending_payments());
884 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
885 check_added_monitors!(nodes[0], 1);
887 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
888 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
890 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
892 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
893 // error, as the channel has hit the chain.
894 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
895 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
897 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
898 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
899 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
900 assert_eq!(as_err.len(), 2);
901 let bs_commitment_tx;
903 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
904 assert_eq!(node_id, nodes[1].node.get_our_node_id());
905 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
906 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())) }
907 , [nodes[0].node.get_our_node_id()], 100000);
908 check_added_monitors!(nodes[1], 1);
909 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
911 _ => panic!("Unexpected event"),
913 check_closed_broadcast!(nodes[1], false);
915 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
916 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
917 // incoming HTLCs with the same payment hash later.
918 nodes[2].node.fail_htlc_backwards(&payment_hash);
919 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
920 check_added_monitors!(nodes[2], 1);
922 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
923 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
924 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
925 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
926 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
928 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
929 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
930 // after the commitment transaction, so always connect the commitment transaction.
931 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
932 if nodes[0].connect_style.borrow().updates_best_block_first() {
933 let _ = nodes[0].tx_broadcaster.txn_broadcast();
935 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
937 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
938 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
939 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
940 assert_eq!(as_htlc_timeout.len(), 1);
941 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
943 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
944 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
946 if nodes[0].connect_style.borrow().updates_best_block_first() {
947 let _ = nodes[0].tx_broadcaster.txn_broadcast();
950 // Create a new channel on which to retry the payment before we fail the payment via the
951 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
952 // connecting several blocks while creating the channel (implying time has passed).
953 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
954 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
955 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
957 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
958 // confirming, we will fail as it's considered still-pending...
959 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
960 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
961 Err(PaymentSendFailure::DuplicatePayment) => {},
962 _ => panic!("Unexpected error")
964 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
966 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
967 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
968 // (which should also still work).
969 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
970 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
971 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
973 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
974 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
975 nodes_0_serialized = nodes[0].node.encode();
977 // After the payment failed, we're free to send it again.
978 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
979 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
980 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
982 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);
983 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
985 nodes[0].node.test_process_background_events();
986 check_added_monitors(&nodes[0], 1);
988 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
989 reconnect_args.send_channel_ready = (true, true);
990 reconnect_nodes(reconnect_args);
992 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
993 // the payment is not (spuriously) listed as still pending.
994 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
995 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
996 check_added_monitors!(nodes[0], 1);
997 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
998 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1000 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
1001 Err(PaymentSendFailure::DuplicatePayment) => {},
1002 _ => panic!("Unexpected error")
1004 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1006 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1007 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
1008 nodes_0_serialized = nodes[0].node.encode();
1010 // Check that after reload we can send the payment again (though we shouldn't, since it was
1011 // claimed previously).
1012 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);
1013 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
1015 nodes[0].node.test_process_background_events();
1016 check_added_monitors(&nodes[0], 1);
1018 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1020 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
1021 Err(PaymentSendFailure::DuplicatePayment) => {},
1022 _ => panic!("Unexpected error")
1024 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1028 fn test_completed_payment_not_retryable_on_reload() {
1029 do_test_completed_payment_not_retryable_on_reload(true);
1030 do_test_completed_payment_not_retryable_on_reload(false);
1034 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
1035 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
1036 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
1037 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
1038 // the ChannelMonitor tells it to.
1040 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
1041 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
1042 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
1043 let chanmon_cfgs = create_chanmon_cfgs(2);
1044 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1046 let new_chain_monitor;
1047 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1048 let nodes_0_deserialized;
1049 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1051 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
1053 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
1055 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
1056 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
1057 check_closed_broadcast!(nodes[0], true);
1058 check_added_monitors!(nodes[0], 1);
1059 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
1061 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1062 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
1064 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
1065 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
1066 let (commitment_tx, htlc_timeout_tx) = {
1067 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
1068 assert_eq!(txn.len(), 2);
1069 check_spends!(txn[0], funding_tx);
1070 check_spends!(txn[1], txn[0]);
1071 (txn.remove(0), txn.remove(0))
1074 nodes[1].node.claim_funds(payment_preimage);
1075 check_added_monitors!(nodes[1], 1);
1076 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
1078 mine_transaction(&nodes[1], &commitment_tx);
1079 check_closed_broadcast!(nodes[1], true);
1080 check_added_monitors!(nodes[1], 1);
1081 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
1082 let htlc_success_tx = {
1083 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
1084 assert_eq!(txn.len(), 1);
1085 check_spends!(txn[0], commitment_tx);
1089 mine_transaction(&nodes[0], &commitment_tx);
1091 if confirm_commitment_tx {
1092 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
1095 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { vec![htlc_timeout_tx] } else { vec![htlc_success_tx] });
1097 if payment_timeout {
1098 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
1099 connect_block(&nodes[0], &claim_block);
1100 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
1103 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
1104 // returning InProgress. This should cause the claim event to never make its way to the
1106 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
1107 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
1109 if payment_timeout {
1110 connect_blocks(&nodes[0], 1);
1112 connect_block(&nodes[0], &claim_block);
1115 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
1116 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
1117 .get_mut(&funding_txo).unwrap().drain().collect();
1118 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
1119 // If we're testing connection idempotency we may get substantially more.
1120 assert!(mon_updates.len() >= 1);
1121 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
1122 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1124 // If we persist the ChannelManager here, we should get the PaymentSent event after
1126 let mut chan_manager_serialized = Vec::new();
1127 if !persist_manager_post_event {
1128 chan_manager_serialized = nodes[0].node.encode();
1131 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
1132 // payment sent event.
1133 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1134 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1135 for update in mon_updates {
1136 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
1138 if payment_timeout {
1139 expect_payment_failed!(nodes[0], payment_hash, false);
1141 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1144 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
1146 if persist_manager_post_event {
1147 chan_manager_serialized = nodes[0].node.encode();
1150 // Now reload nodes[0]...
1151 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
1153 if persist_manager_post_event {
1154 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1155 } else if payment_timeout {
1156 expect_payment_failed!(nodes[0], payment_hash, false);
1158 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1161 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
1162 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
1163 // payment events should kick in, leaving us with no pending events here.
1164 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
1165 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
1166 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1167 check_added_monitors(&nodes[0], 1);
1171 fn test_dup_htlc_onchain_fails_on_reload() {
1172 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
1173 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
1174 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
1175 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
1176 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
1177 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
1181 fn test_fulfill_restart_failure() {
1182 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
1183 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
1184 // again, or fail it, giving us free money.
1186 // Of course probably they won't fail it and give us free money, but because we have code to
1187 // handle it, we should test the logic for it anyway. We do that here.
1188 let chanmon_cfgs = create_chanmon_cfgs(2);
1189 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1191 let new_chain_monitor;
1192 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1193 let nodes_1_deserialized;
1194 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1196 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1197 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
1199 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
1200 // pre-fulfill, which we do by serializing it here.
1201 let chan_manager_serialized = nodes[1].node.encode();
1202 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1204 nodes[1].node.claim_funds(payment_preimage);
1205 check_added_monitors!(nodes[1], 1);
1206 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1208 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1209 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1210 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
1212 // Now reload nodes[1]...
1213 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1215 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1216 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1218 nodes[1].node.fail_htlc_backwards(&payment_hash);
1219 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1220 check_added_monitors!(nodes[1], 1);
1221 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1222 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1223 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1224 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1225 // it had already considered the payment fulfilled, and now they just got free money.
1226 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1230 fn get_ldk_payment_preimage() {
1231 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1232 let chanmon_cfgs = create_chanmon_cfgs(2);
1233 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1234 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1235 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1236 create_announced_chan_between_nodes(&nodes, 0, 1);
1238 let amt_msat = 60_000;
1239 let expiry_secs = 60 * 60;
1240 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1242 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1243 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
1244 let scorer = test_utils::TestScorer::new();
1245 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1246 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1247 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
1248 let route = get_route( &nodes[0].node.get_our_node_id(), &route_params,
1249 &nodes[0].network_graph.read_only(),
1250 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()), nodes[0].logger,
1251 &scorer, &Default::default(), &random_seed_bytes).unwrap();
1252 nodes[0].node.send_payment_with_route(&route, payment_hash,
1253 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1254 check_added_monitors!(nodes[0], 1);
1256 // Make sure to use `get_payment_preimage`
1257 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1258 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1259 assert_eq!(events.len(), 1);
1260 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1261 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1265 fn sent_probe_is_probe_of_sending_node() {
1266 let chanmon_cfgs = create_chanmon_cfgs(3);
1267 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1268 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1269 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1271 create_announced_chan_between_nodes(&nodes, 0, 1);
1272 create_announced_chan_between_nodes(&nodes, 1, 2);
1274 // First check we refuse to build a single-hop probe
1275 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1276 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1278 // Then build an actual two-hop probing path
1279 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1281 match nodes[0].node.send_probe(route.paths[0].clone()) {
1282 Ok((payment_hash, payment_id)) => {
1283 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1284 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1285 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1290 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1291 check_added_monitors!(nodes[0], 1);
1295 fn successful_probe_yields_event() {
1296 let chanmon_cfgs = create_chanmon_cfgs(3);
1297 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1298 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1299 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1301 create_announced_chan_between_nodes(&nodes, 0, 1);
1302 create_announced_chan_between_nodes(&nodes, 1, 2);
1304 let recv_value = 100_000;
1305 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], recv_value);
1307 let res = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1309 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[2]]];
1311 send_probe_along_route(&nodes[0], expected_route);
1313 expect_probe_successful_events(&nodes[0], vec![res]);
1315 assert!(!nodes[0].node.has_pending_payments());
1319 fn failed_probe_yields_event() {
1320 let chanmon_cfgs = create_chanmon_cfgs(3);
1321 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1322 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1323 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1325 create_announced_chan_between_nodes(&nodes, 0, 1);
1326 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1328 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1330 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 9_998_000);
1332 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1334 // node[0] -- update_add_htlcs -> node[1]
1335 check_added_monitors!(nodes[0], 1);
1336 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1337 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1338 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1339 check_added_monitors!(nodes[1], 0);
1340 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1341 expect_pending_htlcs_forwardable!(nodes[1]);
1343 // node[0] <- update_fail_htlcs -- node[1]
1344 check_added_monitors!(nodes[1], 1);
1345 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1346 // Skip the PendingHTLCsForwardable event
1347 let _events = nodes[1].node.get_and_clear_pending_events();
1348 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1349 check_added_monitors!(nodes[0], 0);
1350 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1352 let mut events = nodes[0].node.get_and_clear_pending_events();
1353 assert_eq!(events.len(), 1);
1354 match events.drain(..).next().unwrap() {
1355 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1356 assert_eq!(payment_id, ev_pid);
1357 assert_eq!(payment_hash, ev_ph);
1361 assert!(!nodes[0].node.has_pending_payments());
1365 fn onchain_failed_probe_yields_event() {
1366 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1368 let chanmon_cfgs = create_chanmon_cfgs(3);
1369 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1370 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1371 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1373 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1374 create_announced_chan_between_nodes(&nodes, 1, 2);
1376 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1378 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1379 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 1_000);
1380 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1382 // node[0] -- update_add_htlcs -> node[1]
1383 check_added_monitors!(nodes[0], 1);
1384 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1385 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1386 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1387 check_added_monitors!(nodes[1], 0);
1388 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1389 expect_pending_htlcs_forwardable!(nodes[1]);
1391 check_added_monitors!(nodes[1], 1);
1392 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1394 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1395 // Node A, which after 6 confirmations should result in a probe failure event.
1396 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1397 confirm_transaction(&nodes[0], &bs_txn[0]);
1398 check_closed_broadcast!(&nodes[0], true);
1399 check_added_monitors!(nodes[0], 1);
1401 let mut events = nodes[0].node.get_and_clear_pending_events();
1402 assert_eq!(events.len(), 2);
1403 let mut found_probe_failed = false;
1404 for event in events.drain(..) {
1406 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1407 assert_eq!(payment_id, ev_pid);
1408 assert_eq!(payment_hash, ev_ph);
1409 found_probe_failed = true;
1411 Event::ChannelClosed { .. } => {},
1415 assert!(found_probe_failed);
1416 assert!(!nodes[0].node.has_pending_payments());
1420 fn preflight_probes_yield_event_skip_private_hop() {
1421 let chanmon_cfgs = create_chanmon_cfgs(5);
1422 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1424 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1425 let mut no_htlc_limit_config = test_default_channel_config();
1426 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1428 let user_configs = std::iter::repeat(no_htlc_limit_config).take(5).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1429 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &user_configs);
1430 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1432 // Setup channel topology:
1433 // N0 -(1M:0)- N1 -(1M:0)- N2 -(70k:0)- N3 -(50k:0)- N4
1435 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1436 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
1437 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 70_000, 0);
1438 create_unannounced_chan_between_nodes_with_value(&nodes, 3, 4, 50_000, 0);
1440 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1441 invoice_features.set_basic_mpp_optional();
1443 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
1444 .with_bolt11_features(invoice_features).unwrap();
1446 let recv_value = 50_000_000;
1447 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1448 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1450 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[2], &nodes[3]]];
1452 assert_eq!(res.len(), expected_route.len());
1454 send_probe_along_route(&nodes[0], expected_route);
1456 expect_probe_successful_events(&nodes[0], res.clone());
1458 assert!(!nodes[0].node.has_pending_payments());
1462 fn preflight_probes_yield_event() {
1463 let chanmon_cfgs = create_chanmon_cfgs(4);
1464 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1466 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1467 let mut no_htlc_limit_config = test_default_channel_config();
1468 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1470 let user_configs = std::iter::repeat(no_htlc_limit_config).take(4).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1471 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &user_configs);
1472 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1474 // Setup channel topology:
1475 // (1M:0)- N1 -(30k:0)
1479 // (1M:0)- N2 -(70k:0)
1481 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1482 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1483 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 30_000, 0);
1484 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 70_000, 0);
1486 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1487 invoice_features.set_basic_mpp_optional();
1489 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
1490 .with_bolt11_features(invoice_features).unwrap();
1492 let recv_value = 50_000_000;
1493 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1494 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1496 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
1498 assert_eq!(res.len(), expected_route.len());
1500 send_probe_along_route(&nodes[0], expected_route);
1502 expect_probe_successful_events(&nodes[0], res.clone());
1504 assert!(!nodes[0].node.has_pending_payments());
1508 fn preflight_probes_yield_event_and_skip() {
1509 let chanmon_cfgs = create_chanmon_cfgs(5);
1510 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1512 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1513 let mut no_htlc_limit_config = test_default_channel_config();
1514 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1516 let user_configs = std::iter::repeat(no_htlc_limit_config).take(5).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1517 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &user_configs);
1518 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1520 // Setup channel topology:
1521 // (30k:0)- N2 -(1M:0)
1523 // N0 -(100k:0)-> N1 N4
1525 // (70k:0)- N3 -(1M:0)
1527 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1528 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 30_000, 0);
1529 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 70_000, 0);
1530 create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 1_000_000, 0);
1531 create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0);
1533 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1534 invoice_features.set_basic_mpp_optional();
1536 let payment_params = PaymentParameters::from_node_id(nodes[4].node.get_our_node_id(), TEST_FINAL_CLTV)
1537 .with_bolt11_features(invoice_features).unwrap();
1539 let recv_value = 80_000_000;
1540 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1541 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1543 let expected_route : &[&[&Node]] = &[&[&nodes[1], &nodes[2], &nodes[4]]];
1545 // We check that only one probe was sent, the other one was skipped due to limited liquidity.
1546 assert_eq!(res.len(), 1);
1548 send_probe_along_route(&nodes[0], expected_route);
1550 expect_probe_successful_events(&nodes[0], res.clone());
1552 assert!(!nodes[0].node.has_pending_payments());
1556 fn claimed_send_payment_idempotent() {
1557 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1558 let chanmon_cfgs = create_chanmon_cfgs(2);
1559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1561 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1563 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1565 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1566 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1568 macro_rules! check_send_rejected {
1570 // If we try to resend a new payment with a different payment_hash but with the same
1571 // payment_id, it should be rejected.
1572 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1573 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1575 Err(PaymentSendFailure::DuplicatePayment) => {},
1576 _ => panic!("Unexpected send result: {:?}", send_result),
1579 // Further, if we try to send a spontaneous payment with the same payment_id it should
1580 // also be rejected.
1581 let send_result = nodes[0].node.send_spontaneous_payment(
1582 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1584 Err(PaymentSendFailure::DuplicatePayment) => {},
1585 _ => panic!("Unexpected send result: {:?}", send_result),
1590 check_send_rejected!();
1592 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1593 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1594 // we must remain just as idempotent as we were before.
1595 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, 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(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1997 let events = nodes[0].node.get_and_clear_pending_events();
1998 assert_eq!(events.len(), 2);
2000 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
2001 assert_eq!(payment_preimage, *ev_preimage);
2002 assert_eq!(payment_hash, *ev_hash);
2003 assert_eq!(fee_paid_msat, &Some(1000));
2005 _ => panic!("Unexpected event")
2008 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
2009 assert_eq!(hash, Some(payment_hash));
2011 _ => panic!("Unexpected event")
2013 check_added_monitors(&nodes[0], 1);
2014 } else if test == InterceptTest::Timeout {
2015 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
2016 connect_block(&nodes[0], &block);
2017 connect_block(&nodes[1], &block);
2018 for _ in 0..TEST_FINAL_CLTV {
2019 block.header.prev_blockhash = block.block_hash();
2020 connect_block(&nodes[0], &block);
2021 connect_block(&nodes[1], &block);
2023 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
2024 check_added_monitors!(nodes[1], 1);
2025 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2026 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
2027 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
2028 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
2029 assert!(htlc_timeout_updates.update_fee.is_none());
2031 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
2032 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
2033 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
2035 // Check for unknown intercept id error.
2036 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
2037 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();
2038 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2039 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
2040 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2045 fn accept_underpaying_htlcs_config() {
2046 do_accept_underpaying_htlcs_config(1);
2047 do_accept_underpaying_htlcs_config(2);
2048 do_accept_underpaying_htlcs_config(3);
2051 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
2052 let chanmon_cfgs = create_chanmon_cfgs(3);
2053 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2054 let mut intercept_forwards_config = test_default_channel_config();
2055 intercept_forwards_config.accept_intercept_htlcs = true;
2056 let mut underpay_config = test_default_channel_config();
2057 underpay_config.channel_config.accept_underpaying_htlcs = true;
2058 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
2059 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2061 let mut chan_ids = Vec::new();
2062 for _ in 0..num_mpp_parts {
2063 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000, 0);
2064 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 2_000_000, 0).0.channel_id;
2065 chan_ids.push(channel_id);
2068 // Send the initial payment.
2069 let amt_msat = 900_000;
2070 let skimmed_fee_msat = 20;
2071 let mut route_hints = Vec::new();
2072 for _ in 0..num_mpp_parts {
2073 route_hints.push(RouteHint(vec![RouteHintHop {
2074 src_node_id: nodes[1].node.get_our_node_id(),
2075 short_channel_id: nodes[1].node.get_intercept_scid(),
2078 proportional_millionths: 0,
2080 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
2081 htlc_minimum_msat: None,
2082 htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
2085 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2086 .with_route_hints(route_hints).unwrap()
2087 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap();
2088 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2089 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
2090 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2091 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2092 check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
2093 let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
2094 assert_eq!(events.len(), num_mpp_parts);
2096 // Forward the intercepted payments.
2097 for (idx, ev) in events.into_iter().enumerate() {
2098 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
2099 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
2101 let events = nodes[1].node.get_and_clear_pending_events();
2102 assert_eq!(events.len(), 1);
2103 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
2104 crate::events::Event::HTLCIntercepted {
2105 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
2107 assert_eq!(pmt_hash, payment_hash);
2108 (intercept_id, expected_outbound_amount_msat)
2112 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
2113 nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
2114 expect_pending_htlcs_forwardable!(nodes[1]);
2115 let payment_event = {
2117 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2118 assert_eq!(added_monitors.len(), 1);
2119 added_monitors.clear();
2121 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2122 assert_eq!(events.len(), 1);
2123 SendEvent::from_event(events.remove(0))
2125 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
2126 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
2127 if idx == num_mpp_parts - 1 {
2128 expect_pending_htlcs_forwardable!(nodes[2]);
2132 // Claim the payment and check that the skimmed fee is as expected.
2133 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
2134 let events = nodes[2].node.get_and_clear_pending_events();
2135 assert_eq!(events.len(), 1);
2137 crate::events::Event::PaymentClaimable {
2138 ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
2140 assert_eq!(payment_hash, payment_hash);
2141 assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
2142 assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
2143 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2145 crate::events::PaymentPurpose::InvoicePayment { payment_preimage: ev_payment_preimage,
2146 payment_secret: ev_payment_secret, .. } =>
2148 assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
2149 assert_eq!(payment_secret, *ev_payment_secret);
2154 _ => panic!("Unexpected event"),
2156 let mut expected_paths_vecs = Vec::new();
2157 let mut expected_paths = Vec::new();
2158 for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
2159 for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
2160 expected_paths[0].last().unwrap().node.claim_funds(payment_preimage);
2161 let args = ClaimAlongRouteArgs::new(&nodes[0], &expected_paths[..], payment_preimage)
2162 .with_expected_extra_fees(vec![skimmed_fee_msat as u32; num_mpp_parts]);
2163 let total_fee_msat = pass_claimed_payment_along_route(args);
2164 // The sender doesn't know that the penultimate hop took an extra fee.
2165 expect_payment_sent(&nodes[0], payment_preimage,
2166 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true, true);
2169 #[derive(PartialEq)]
2180 fn automatic_retries() {
2181 do_automatic_retries(AutoRetry::Success);
2182 do_automatic_retries(AutoRetry::Spontaneous);
2183 do_automatic_retries(AutoRetry::FailAttempts);
2184 do_automatic_retries(AutoRetry::FailTimeout);
2185 do_automatic_retries(AutoRetry::FailOnRestart);
2186 do_automatic_retries(AutoRetry::FailOnRetry);
2188 fn do_automatic_retries(test: AutoRetry) {
2189 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
2191 let chanmon_cfgs = create_chanmon_cfgs(3);
2192 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2194 let new_chain_monitor;
2196 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2197 let node_0_deserialized;
2199 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2200 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2201 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2203 // Marshall data to send the payment
2204 #[cfg(feature = "std")]
2205 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2206 #[cfg(not(feature = "std"))]
2207 let payment_expiry_secs = 60 * 60;
2208 let amt_msat = 1000;
2209 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2210 invoice_features.set_variable_length_onion_required();
2211 invoice_features.set_payment_secret_required();
2212 invoice_features.set_basic_mpp_optional();
2213 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2214 .with_expiry_time(payment_expiry_secs as u64)
2215 .with_bolt11_features(invoice_features).unwrap();
2216 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2217 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
2219 macro_rules! pass_failed_attempt_with_retry_along_path {
2220 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
2221 // Send a payment attempt that fails due to lack of liquidity on the second hop
2222 check_added_monitors!(nodes[0], 1);
2223 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2224 let mut update_add = update_0.update_add_htlcs[0].clone();
2225 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
2226 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
2227 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2228 nodes[1].node.process_pending_htlc_forwards();
2229 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
2230 vec![HTLCDestination::NextHopChannel {
2231 node_id: Some(nodes[2].node.get_our_node_id()),
2232 channel_id: $failing_channel_id,
2234 nodes[1].node.process_pending_htlc_forwards();
2235 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2236 check_added_monitors!(&nodes[1], 1);
2237 assert!(update_1.update_fail_htlcs.len() == 1);
2238 let fail_msg = update_1.update_fail_htlcs[0].clone();
2239 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
2240 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
2242 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
2243 let mut events = nodes[0].node.get_and_clear_pending_events();
2244 assert_eq!(events.len(), 2);
2246 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2247 assert_eq!(payment_hash, ev_payment_hash);
2248 assert_eq!(payment_failed_permanently, false);
2250 _ => panic!("Unexpected event"),
2252 if $expect_pending_htlcs_forwardable {
2254 Event::PendingHTLCsForwardable { .. } => {},
2255 _ => panic!("Unexpected event"),
2259 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
2260 assert_eq!(payment_hash, ev_payment_hash);
2262 _ => panic!("Unexpected event"),
2268 if test == AutoRetry::Success {
2269 // Test that we can succeed on the first retry.
2270 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2271 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2272 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2274 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2275 // attempt, since the initial second hop channel will be excluded from pathfinding
2276 create_announced_chan_between_nodes(&nodes, 1, 2);
2278 // We retry payments in `process_pending_htlc_forwards`
2279 nodes[0].node.process_pending_htlc_forwards();
2280 check_added_monitors!(nodes[0], 1);
2281 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2282 assert_eq!(msg_events.len(), 1);
2283 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
2284 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2285 } else if test == AutoRetry::Spontaneous {
2286 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
2287 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
2288 Retry::Attempts(1)).unwrap();
2289 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2291 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2292 // attempt, since the initial second hop channel will be excluded from pathfinding
2293 create_announced_chan_between_nodes(&nodes, 1, 2);
2295 // We retry payments in `process_pending_htlc_forwards`
2296 nodes[0].node.process_pending_htlc_forwards();
2297 check_added_monitors!(nodes[0], 1);
2298 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2299 assert_eq!(msg_events.len(), 1);
2300 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2301 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2302 } else if test == AutoRetry::FailAttempts {
2303 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2304 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2305 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2306 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2308 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2309 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2310 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2312 // We retry payments in `process_pending_htlc_forwards`
2313 nodes[0].node.process_pending_htlc_forwards();
2314 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2316 // Ensure we won't retry a second time.
2317 nodes[0].node.process_pending_htlc_forwards();
2318 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2319 assert_eq!(msg_events.len(), 0);
2320 } else if test == AutoRetry::FailTimeout {
2321 #[cfg(feature = "std")] {
2322 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2323 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2324 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2325 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2327 // Advance the time so the second attempt fails due to timeout.
2328 SinceEpoch::advance(Duration::from_secs(61));
2330 // Make sure we don't retry again.
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);
2335 let mut events = nodes[0].node.get_and_clear_pending_events();
2336 assert_eq!(events.len(), 1);
2338 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2339 assert_eq!(payment_hash, *ev_payment_hash);
2340 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2341 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2343 _ => panic!("Unexpected event"),
2346 } else if test == AutoRetry::FailOnRestart {
2347 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2348 // attempts remaining prior to restart.
2349 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2350 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2351 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2353 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2354 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2355 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2357 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2358 nodes[0].node.process_pending_htlc_forwards();
2359 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2361 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2362 let node_encoded = nodes[0].node.encode();
2363 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2364 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2366 let mut events = nodes[0].node.get_and_clear_pending_events();
2367 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2368 // Make sure we don't retry again.
2369 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2370 assert_eq!(msg_events.len(), 0);
2372 let mut events = nodes[0].node.get_and_clear_pending_events();
2373 assert_eq!(events.len(), 1);
2375 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2376 assert_eq!(payment_hash, *ev_payment_hash);
2377 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2378 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2380 _ => panic!("Unexpected event"),
2382 } else if test == AutoRetry::FailOnRetry {
2383 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2384 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2385 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2387 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2388 // fail to find a route.
2389 nodes[0].node.process_pending_htlc_forwards();
2390 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2391 assert_eq!(msg_events.len(), 0);
2393 let mut events = nodes[0].node.get_and_clear_pending_events();
2394 assert_eq!(events.len(), 1);
2396 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2397 assert_eq!(payment_hash, *ev_payment_hash);
2398 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2399 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2401 _ => panic!("Unexpected event"),
2407 fn auto_retry_partial_failure() {
2408 // Test that we'll retry appropriately on send partial failure and retry partial failure.
2409 let chanmon_cfgs = create_chanmon_cfgs(2);
2410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2412 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2414 // Open three channels, the first has plenty of liquidity, the second and third have ~no
2415 // available liquidity, causing any outbound payments routed over it to fail immediately.
2416 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2417 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;
2418 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;
2420 // Marshall data to send the payment
2421 let amt_msat = 10_000_000;
2422 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2423 #[cfg(feature = "std")]
2424 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2425 #[cfg(not(feature = "std"))]
2426 let payment_expiry_secs = 60 * 60;
2427 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2428 invoice_features.set_variable_length_onion_required();
2429 invoice_features.set_payment_secret_required();
2430 invoice_features.set_basic_mpp_optional();
2431 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2432 .with_expiry_time(payment_expiry_secs as u64)
2433 .with_bolt11_features(invoice_features).unwrap();
2435 // Configure the initial send path
2436 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2437 route_params.max_total_routing_fee_msat = None;
2439 let send_route = Route {
2441 Path { hops: vec![RouteHop {
2442 pubkey: nodes[1].node.get_our_node_id(),
2443 node_features: nodes[1].node.node_features(),
2444 short_channel_id: chan_1_id,
2445 channel_features: nodes[1].node.channel_features(),
2446 fee_msat: amt_msat / 2,
2447 cltv_expiry_delta: 100,
2448 maybe_announced_channel: true,
2449 }], blinded_tail: None },
2450 Path { hops: vec![RouteHop {
2451 pubkey: nodes[1].node.get_our_node_id(),
2452 node_features: nodes[1].node.node_features(),
2453 short_channel_id: chan_2_id,
2454 channel_features: nodes[1].node.channel_features(),
2455 fee_msat: amt_msat / 2,
2456 cltv_expiry_delta: 100,
2457 maybe_announced_channel: true,
2458 }], blinded_tail: None },
2460 route_params: Some(route_params.clone()),
2462 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2464 // Configure the retry1 paths
2465 let mut payment_params = route_params.payment_params.clone();
2466 payment_params.previously_failed_channels.push(chan_2_id);
2467 let mut retry_1_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 2);
2468 retry_1_params.max_total_routing_fee_msat = None;
2470 let retry_1_route = Route {
2472 Path { hops: vec![RouteHop {
2473 pubkey: nodes[1].node.get_our_node_id(),
2474 node_features: nodes[1].node.node_features(),
2475 short_channel_id: chan_1_id,
2476 channel_features: nodes[1].node.channel_features(),
2477 fee_msat: amt_msat / 4,
2478 cltv_expiry_delta: 100,
2479 maybe_announced_channel: true,
2480 }], blinded_tail: None },
2481 Path { hops: vec![RouteHop {
2482 pubkey: nodes[1].node.get_our_node_id(),
2483 node_features: nodes[1].node.node_features(),
2484 short_channel_id: chan_3_id,
2485 channel_features: nodes[1].node.channel_features(),
2486 fee_msat: amt_msat / 4,
2487 cltv_expiry_delta: 100,
2488 maybe_announced_channel: true,
2489 }], blinded_tail: None },
2491 route_params: Some(retry_1_params.clone()),
2493 nodes[0].router.expect_find_route(retry_1_params.clone(), Ok(retry_1_route));
2495 // Configure the retry2 path
2496 let mut payment_params = retry_1_params.payment_params.clone();
2497 payment_params.previously_failed_channels.push(chan_3_id);
2498 let mut retry_2_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 4);
2499 retry_2_params.max_total_routing_fee_msat = None;
2501 let retry_2_route = Route {
2503 Path { hops: vec![RouteHop {
2504 pubkey: nodes[1].node.get_our_node_id(),
2505 node_features: nodes[1].node.node_features(),
2506 short_channel_id: chan_1_id,
2507 channel_features: nodes[1].node.channel_features(),
2508 fee_msat: amt_msat / 4,
2509 cltv_expiry_delta: 100,
2510 maybe_announced_channel: true,
2511 }], blinded_tail: None },
2513 route_params: Some(retry_2_params.clone()),
2515 nodes[0].router.expect_find_route(retry_2_params, Ok(retry_2_route));
2517 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2518 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2519 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2520 let payment_failed_events = nodes[0].node.get_and_clear_pending_events();
2521 assert_eq!(payment_failed_events.len(), 2);
2522 match payment_failed_events[0] {
2523 Event::PaymentPathFailed { .. } => {},
2524 _ => panic!("Unexpected event"),
2526 match payment_failed_events[1] {
2527 Event::PaymentPathFailed { .. } => {},
2528 _ => panic!("Unexpected event"),
2531 // Pass the first part of the payment along the path.
2532 check_added_monitors!(nodes[0], 1); // only one HTLC actually made it out
2533 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2535 // Only one HTLC/channel update actually made it out
2536 assert_eq!(msg_events.len(), 1);
2537 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2539 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2540 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2541 check_added_monitors!(nodes[1], 1);
2542 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2544 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2545 check_added_monitors!(nodes[0], 1);
2546 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2548 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2549 check_added_monitors!(nodes[0], 1);
2550 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2552 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2553 check_added_monitors!(nodes[1], 1);
2555 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2556 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2557 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2558 check_added_monitors!(nodes[1], 1);
2559 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2561 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2562 check_added_monitors!(nodes[0], 1);
2564 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2565 check_added_monitors!(nodes[0], 1);
2566 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2568 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2569 check_added_monitors!(nodes[1], 1);
2571 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2572 nodes[1].node.process_pending_htlc_forwards();
2573 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2574 nodes[1].node.claim_funds(payment_preimage);
2575 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2576 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2577 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2579 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2580 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
2581 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2582 check_added_monitors!(nodes[0], 1);
2583 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2585 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2586 check_added_monitors!(nodes[1], 4);
2587 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2589 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2590 check_added_monitors!(nodes[1], 1);
2591 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2593 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2594 check_added_monitors!(nodes[0], 1);
2595 expect_payment_path_successful!(nodes[0]);
2597 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2598 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2599 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2600 check_added_monitors!(nodes[0], 1);
2601 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2603 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2604 check_added_monitors!(nodes[1], 1);
2606 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2607 check_added_monitors!(nodes[1], 1);
2608 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2610 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2611 check_added_monitors!(nodes[0], 1);
2612 let events = nodes[0].node.get_and_clear_pending_events();
2613 assert_eq!(events.len(), 2);
2614 if let Event::PaymentPathSuccessful { .. } = events[0] {} else { panic!(); }
2615 if let Event::PaymentPathSuccessful { .. } = events[1] {} else { panic!(); }
2619 fn auto_retry_zero_attempts_send_error() {
2620 let chanmon_cfgs = create_chanmon_cfgs(2);
2621 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2622 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2623 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2625 // Open a single channel that does not have sufficient liquidity for the payment we want to
2627 let chan_id = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 989_000_000).0.contents.short_channel_id;
2629 // Marshall data to send the payment
2630 let amt_msat = 10_000_000;
2631 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(amt_msat), None);
2632 #[cfg(feature = "std")]
2633 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2634 #[cfg(not(feature = "std"))]
2635 let payment_expiry_secs = 60 * 60;
2636 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2637 invoice_features.set_variable_length_onion_required();
2638 invoice_features.set_payment_secret_required();
2639 invoice_features.set_basic_mpp_optional();
2640 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2641 .with_expiry_time(payment_expiry_secs as u64)
2642 .with_bolt11_features(invoice_features).unwrap();
2643 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2645 // Override the route search to return a route, rather than failing at the route-finding step.
2646 let send_route = Route {
2648 Path { hops: vec![RouteHop {
2649 pubkey: nodes[1].node.get_our_node_id(),
2650 node_features: nodes[1].node.node_features(),
2651 short_channel_id: chan_id,
2652 channel_features: nodes[1].node.channel_features(),
2654 cltv_expiry_delta: 100,
2655 maybe_announced_channel: true,
2656 }], blinded_tail: None },
2658 route_params: Some(route_params.clone()),
2660 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2662 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2663 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2664 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2665 let events = nodes[0].node.get_and_clear_pending_events();
2666 assert_eq!(events.len(), 2);
2667 if let Event::PaymentPathFailed { .. } = events[0] { } else { panic!(); }
2668 if let Event::PaymentFailed { .. } = events[1] { } else { panic!(); }
2669 check_added_monitors!(nodes[0], 0);
2673 fn fails_paying_after_rejected_by_payee() {
2674 let chanmon_cfgs = create_chanmon_cfgs(2);
2675 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2676 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2677 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2679 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2681 // Marshall data to send the payment
2682 let amt_msat = 20_000;
2683 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2684 #[cfg(feature = "std")]
2685 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2686 #[cfg(not(feature = "std"))]
2687 let payment_expiry_secs = 60 * 60;
2688 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2689 invoice_features.set_variable_length_onion_required();
2690 invoice_features.set_payment_secret_required();
2691 invoice_features.set_basic_mpp_optional();
2692 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2693 .with_expiry_time(payment_expiry_secs as u64)
2694 .with_bolt11_features(invoice_features).unwrap();
2695 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2697 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2698 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2699 check_added_monitors!(nodes[0], 1);
2700 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2701 assert_eq!(events.len(), 1);
2702 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2703 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2704 check_added_monitors!(nodes[1], 0);
2705 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2706 expect_pending_htlcs_forwardable!(nodes[1]);
2707 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2709 nodes[1].node.fail_htlc_backwards(&payment_hash);
2710 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2711 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2715 fn retry_multi_path_single_failed_payment() {
2716 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2717 let chanmon_cfgs = create_chanmon_cfgs(2);
2718 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2719 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2720 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2722 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2723 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2725 let amt_msat = 100_010_000;
2727 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2728 #[cfg(feature = "std")]
2729 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2730 #[cfg(not(feature = "std"))]
2731 let payment_expiry_secs = 60 * 60;
2732 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2733 invoice_features.set_variable_length_onion_required();
2734 invoice_features.set_payment_secret_required();
2735 invoice_features.set_basic_mpp_optional();
2736 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2737 .with_expiry_time(payment_expiry_secs as u64)
2738 .with_bolt11_features(invoice_features).unwrap();
2739 let mut route_params = RouteParameters::from_payment_params_and_value(
2740 payment_params.clone(), amt_msat);
2741 route_params.max_total_routing_fee_msat = None;
2743 let chans = nodes[0].node.list_usable_channels();
2744 let mut route = Route {
2746 Path { hops: vec![RouteHop {
2747 pubkey: nodes[1].node.get_our_node_id(),
2748 node_features: nodes[1].node.node_features(),
2749 short_channel_id: chans[0].short_channel_id.unwrap(),
2750 channel_features: nodes[1].node.channel_features(),
2752 cltv_expiry_delta: 100,
2753 maybe_announced_channel: true,
2754 }], blinded_tail: None },
2755 Path { hops: vec![RouteHop {
2756 pubkey: nodes[1].node.get_our_node_id(),
2757 node_features: nodes[1].node.node_features(),
2758 short_channel_id: chans[1].short_channel_id.unwrap(),
2759 channel_features: nodes[1].node.channel_features(),
2760 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2761 cltv_expiry_delta: 100,
2762 maybe_announced_channel: true,
2763 }], blinded_tail: None },
2765 route_params: Some(route_params.clone()),
2767 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2768 // On retry, split the payment across both channels.
2769 route.paths[0].hops[0].fee_msat = 50_000_001;
2770 route.paths[1].hops[0].fee_msat = 50_000_000;
2771 let mut pay_params = route.route_params.clone().unwrap().payment_params;
2772 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2774 let mut retry_params = RouteParameters::from_payment_params_and_value(pay_params, 100_000_000);
2775 retry_params.max_total_routing_fee_msat = None;
2776 route.route_params = Some(retry_params.clone());
2777 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2780 let scorer = chanmon_cfgs[0].scorer.read().unwrap();
2781 // The initial send attempt, 2 paths
2782 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2783 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2784 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2785 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2786 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2789 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2790 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2791 let events = nodes[0].node.get_and_clear_pending_events();
2792 assert_eq!(events.len(), 1);
2794 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2795 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2796 short_channel_id: Some(expected_scid), .. } =>
2798 assert_eq!(payment_hash, ev_payment_hash);
2799 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2801 _ => panic!("Unexpected event"),
2803 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2804 assert_eq!(htlc_msgs.len(), 2);
2805 check_added_monitors!(nodes[0], 2);
2809 fn immediate_retry_on_failure() {
2810 // Tests that we can/will retry immediately after a failure
2811 let chanmon_cfgs = create_chanmon_cfgs(2);
2812 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2813 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2814 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2816 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2817 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2819 let amt_msat = 100_000_001;
2820 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2821 #[cfg(feature = "std")]
2822 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2823 #[cfg(not(feature = "std"))]
2824 let payment_expiry_secs = 60 * 60;
2825 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2826 invoice_features.set_variable_length_onion_required();
2827 invoice_features.set_payment_secret_required();
2828 invoice_features.set_basic_mpp_optional();
2829 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2830 .with_expiry_time(payment_expiry_secs as u64)
2831 .with_bolt11_features(invoice_features).unwrap();
2832 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2834 let chans = nodes[0].node.list_usable_channels();
2835 let mut route = Route {
2837 Path { hops: vec![RouteHop {
2838 pubkey: nodes[1].node.get_our_node_id(),
2839 node_features: nodes[1].node.node_features(),
2840 short_channel_id: chans[0].short_channel_id.unwrap(),
2841 channel_features: nodes[1].node.channel_features(),
2842 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2843 cltv_expiry_delta: 100,
2844 maybe_announced_channel: true,
2845 }], blinded_tail: None },
2847 route_params: Some(route_params.clone()),
2849 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2850 // On retry, split the payment across both channels.
2851 route.paths.push(route.paths[0].clone());
2852 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2853 route.paths[0].hops[0].fee_msat = 50_000_000;
2854 route.paths[1].hops[0].fee_msat = 50_000_001;
2855 let mut pay_params = route_params.payment_params.clone();
2856 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2857 let retry_params = RouteParameters::from_payment_params_and_value(pay_params, amt_msat);
2858 route.route_params = Some(retry_params.clone());
2859 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2861 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2862 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2863 let events = nodes[0].node.get_and_clear_pending_events();
2864 assert_eq!(events.len(), 1);
2866 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2867 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2868 short_channel_id: Some(expected_scid), .. } =>
2870 assert_eq!(payment_hash, ev_payment_hash);
2871 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2873 _ => panic!("Unexpected event"),
2875 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2876 assert_eq!(htlc_msgs.len(), 2);
2877 check_added_monitors!(nodes[0], 2);
2881 fn no_extra_retries_on_back_to_back_fail() {
2882 // In a previous release, we had a race where we may exceed the payment retry count if we
2883 // get two failures in a row with the second indicating that all paths had failed (this field,
2884 // `all_paths_failed`, has since been removed).
2885 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2886 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2887 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2888 // pending which we will see later. Thus, when we previously removed the retry tracking map
2889 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2890 // retry entry even though more events for the same payment were still pending. This led to
2891 // us retrying a payment again even though we'd already given up on it.
2893 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2894 // is used to remove the payment retry counter entries instead. This tests for the specific
2895 // excess-retry case while also testing `PaymentFailed` generation.
2897 let chanmon_cfgs = create_chanmon_cfgs(3);
2898 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2899 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2900 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2902 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2903 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2905 let amt_msat = 200_000_000;
2906 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2907 #[cfg(feature = "std")]
2908 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2909 #[cfg(not(feature = "std"))]
2910 let payment_expiry_secs = 60 * 60;
2911 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2912 invoice_features.set_variable_length_onion_required();
2913 invoice_features.set_payment_secret_required();
2914 invoice_features.set_basic_mpp_optional();
2915 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2916 .with_expiry_time(payment_expiry_secs as u64)
2917 .with_bolt11_features(invoice_features).unwrap();
2918 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2919 route_params.max_total_routing_fee_msat = None;
2921 let mut route = Route {
2923 Path { hops: vec![RouteHop {
2924 pubkey: nodes[1].node.get_our_node_id(),
2925 node_features: nodes[1].node.node_features(),
2926 short_channel_id: chan_1_scid,
2927 channel_features: nodes[1].node.channel_features(),
2928 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2929 cltv_expiry_delta: 100,
2930 maybe_announced_channel: true,
2932 pubkey: nodes[2].node.get_our_node_id(),
2933 node_features: nodes[2].node.node_features(),
2934 short_channel_id: chan_2_scid,
2935 channel_features: nodes[2].node.channel_features(),
2936 fee_msat: 100_000_000,
2937 cltv_expiry_delta: 100,
2938 maybe_announced_channel: true,
2939 }], blinded_tail: None },
2940 Path { hops: vec![RouteHop {
2941 pubkey: nodes[1].node.get_our_node_id(),
2942 node_features: nodes[1].node.node_features(),
2943 short_channel_id: chan_1_scid,
2944 channel_features: nodes[1].node.channel_features(),
2945 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2946 cltv_expiry_delta: 100,
2947 maybe_announced_channel: true,
2949 pubkey: nodes[2].node.get_our_node_id(),
2950 node_features: nodes[2].node.node_features(),
2951 short_channel_id: chan_2_scid,
2952 channel_features: nodes[2].node.channel_features(),
2953 fee_msat: 100_000_000,
2954 cltv_expiry_delta: 100,
2955 maybe_announced_channel: true,
2956 }], blinded_tail: None }
2958 route_params: Some(route_params.clone()),
2960 route.route_params.as_mut().unwrap().max_total_routing_fee_msat = None;
2961 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2962 let mut second_payment_params = route_params.payment_params.clone();
2963 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2964 // On retry, we'll only return one path
2965 route.paths.remove(1);
2966 route.paths[0].hops[1].fee_msat = amt_msat;
2967 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat);
2968 retry_params.max_total_routing_fee_msat = None;
2969 route.route_params = Some(retry_params.clone());
2970 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2972 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2973 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2974 let htlc_updates = SendEvent::from_node(&nodes[0]);
2975 check_added_monitors!(nodes[0], 1);
2976 assert_eq!(htlc_updates.msgs.len(), 1);
2978 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2979 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2980 check_added_monitors!(nodes[1], 1);
2981 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2983 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2984 check_added_monitors!(nodes[0], 1);
2985 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2987 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2988 check_added_monitors!(nodes[0], 1);
2989 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2991 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2992 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2993 check_added_monitors!(nodes[1], 1);
2994 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2996 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2997 check_added_monitors!(nodes[1], 1);
2998 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3000 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
3001 check_added_monitors!(nodes[0], 1);
3003 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3004 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
3005 check_added_monitors!(nodes[0], 1);
3006 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3008 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
3009 check_added_monitors!(nodes[1], 1);
3010 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3012 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
3013 check_added_monitors!(nodes[1], 1);
3014 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3016 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
3017 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
3018 check_added_monitors!(nodes[0], 1);
3020 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
3021 check_added_monitors!(nodes[0], 1);
3022 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3024 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
3025 check_added_monitors!(nodes[1], 1);
3026 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
3027 check_added_monitors!(nodes[1], 1);
3028 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3030 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
3031 check_added_monitors!(nodes[0], 1);
3033 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
3034 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
3037 // Previously, we retried payments in an event consumer, which would retry each
3038 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
3039 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
3040 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
3041 // by adding the `PaymentFailed` event.
3043 // Because we now retry payments as a batch, we simply return a single-path route in the
3044 // second, batched, request, have that fail, ensure the payment was abandoned.
3045 let mut events = nodes[0].node.get_and_clear_pending_events();
3046 assert_eq!(events.len(), 3);
3048 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3049 assert_eq!(payment_hash, ev_payment_hash);
3050 assert_eq!(payment_failed_permanently, false);
3052 _ => panic!("Unexpected event"),
3055 Event::PendingHTLCsForwardable { .. } => {},
3056 _ => panic!("Unexpected event"),
3059 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3060 assert_eq!(payment_hash, ev_payment_hash);
3061 assert_eq!(payment_failed_permanently, false);
3063 _ => panic!("Unexpected event"),
3066 nodes[0].node.process_pending_htlc_forwards();
3067 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3068 check_added_monitors!(nodes[0], 1);
3070 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3071 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3072 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3073 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3074 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
3076 let mut events = nodes[0].node.get_and_clear_pending_events();
3077 assert_eq!(events.len(), 2);
3079 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3080 assert_eq!(payment_hash, ev_payment_hash);
3081 assert_eq!(payment_failed_permanently, false);
3083 _ => panic!("Unexpected event"),
3086 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
3087 assert_eq!(payment_hash, *ev_payment_hash);
3088 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
3089 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
3091 _ => panic!("Unexpected event"),
3096 fn test_simple_partial_retry() {
3097 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
3098 // full amount of the payment, rather than only the missing amount. Here we simply test for
3099 // this by sending a payment with two parts, failing one, and retrying the second. Note that
3100 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
3102 let chanmon_cfgs = create_chanmon_cfgs(3);
3103 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3104 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3105 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3107 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3108 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
3110 let amt_msat = 200_000_000;
3111 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3112 #[cfg(feature = "std")]
3113 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3114 #[cfg(not(feature = "std"))]
3115 let payment_expiry_secs = 60 * 60;
3116 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3117 invoice_features.set_variable_length_onion_required();
3118 invoice_features.set_payment_secret_required();
3119 invoice_features.set_basic_mpp_optional();
3120 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3121 .with_expiry_time(payment_expiry_secs as u64)
3122 .with_bolt11_features(invoice_features).unwrap();
3123 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
3124 route_params.max_total_routing_fee_msat = None;
3126 let mut route = Route {
3128 Path { hops: vec![RouteHop {
3129 pubkey: nodes[1].node.get_our_node_id(),
3130 node_features: nodes[1].node.node_features(),
3131 short_channel_id: chan_1_scid,
3132 channel_features: nodes[1].node.channel_features(),
3133 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
3134 cltv_expiry_delta: 100,
3135 maybe_announced_channel: true,
3137 pubkey: nodes[2].node.get_our_node_id(),
3138 node_features: nodes[2].node.node_features(),
3139 short_channel_id: chan_2_scid,
3140 channel_features: nodes[2].node.channel_features(),
3141 fee_msat: 100_000_000,
3142 cltv_expiry_delta: 100,
3143 maybe_announced_channel: true,
3144 }], blinded_tail: None },
3145 Path { hops: vec![RouteHop {
3146 pubkey: nodes[1].node.get_our_node_id(),
3147 node_features: nodes[1].node.node_features(),
3148 short_channel_id: chan_1_scid,
3149 channel_features: nodes[1].node.channel_features(),
3151 cltv_expiry_delta: 100,
3152 maybe_announced_channel: true,
3154 pubkey: nodes[2].node.get_our_node_id(),
3155 node_features: nodes[2].node.node_features(),
3156 short_channel_id: chan_2_scid,
3157 channel_features: nodes[2].node.channel_features(),
3158 fee_msat: 100_000_000,
3159 cltv_expiry_delta: 100,
3160 maybe_announced_channel: true,
3161 }], blinded_tail: None }
3163 route_params: Some(route_params.clone()),
3166 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3168 let mut second_payment_params = route_params.payment_params.clone();
3169 second_payment_params.previously_failed_channels = vec![chan_2_scid];
3170 // On retry, we'll only be asked for one path (or 100k sats)
3171 route.paths.remove(0);
3172 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat / 2);
3173 retry_params.max_total_routing_fee_msat = None;
3174 route.route_params = Some(retry_params.clone());
3175 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
3177 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3178 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
3179 let htlc_updates = SendEvent::from_node(&nodes[0]);
3180 check_added_monitors!(nodes[0], 1);
3181 assert_eq!(htlc_updates.msgs.len(), 1);
3183 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
3184 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
3185 check_added_monitors!(nodes[1], 1);
3186 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3188 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
3189 check_added_monitors!(nodes[0], 1);
3190 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
3192 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
3193 check_added_monitors!(nodes[0], 1);
3194 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3196 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
3197 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
3198 check_added_monitors!(nodes[1], 1);
3199 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3201 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
3202 check_added_monitors!(nodes[1], 1);
3203 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3205 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
3206 check_added_monitors!(nodes[0], 1);
3208 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3209 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
3210 check_added_monitors!(nodes[0], 1);
3211 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3213 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
3214 check_added_monitors!(nodes[1], 1);
3216 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
3217 check_added_monitors!(nodes[1], 1);
3219 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3221 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
3222 check_added_monitors!(nodes[0], 1);
3224 let mut events = nodes[0].node.get_and_clear_pending_events();
3225 assert_eq!(events.len(), 2);
3227 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3228 assert_eq!(payment_hash, ev_payment_hash);
3229 assert_eq!(payment_failed_permanently, false);
3231 _ => panic!("Unexpected event"),
3234 Event::PendingHTLCsForwardable { .. } => {},
3235 _ => panic!("Unexpected event"),
3238 nodes[0].node.process_pending_htlc_forwards();
3239 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3240 check_added_monitors!(nodes[0], 1);
3242 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3243 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3245 expect_pending_htlcs_forwardable!(nodes[1]);
3246 check_added_monitors!(nodes[1], 1);
3248 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3249 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
3250 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
3251 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
3253 expect_pending_htlcs_forwardable!(nodes[2]);
3254 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
3258 #[cfg(feature = "std")]
3259 fn test_threaded_payment_retries() {
3260 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
3261 // a single thread and would happily let multiple threads run retries at the same time. Because
3262 // retries are done by first calculating the amount we need to retry, then dropping the
3263 // relevant lock, then actually sending, we would happily let multiple threads retry the same
3264 // amount at the same time, overpaying our original HTLC!
3265 let chanmon_cfgs = create_chanmon_cfgs(4);
3266 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3267 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3268 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3270 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
3271 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
3272 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
3273 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
3275 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3276 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
3277 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
3278 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
3280 let amt_msat = 100_000_000;
3281 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3282 #[cfg(feature = "std")]
3283 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3284 #[cfg(not(feature = "std"))]
3285 let payment_expiry_secs = 60 * 60;
3286 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3287 invoice_features.set_variable_length_onion_required();
3288 invoice_features.set_payment_secret_required();
3289 invoice_features.set_basic_mpp_optional();
3290 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3291 .with_expiry_time(payment_expiry_secs as u64)
3292 .with_bolt11_features(invoice_features).unwrap();
3293 let mut route_params = RouteParameters {
3294 payment_params, final_value_msat: amt_msat, max_total_routing_fee_msat: Some(500_000),
3297 let mut route = Route {
3299 Path { hops: vec![RouteHop {
3300 pubkey: nodes[1].node.get_our_node_id(),
3301 node_features: nodes[1].node.node_features(),
3302 short_channel_id: chan_1_scid,
3303 channel_features: nodes[1].node.channel_features(),
3305 cltv_expiry_delta: 100,
3306 maybe_announced_channel: true,
3308 pubkey: nodes[3].node.get_our_node_id(),
3309 node_features: nodes[2].node.node_features(),
3310 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3311 channel_features: nodes[2].node.channel_features(),
3312 fee_msat: amt_msat / 1000,
3313 cltv_expiry_delta: 100,
3314 maybe_announced_channel: true,
3315 }], blinded_tail: None },
3316 Path { hops: vec![RouteHop {
3317 pubkey: nodes[2].node.get_our_node_id(),
3318 node_features: nodes[2].node.node_features(),
3319 short_channel_id: chan_3_scid,
3320 channel_features: nodes[2].node.channel_features(),
3322 cltv_expiry_delta: 100,
3323 maybe_announced_channel: true,
3325 pubkey: nodes[3].node.get_our_node_id(),
3326 node_features: nodes[3].node.node_features(),
3327 short_channel_id: chan_4_scid,
3328 channel_features: nodes[3].node.channel_features(),
3329 fee_msat: amt_msat - amt_msat / 1000,
3330 cltv_expiry_delta: 100,
3331 maybe_announced_channel: true,
3332 }], blinded_tail: None }
3334 route_params: Some(route_params.clone()),
3336 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3338 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3339 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3340 check_added_monitors!(nodes[0], 2);
3341 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3342 assert_eq!(send_msg_events.len(), 2);
3343 send_msg_events.retain(|msg|
3344 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3345 // Drop the commitment update for nodes[2], we can just let that one sit pending
3347 *node_id == nodes[1].node.get_our_node_id()
3348 } else { panic!(); }
3351 // from here on out, the retry `RouteParameters` amount will be amt/1000
3352 route_params.final_value_msat /= 1000;
3353 route.route_params = Some(route_params.clone());
3356 let end_time = Instant::now() + Duration::from_secs(1);
3357 macro_rules! thread_body { () => { {
3358 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3359 let node_ref = NodePtr::from_node(&nodes[0]);
3362 let node_a = unsafe { &*node_ref.0 };
3363 while Instant::now() < end_time {
3364 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3365 // Ignore if we have any pending events, just always pretend we just got a
3366 // PendingHTLCsForwardable
3367 node_a.node.process_pending_htlc_forwards();
3371 let mut threads = Vec::new();
3372 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3374 // Back in the main thread, poll pending messages and make sure that we never have more than
3375 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3376 // there are HTLC messages shoved in while its running. This allows us to test that we never
3377 // generate an additional update_add_htlc until we've fully failed the first.
3378 let mut previously_failed_channels = Vec::new();
3380 assert_eq!(send_msg_events.len(), 1);
3381 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3382 assert_eq!(send_event.msgs.len(), 1);
3384 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3385 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3387 // Note that we only push one route into `expect_find_route` at a time, because that's all
3388 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3389 // we should still ultimately fail for the same reason - because we're trying to send too
3390 // many HTLCs at once.
3391 let mut new_route_params = route_params.clone();
3392 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3393 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3394 new_route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 100_000);
3395 route.paths[0].hops[1].short_channel_id += 1;
3396 route.route_params = Some(new_route_params.clone());
3397 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3399 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3400 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3401 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3402 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3403 // This races with our other threads which may generate an add-HTLCs commitment update via
3404 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3405 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3406 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3407 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3409 let cur_time = Instant::now();
3410 if cur_time > end_time {
3411 for thread in threads.drain(..) { thread.join().unwrap(); }
3414 // Make sure we have some events to handle when we go around...
3415 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3416 nodes[0].node.process_pending_htlc_forwards();
3417 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3418 check_added_monitors!(nodes[0], 2);
3420 if cur_time > end_time {
3426 fn do_no_missing_sent_on_reload(persist_manager_with_payment: bool, at_midpoint: bool) {
3427 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3428 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3429 // it was last persisted.
3430 let chanmon_cfgs = create_chanmon_cfgs(2);
3431 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3432 let (persister_a, persister_b, persister_c);
3433 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3434 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3435 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3436 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3438 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3440 let mut nodes_0_serialized = Vec::new();
3441 if !persist_manager_with_payment {
3442 nodes_0_serialized = nodes[0].node.encode();
3445 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3447 if persist_manager_with_payment {
3448 nodes_0_serialized = nodes[0].node.encode();
3451 nodes[1].node.claim_funds(our_payment_preimage);
3452 check_added_monitors!(nodes[1], 1);
3453 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3456 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3457 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3458 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3459 check_added_monitors!(nodes[0], 1);
3461 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3462 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
3463 commitment_signed_dance!(nodes[0], nodes[1], htlc_fulfill_updates.commitment_signed, false);
3464 // Ignore the PaymentSent event which is now pending on nodes[0] - if we were to handle it we'd
3465 // be expected to ignore the eventual conflicting PaymentFailed, but by not looking at it we
3466 // expect to get the PaymentSent again later.
3467 check_added_monitors(&nodes[0], 0);
3470 // The ChannelMonitor should always be the latest version, as we're required to persist it
3471 // during the commitment signed handling.
3472 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3473 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3475 let events = nodes[0].node.get_and_clear_pending_events();
3476 assert_eq!(events.len(), 2);
3477 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3478 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3479 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3480 // the double-claim that would otherwise appear at the end of this test.
3481 nodes[0].node.timer_tick_occurred();
3482 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3483 assert_eq!(as_broadcasted_txn.len(), 1);
3485 // Ensure that, even after some time, if we restart we still include *something* in the current
3486 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3487 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3488 // A naive implementation of the fix here would wipe the pending payments set, causing a
3489 // failure event when we restart.
3490 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3492 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3493 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);
3494 let events = nodes[0].node.get_and_clear_pending_events();
3495 assert!(events.is_empty());
3497 // Ensure that we don't generate any further events even after the channel-closing commitment
3498 // transaction is confirmed on-chain.
3499 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3500 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3502 let events = nodes[0].node.get_and_clear_pending_events();
3503 assert!(events.is_empty());
3505 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3506 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);
3507 let events = nodes[0].node.get_and_clear_pending_events();
3508 assert!(events.is_empty());
3509 check_added_monitors(&nodes[0], 1);
3513 fn no_missing_sent_on_midpoint_reload() {
3514 do_no_missing_sent_on_reload(false, true);
3515 do_no_missing_sent_on_reload(true, true);
3519 fn no_missing_sent_on_reload() {
3520 do_no_missing_sent_on_reload(false, false);
3521 do_no_missing_sent_on_reload(true, false);
3524 fn do_claim_from_closed_chan(fail_payment: bool) {
3525 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3526 // received had been closed between when the HTLC was received and when we went to claim it.
3527 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3528 // presumably the sender may retry later. Long ago it also reduced total code in the claim
3531 // However, this doesn't make sense if you're trying to do an atomic swap or some other
3532 // protocol that requires atomicity with some other action - if your money got claimed
3533 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3534 // is an over-optimization - there should be a very, very low likelihood that a channel closes
3535 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3536 // Since we now have code to handle this anyway we should allow it.
3538 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3539 // CLTVs on the paths to different value resulting in a different claim deadline.
3540 let chanmon_cfgs = create_chanmon_cfgs(4);
3541 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3542 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3543 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3545 create_announced_chan_between_nodes(&nodes, 0, 1);
3546 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3547 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3548 create_announced_chan_between_nodes(&nodes, 2, 3);
3550 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3551 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3552 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
3553 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000_000);
3554 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3555 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3556 // Make sure the route is ordered as the B->D path before C->D
3557 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3558 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3560 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3561 // the HTLC is being relayed.
3562 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3563 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3564 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3566 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3567 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3568 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3569 check_added_monitors(&nodes[0], 2);
3570 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3571 send_msgs.sort_by(|a, _| {
3573 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3574 let node_b_id = nodes[1].node.get_our_node_id();
3575 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3578 assert_eq!(send_msgs.len(), 2);
3579 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3580 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3581 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3582 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3584 match receive_event.unwrap() {
3585 Event::PaymentClaimable { claim_deadline, .. } => {
3586 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3591 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3593 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3594 - if fail_payment { 0 } else { 2 });
3596 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3597 // and expire both immediately, though, by connecting another 4 blocks.
3598 let reason = HTLCDestination::FailedPayment { payment_hash };
3599 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3600 connect_blocks(&nodes[3], 4);
3601 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3602 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3604 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3605 check_closed_event!(&nodes[1], 1, ClosureReason::HolderForceClosed, false,
3606 [nodes[3].node.get_our_node_id()], 1000000);
3607 check_closed_broadcast(&nodes[1], 1, true);
3608 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3609 assert_eq!(bs_tx.len(), 1);
3611 mine_transaction(&nodes[3], &bs_tx[0]);
3612 check_added_monitors(&nodes[3], 1);
3613 check_closed_broadcast(&nodes[3], 1, true);
3614 check_closed_event!(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false,
3615 [nodes[1].node.get_our_node_id()], 1000000);
3617 nodes[3].node.claim_funds(payment_preimage);
3618 check_added_monitors(&nodes[3], 2);
3619 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3621 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3622 assert_eq!(ds_tx.len(), 1);
3623 check_spends!(&ds_tx[0], &bs_tx[0]);
3625 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3626 check_added_monitors(&nodes[1], 1);
3627 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3629 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3630 check_added_monitors(&nodes[1], 1);
3631 assert_eq!(bs_claims.len(), 1);
3632 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3633 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3634 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3635 } else { panic!(); }
3637 expect_payment_sent!(nodes[0], payment_preimage);
3639 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3640 assert_eq!(ds_claim_msgs.len(), 1);
3641 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3642 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3643 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3644 check_added_monitors(&nodes[2], 1);
3645 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3646 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3648 } else { panic!(); };
3650 assert_eq!(cs_claim_msgs.len(), 1);
3651 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3652 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3653 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3654 } else { panic!(); }
3656 expect_payment_path_successful!(nodes[0]);
3661 fn claim_from_closed_chan() {
3662 do_claim_from_closed_chan(true);
3663 do_claim_from_closed_chan(false);
3667 fn test_custom_tlvs_basic() {
3668 do_test_custom_tlvs(false, false, false);
3669 do_test_custom_tlvs(true, false, false);
3673 fn test_custom_tlvs_explicit_claim() {
3674 // Test that when receiving even custom TLVs the user must explicitly accept in case they
3676 do_test_custom_tlvs(false, true, false);
3677 do_test_custom_tlvs(false, true, true);
3680 fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) {
3681 let chanmon_cfgs = create_chanmon_cfgs(2);
3682 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3683 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None; 2]);
3684 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3686 create_announced_chan_between_nodes(&nodes, 0, 1);
3688 let amt_msat = 100_000;
3689 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat);
3690 let payment_id = PaymentId(our_payment_hash.0);
3691 let custom_tlvs = vec![
3692 (if even_tlvs { 5482373482 } else { 5482373483 }, vec![1, 2, 3, 4]),
3693 (5482373487, vec![0x42u8; 16]),
3695 let onion_fields = RecipientOnionFields {
3696 payment_secret: if spontaneous { None } else { Some(our_payment_secret) },
3697 payment_metadata: None,
3698 custom_tlvs: custom_tlvs.clone()
3701 nodes[0].node.send_spontaneous_payment(&route, Some(our_payment_preimage), onion_fields, payment_id).unwrap();
3703 nodes[0].node.send_payment_with_route(&route, our_payment_hash, onion_fields, payment_id).unwrap();
3705 check_added_monitors(&nodes[0], 1);
3707 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3708 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
3709 let mut payment_event = SendEvent::from_event(ev);
3711 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3712 check_added_monitors!(&nodes[1], 0);
3713 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3714 expect_pending_htlcs_forwardable!(nodes[1]);
3716 let events = nodes[1].node.get_and_clear_pending_events();
3717 assert_eq!(events.len(), 1);
3719 Event::PaymentClaimable { ref onion_fields, .. } => {
3720 assert_eq!(onion_fields.clone().unwrap().custom_tlvs().clone(), custom_tlvs);
3722 _ => panic!("Unexpected event"),
3725 match (known_tlvs, even_tlvs) {
3727 nodes[1].node.claim_funds_with_known_custom_tlvs(our_payment_preimage);
3728 let expected_total_fee_msat = pass_claimed_payment_along_route(ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1]]], our_payment_preimage));
3729 expect_payment_sent!(&nodes[0], our_payment_preimage, Some(expected_total_fee_msat));
3732 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3735 nodes[1].node.claim_funds(our_payment_preimage);
3736 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3737 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], expected_destinations);
3738 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, our_payment_hash, PaymentFailureReason::RecipientRejected);
3744 fn test_retry_custom_tlvs() {
3745 // Test that custom TLVs are successfully sent on retries
3746 let chanmon_cfgs = create_chanmon_cfgs(3);
3747 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3748 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3749 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3751 create_announced_chan_between_nodes(&nodes, 0, 1);
3752 let (chan_2_update, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 2, 1);
3755 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3757 let amt_msat = 1_000_000;
3758 let (mut route, payment_hash, payment_preimage, payment_secret) =
3759 get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
3761 // Initiate the payment
3762 let payment_id = PaymentId(payment_hash.0);
3763 let mut route_params = route.route_params.clone().unwrap();
3765 let custom_tlvs = vec![((1 << 16) + 1, vec![0x42u8; 16])];
3766 let onion_fields = RecipientOnionFields::secret_only(payment_secret);
3767 let onion_fields = onion_fields.with_custom_tlvs(custom_tlvs.clone()).unwrap();
3769 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3770 nodes[0].node.send_payment(payment_hash, onion_fields,
3771 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3772 check_added_monitors!(nodes[0], 1); // one monitor per path
3774 // Add the HTLC along the first hop.
3775 let htlc_updates = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
3776 let msgs::CommitmentUpdate { update_add_htlcs, commitment_signed, .. } = htlc_updates;
3777 assert_eq!(update_add_htlcs.len(), 1);
3778 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_htlcs[0]);
3779 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
3781 // Attempt to forward the payment and complete the path's failure.
3782 expect_pending_htlcs_forwardable!(&nodes[1]);
3783 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1],
3784 vec![HTLCDestination::NextHopChannel {
3785 node_id: Some(nodes[2].node.get_our_node_id()),
3786 channel_id: chan_2_id
3788 check_added_monitors!(nodes[1], 1);
3790 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3791 let msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } = htlc_updates;
3792 assert_eq!(update_fail_htlcs.len(), 1);
3793 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3794 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
3796 let mut events = nodes[0].node.get_and_clear_pending_events();
3798 Event::PendingHTLCsForwardable { .. } => {},
3799 _ => panic!("Unexpected event")
3802 expect_payment_failed_conditions_event(events, payment_hash, false,
3803 PaymentFailedConditions::new().mpp_parts_remain());
3805 // Rebalance the channel so the retry of the payment can succeed.
3806 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3808 // Retry the payment and make sure it succeeds
3809 route_params.payment_params.previously_failed_channels.push(chan_2_update.contents.short_channel_id);
3810 route.route_params = Some(route_params.clone());
3811 nodes[0].router.expect_find_route(route_params, Ok(route));
3812 nodes[0].node.process_pending_htlc_forwards();
3813 check_added_monitors!(nodes[0], 1);
3814 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3815 assert_eq!(events.len(), 1);
3816 let payment_claimable = pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000,
3817 payment_hash, Some(payment_secret), events.pop().unwrap(), true, None).unwrap();
3818 match payment_claimable {
3819 Event::PaymentClaimable { onion_fields, .. } => {
3820 assert_eq!(&onion_fields.unwrap().custom_tlvs()[..], &custom_tlvs[..]);
3822 _ => panic!("Unexpected event"),
3824 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
3828 fn test_custom_tlvs_consistency() {
3829 let even_type_1 = 1 << 16;
3830 let odd_type_1 = (1 << 16)+ 1;
3831 let even_type_2 = (1 << 16) + 2;
3832 let odd_type_2 = (1 << 16) + 3;
3833 let value_1 = || vec![1, 2, 3, 4];
3834 let differing_value_1 = || vec![1, 2, 3, 5];
3835 let value_2 = || vec![42u8; 16];
3837 // Drop missing odd tlvs
3838 do_test_custom_tlvs_consistency(
3839 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3840 vec![(odd_type_1, value_1())],
3841 Some(vec![(odd_type_1, value_1())]),
3843 // Drop non-matching odd tlvs
3844 do_test_custom_tlvs_consistency(
3845 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3846 vec![(odd_type_1, differing_value_1()), (odd_type_2, value_2())],
3847 Some(vec![(odd_type_2, value_2())]),
3849 // Fail missing even tlvs
3850 do_test_custom_tlvs_consistency(
3851 vec![(odd_type_1, value_1()), (even_type_2, value_2())],
3852 vec![(odd_type_1, value_1())],
3855 // Fail non-matching even tlvs
3856 do_test_custom_tlvs_consistency(
3857 vec![(even_type_1, value_1()), (odd_type_2, value_2())],
3858 vec![(even_type_1, differing_value_1()), (odd_type_2, value_2())],
3863 fn do_test_custom_tlvs_consistency(first_tlvs: Vec<(u64, Vec<u8>)>, second_tlvs: Vec<(u64, Vec<u8>)>,
3864 expected_receive_tlvs: Option<Vec<(u64, Vec<u8>)>>) {
3866 let chanmon_cfgs = create_chanmon_cfgs(4);
3867 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3868 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3869 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3871 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
3872 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
3873 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
3874 let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
3876 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3877 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
3878 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
3879 assert_eq!(route.paths.len(), 2);
3880 route.paths.sort_by(|path_a, _| {
3881 // Sort the path so that the path through nodes[1] comes first
3882 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3883 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
3886 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
3887 let payment_id = PaymentId([42; 32]);
3888 let amt_msat = 15_000_000;
3891 let onion_fields = RecipientOnionFields {
3892 payment_secret: Some(our_payment_secret),
3893 payment_metadata: None,
3894 custom_tlvs: first_tlvs
3896 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
3897 onion_fields.clone(), payment_id, &route).unwrap();
3898 let cur_height = nodes[0].best_block_info().1;
3899 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
3900 onion_fields.clone(), amt_msat, cur_height, payment_id,
3901 &None, session_privs[0]).unwrap();
3902 check_added_monitors!(nodes[0], 1);
3905 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3906 assert_eq!(events.len(), 1);
3907 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, our_payment_hash,
3908 Some(our_payment_secret), events.pop().unwrap(), false, None);
3910 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
3913 let onion_fields = RecipientOnionFields {
3914 payment_secret: Some(our_payment_secret),
3915 payment_metadata: None,
3916 custom_tlvs: second_tlvs
3918 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
3919 onion_fields.clone(), amt_msat, cur_height, payment_id, &None, session_privs[1]).unwrap();
3920 check_added_monitors!(nodes[0], 1);
3923 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3924 assert_eq!(events.len(), 1);
3925 let payment_event = SendEvent::from_event(events.pop().unwrap());
3927 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3928 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
3930 expect_pending_htlcs_forwardable!(nodes[2]);
3931 check_added_monitors!(nodes[2], 1);
3933 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
3934 assert_eq!(events.len(), 1);
3935 let payment_event = SendEvent::from_event(events.pop().unwrap());
3937 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
3938 check_added_monitors!(nodes[3], 0);
3939 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
3941 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3942 nodes[3].node.process_pending_htlc_forwards();
3944 if let Some(expected_tlvs) = expected_receive_tlvs {
3945 // Claim and match expected
3946 let events = nodes[3].node.get_and_clear_pending_events();
3947 assert_eq!(events.len(), 1);
3949 Event::PaymentClaimable { ref onion_fields, .. } => {
3950 assert_eq!(onion_fields.clone().unwrap().custom_tlvs, expected_tlvs);
3952 _ => panic!("Unexpected event"),
3955 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]],
3956 false, our_payment_preimage);
3957 expect_payment_sent(&nodes[0], our_payment_preimage, Some(Some(2000)), true, true);
3960 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3961 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], expected_destinations);
3962 check_added_monitors!(nodes[3], 1);
3964 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
3965 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
3966 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
3968 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![
3969 HTLCDestination::NextHopChannel {
3970 node_id: Some(nodes[3].node.get_our_node_id()),
3971 channel_id: chan_2_3.2
3973 check_added_monitors!(nodes[2], 1);
3975 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
3976 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
3977 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
3979 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true,
3980 PaymentFailedConditions::new().mpp_parts_remain());
3984 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3985 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3986 // another results in the HTLC being rejected.
3988 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3989 // first of which we'll deliver and the second of which we'll fail and then re-send with
3990 // modified payment metadata, which will in turn result in it being failed by the recipient.
3991 let chanmon_cfgs = create_chanmon_cfgs(4);
3992 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3994 let new_chain_monitor;
3996 let mut config = test_default_channel_config();
3997 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3998 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3999 let nodes_0_deserialized;
4001 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4003 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
4004 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
4005 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
4006 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
4008 // Pay more than half of each channel's max, requiring MPP
4009 let amt_msat = 750_000_000;
4010 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
4011 let payment_id = PaymentId(payment_hash.0);
4012 let payment_metadata = vec![44, 49, 52, 142];
4014 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
4015 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
4016 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
4018 // Send the MPP payment, delivering the updated commitment state to nodes[1].
4019 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
4020 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata), custom_tlvs: vec![],
4021 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
4022 check_added_monitors!(nodes[0], 2);
4024 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
4025 assert_eq!(send_events.len(), 2);
4026 let first_send = SendEvent::from_event(send_events.pop().unwrap());
4027 let second_send = SendEvent::from_event(send_events.pop().unwrap());
4029 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
4030 (&first_send, &second_send)
4032 (&second_send, &first_send)
4034 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
4035 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
4037 expect_pending_htlcs_forwardable!(nodes[1]);
4038 check_added_monitors(&nodes[1], 1);
4039 let b_forward_ev = SendEvent::from_node(&nodes[1]);
4040 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
4041 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
4043 expect_pending_htlcs_forwardable!(nodes[3]);
4045 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
4046 // will result in nodes[2] failing the HTLC back.
4047 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4048 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
4050 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
4051 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
4053 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
4054 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
4055 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
4057 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
4058 assert_eq!(payment_fail_retryable_evs.len(), 2);
4059 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
4060 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
4062 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
4063 // stored for our payment.
4065 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
4068 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
4069 // the payment state.
4071 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
4072 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
4073 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
4074 persister, new_chain_monitor, nodes_0_deserialized);
4075 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4076 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
4078 let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
4079 reconnect_args.send_channel_ready = (true, true);
4080 reconnect_nodes(reconnect_args);
4082 // Create a new channel between C and D as A will refuse to retry on the existing one because
4084 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
4086 // Now retry the failed HTLC.
4087 nodes[0].node.process_pending_htlc_forwards();
4088 check_added_monitors(&nodes[0], 1);
4089 let as_resend = SendEvent::from_node(&nodes[0]);
4090 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
4091 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
4093 expect_pending_htlcs_forwardable!(nodes[2]);
4094 check_added_monitors(&nodes[2], 1);
4095 let cs_forward = SendEvent::from_node(&nodes[2]);
4096 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
4097 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
4099 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
4100 // the payment metadata was modified, failing only the one modified HTLC and retaining the
4103 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
4104 nodes[3].node.process_pending_htlc_forwards();
4105 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
4106 &[HTLCDestination::FailedPayment {payment_hash}]);
4107 nodes[3].node.process_pending_htlc_forwards();
4109 check_added_monitors(&nodes[3], 1);
4110 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
4112 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
4113 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
4114 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
4115 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
4117 expect_pending_htlcs_forwardable!(nodes[3]);
4118 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
4119 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
4124 fn test_payment_metadata_consistency() {
4125 do_test_payment_metadata_consistency(true, true);
4126 do_test_payment_metadata_consistency(true, false);
4127 do_test_payment_metadata_consistency(false, true);
4128 do_test_payment_metadata_consistency(false, false);
4132 fn test_htlc_forward_considers_anchor_outputs_value() {
4135 // 1) Forwarding nodes don't forward HTLCs that would cause their balance to dip below the
4136 // reserve when considering the value of anchor outputs.
4138 // 2) Recipients of `update_add_htlc` properly reject HTLCs that would cause the initiator's
4139 // balance to dip below the reserve when considering the value of anchor outputs.
4140 let mut config = test_default_channel_config();
4141 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
4142 config.manually_accept_inbound_channels = true;
4143 config.channel_config.forwarding_fee_base_msat = 0;
4144 config.channel_config.forwarding_fee_proportional_millionths = 0;
4146 // Set up a test network of three nodes that replicates a production failure leading to the
4147 // discovery of this bug.
4148 let chanmon_cfgs = create_chanmon_cfgs(3);
4149 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4150 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(config)]);
4151 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4153 const CHAN_AMT: u64 = 1_000_000;
4154 const PUSH_MSAT: u64 = 900_000_000;
4155 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, CHAN_AMT, 500_000_000);
4156 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, CHAN_AMT, PUSH_MSAT);
4158 let channel_reserve_msat = get_holder_selected_channel_reserve_satoshis(CHAN_AMT, &config) * 1000;
4159 let commitment_fee_msat = commit_tx_fee_msat(
4160 *nodes[1].fee_estimator.sat_per_kw.lock().unwrap(), 2, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()
4162 let anchor_outpus_value_msat = ANCHOR_OUTPUT_VALUE_SATOSHI * 2 * 1000;
4163 let sendable_balance_msat = CHAN_AMT * 1000 - PUSH_MSAT - channel_reserve_msat - commitment_fee_msat - anchor_outpus_value_msat;
4164 let channel_details = nodes[1].node.list_channels().into_iter().find(|channel| channel.channel_id == chan_id_2).unwrap();
4165 assert!(sendable_balance_msat >= channel_details.next_outbound_htlc_minimum_msat);
4166 assert!(sendable_balance_msat <= channel_details.next_outbound_htlc_limit_msat);
4168 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], sendable_balance_msat);
4169 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], sendable_balance_msat);
4171 // Send out an HTLC that would cause the forwarding node to dip below its reserve when
4172 // considering the value of anchor outputs.
4173 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(
4174 nodes[0], nodes[2], sendable_balance_msat + anchor_outpus_value_msat
4176 nodes[0].node.send_payment_with_route(
4177 &route, payment_hash, RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
4179 check_added_monitors!(nodes[0], 1);
4181 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4182 assert_eq!(events.len(), 1);
4183 let mut update_add_htlc = if let MessageSendEvent::UpdateHTLCs { updates, .. } = events.pop().unwrap() {
4184 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
4185 check_added_monitors(&nodes[1], 0);
4186 commitment_signed_dance!(nodes[1], nodes[0], &updates.commitment_signed, false);
4187 updates.update_add_htlcs[0].clone()
4189 panic!("Unexpected event");
4192 // The forwarding node should reject forwarding it as expected.
4193 expect_pending_htlcs_forwardable!(nodes[1]);
4194 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1], vec![HTLCDestination::NextHopChannel {
4195 node_id: Some(nodes[2].node.get_our_node_id()),
4196 channel_id: chan_id_2
4198 check_added_monitors(&nodes[1], 1);
4200 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
4201 assert_eq!(events.len(), 1);
4202 if let MessageSendEvent::UpdateHTLCs { updates, .. } = events.pop().unwrap() {
4203 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4204 check_added_monitors(&nodes[0], 0);
4205 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4207 panic!("Unexpected event");
4210 expect_payment_failed!(nodes[0], payment_hash, false);
4212 // Assume that the forwarding node did forward it, and make sure the recipient rejects it as an
4213 // invalid update and closes the channel.
4214 update_add_htlc.channel_id = chan_id_2;
4215 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
4216 check_closed_event(&nodes[2], 1, ClosureReason::ProcessingError {
4217 err: "Remote HTLC add would put them under remote reserve value".to_owned()
4218 }, false, &[nodes[1].node.get_our_node_id()], 1_000_000);
4219 check_closed_broadcast(&nodes[2], 1, true);
4220 check_added_monitors(&nodes[2], 1);
4224 fn peel_payment_onion_custom_tlvs() {
4225 let chanmon_cfgs = create_chanmon_cfgs(2);
4226 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4227 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4228 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4229 create_announced_chan_between_nodes(&nodes, 0, 1);
4230 let secp_ctx = Secp256k1::new();
4232 let amt_msat = 1000;
4233 let payment_params = PaymentParameters::for_keysend(nodes[1].node.get_our_node_id(),
4234 TEST_FINAL_CLTV, false);
4235 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
4236 let route = functional_test_utils::get_route(&nodes[0], &route_params).unwrap();
4237 let mut recipient_onion = RecipientOnionFields::spontaneous_empty()
4238 .with_custom_tlvs(vec![(414141, vec![42; 1200])]).unwrap();
4239 let prng_seed = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
4240 let session_priv = SecretKey::from_slice(&prng_seed[..]).expect("RNG is busted");
4241 let keysend_preimage = PaymentPreimage([42; 32]);
4242 let payment_hash = PaymentHash(Sha256::hash(&keysend_preimage.0).to_byte_array());
4244 let (onion_routing_packet, first_hop_msat, cltv_expiry) = onion_utils::create_payment_onion(
4245 &secp_ctx, &route.paths[0], &session_priv, amt_msat, recipient_onion.clone(),
4246 nodes[0].best_block_info().1, &payment_hash, &Some(keysend_preimage), prng_seed
4249 let update_add = msgs::UpdateAddHTLC {
4250 channel_id: ChannelId([0; 32]),
4252 amount_msat: first_hop_msat,
4255 skimmed_fee_msat: None,
4256 onion_routing_packet,
4257 blinding_point: None,
4259 let peeled_onion = crate::ln::onion_payment::peel_payment_onion(
4260 &update_add, &&chanmon_cfgs[1].keys_manager, &&chanmon_cfgs[1].logger, &secp_ctx,
4261 nodes[1].best_block_info().1, true, false
4263 assert_eq!(peeled_onion.incoming_amt_msat, Some(amt_msat));
4264 match peeled_onion.routing {
4265 PendingHTLCRouting::ReceiveKeysend {
4266 payment_data, payment_metadata, custom_tlvs, ..
4268 #[cfg(not(c_bindings))]
4269 assert_eq!(&custom_tlvs, recipient_onion.custom_tlvs());
4271 assert_eq!(custom_tlvs, recipient_onion.custom_tlvs());
4272 assert!(payment_metadata.is_none());
4273 assert!(payment_data.is_none());