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;
45 #[cfg(feature = "std")]
47 crate::util::time::tests::SinceEpoch,
48 std::time::{SystemTime, Instant, Duration}
53 let chanmon_cfgs = create_chanmon_cfgs(4);
54 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
55 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
56 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
58 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
59 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
60 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
61 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
63 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
64 let path = route.paths[0].clone();
65 route.paths.push(path);
66 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
67 route.paths[0].hops[0].short_channel_id = chan_1_id;
68 route.paths[0].hops[1].short_channel_id = chan_3_id;
69 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
70 route.paths[1].hops[0].short_channel_id = chan_2_id;
71 route.paths[1].hops[1].short_channel_id = chan_4_id;
72 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
73 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
78 let chanmon_cfgs = create_chanmon_cfgs(4);
79 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
80 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
81 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
83 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
84 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
85 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
86 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
88 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
90 let amt_msat = 1_000_000;
91 let max_total_routing_fee_msat = 50_000;
92 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
93 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
94 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(
95 nodes[0], nodes[3], payment_params, amt_msat, Some(max_total_routing_fee_msat));
96 let path = route.paths[0].clone();
97 route.paths.push(path);
98 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
99 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
100 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
101 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
102 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
103 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
105 // Initiate the MPP payment.
106 let payment_id = PaymentId(payment_hash.0);
107 let mut route_params = route.route_params.clone().unwrap();
109 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
110 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
111 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
112 check_added_monitors!(nodes[0], 2); // one monitor per path
113 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
114 assert_eq!(events.len(), 2);
116 // Pass half of the payment along the success path.
117 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
118 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
120 // Add the HTLC along the first hop.
121 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
122 let send_event = SendEvent::from_event(fail_path_msgs_1);
123 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
124 commitment_signed_dance!(nodes[2], nodes[0], &send_event.commitment_msg, false);
126 // Attempt to forward the payment and complete the 2nd path's failure.
127 expect_pending_htlcs_forwardable!(&nodes[2]);
128 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 }]);
129 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
130 assert!(htlc_updates.update_add_htlcs.is_empty());
131 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
132 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
133 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
134 check_added_monitors!(nodes[2], 1);
135 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
136 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
137 let mut events = nodes[0].node.get_and_clear_pending_events();
139 Event::PendingHTLCsForwardable { .. } => {},
140 _ => panic!("Unexpected event")
143 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
145 // Rebalance the channel so the second half of the payment can succeed.
146 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
148 // Retry the second half of the payment and make sure it succeeds.
149 route.paths.remove(0);
150 route_params.final_value_msat = 1_000_000;
151 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
152 // Check the remaining max total routing fee for the second attempt is 50_000 - 1_000 msat fee
153 // used by the first path
154 route_params.max_total_routing_fee_msat = Some(max_total_routing_fee_msat - 1_000);
155 route.route_params = Some(route_params.clone());
156 nodes[0].router.expect_find_route(route_params, Ok(route));
157 nodes[0].node.process_pending_htlc_forwards();
158 check_added_monitors!(nodes[0], 1);
159 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
160 assert_eq!(events.len(), 1);
161 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
162 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
166 fn mpp_retry_overpay() {
167 // We create an MPP scenario with two paths in which we need to overpay to reach
168 // htlc_minimum_msat. We then fail the overpaid path and check that on retry our
169 // max_total_routing_fee_msat only accounts for the path's fees, but not for the fees overpaid
170 // in the first attempt.
171 let chanmon_cfgs = create_chanmon_cfgs(4);
172 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
173 let mut user_config = test_default_channel_config();
174 user_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
175 let mut limited_config_1 = user_config.clone();
176 limited_config_1.channel_handshake_config.our_htlc_minimum_msat = 35_000_000;
177 let mut limited_config_2 = user_config.clone();
178 limited_config_2.channel_handshake_config.our_htlc_minimum_msat = 34_500_000;
179 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
180 &[Some(user_config), Some(limited_config_1), Some(limited_config_2), Some(user_config)]);
181 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
183 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 40_000, 0);
184 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 40_000, 0);
185 let (_chan_3_update, _, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 40_000, 0);
186 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes_with_value(&nodes, 3, 2, 40_000, 0);
188 let amt_msat = 70_000_000;
189 let max_total_routing_fee_msat = Some(1_000_000);
191 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
192 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
193 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(
194 nodes[0], nodes[3], payment_params, amt_msat, max_total_routing_fee_msat);
196 // Check we overpay on the second path which we're about to fail.
197 assert_eq!(chan_1_update.contents.fee_proportional_millionths, 0);
198 let overpaid_amount_1 = route.paths[0].fee_msat() as u32 - chan_1_update.contents.fee_base_msat;
199 assert_eq!(overpaid_amount_1, 0);
201 assert_eq!(chan_2_update.contents.fee_proportional_millionths, 0);
202 let overpaid_amount_2 = route.paths[1].fee_msat() as u32 - chan_2_update.contents.fee_base_msat;
204 let total_overpaid_amount = overpaid_amount_1 + overpaid_amount_2;
206 // Initiate the payment.
207 let payment_id = PaymentId(payment_hash.0);
208 let mut route_params = route.route_params.clone().unwrap();
210 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
211 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
212 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
213 check_added_monitors!(nodes[0], 2); // one monitor per path
214 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
215 assert_eq!(events.len(), 2);
217 // Pass half of the payment along the success path.
218 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
219 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, payment_hash,
220 Some(payment_secret), success_path_msgs, false, None);
222 // Add the HTLC along the first hop.
223 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
224 let send_event = SendEvent::from_event(fail_path_msgs_1);
225 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
226 commitment_signed_dance!(nodes[2], nodes[0], &send_event.commitment_msg, false);
228 // Attempt to forward the payment and complete the 2nd path's failure.
229 expect_pending_htlcs_forwardable!(&nodes[2]);
230 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[2],
231 vec![HTLCDestination::NextHopChannel {
232 node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_4_id
235 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
236 assert!(htlc_updates.update_add_htlcs.is_empty());
237 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
238 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
239 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
240 check_added_monitors!(nodes[2], 1);
241 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(),
242 &htlc_updates.update_fail_htlcs[0]);
243 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
244 let mut events = nodes[0].node.get_and_clear_pending_events();
246 Event::PendingHTLCsForwardable { .. } => {},
247 _ => panic!("Unexpected event")
250 expect_payment_failed_conditions_event(events, payment_hash, false,
251 PaymentFailedConditions::new().mpp_parts_remain());
253 // Rebalance the channel so the second half of the payment can succeed.
254 send_payment(&nodes[3], &vec!(&nodes[2])[..], 38_000_000);
256 // Retry the second half of the payment and make sure it succeeds.
257 let first_path_value = route.paths[0].final_value_msat();
258 assert_eq!(first_path_value, 36_000_000);
260 route.paths.remove(0);
261 route_params.final_value_msat -= first_path_value;
262 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
263 // Check the remaining max total routing fee for the second attempt accounts only for 1_000 msat
264 // base fee, but not for overpaid value of the first try.
265 route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 1000);
267 route.route_params = Some(route_params.clone());
268 nodes[0].router.expect_find_route(route_params, Ok(route));
269 nodes[0].node.process_pending_htlc_forwards();
271 check_added_monitors!(nodes[0], 1);
272 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
273 assert_eq!(events.len(), 1);
274 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], amt_msat, payment_hash,
275 Some(payment_secret), events.pop().unwrap(), true, None);
277 // Can't use claim_payment_along_route as it doesn't support overpayment, so we break out the
278 // individual steps here.
279 let extra_fees = vec![0, total_overpaid_amount];
280 let expected_total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
281 &nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], &extra_fees[..], false,
283 expect_payment_sent!(&nodes[0], payment_preimage, Some(expected_total_fee_msat));
286 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
287 let chanmon_cfgs = create_chanmon_cfgs(4);
288 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
289 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
290 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
292 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
293 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
294 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
295 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
297 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
298 let path = route.paths[0].clone();
299 route.paths.push(path);
300 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
301 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
302 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
303 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
304 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
305 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
307 // Initiate the MPP payment.
308 nodes[0].node.send_payment_with_route(&route, payment_hash,
309 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
310 check_added_monitors!(nodes[0], 2); // one monitor per path
311 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
312 assert_eq!(events.len(), 2);
314 // Pass half of the payment along the first path.
315 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
316 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
318 if send_partial_mpp {
319 // Time out the partial MPP
320 for _ in 0..MPP_TIMEOUT_TICKS {
321 nodes[3].node.timer_tick_occurred();
324 // Failed HTLC from node 3 -> 1
325 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
326 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
327 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
328 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
329 check_added_monitors!(nodes[3], 1);
330 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
332 // Failed HTLC from node 1 -> 0
333 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 }]);
334 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
335 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
336 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
337 check_added_monitors!(nodes[1], 1);
338 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
340 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
342 // Pass half of the payment along the second path.
343 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
344 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
346 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
347 for _ in 0..MPP_TIMEOUT_TICKS {
348 nodes[3].node.timer_tick_occurred();
351 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
356 fn mpp_receive_timeout() {
357 do_mpp_receive_timeout(true);
358 do_mpp_receive_timeout(false);
362 fn test_keysend_payments() {
363 do_test_keysend_payments(false, false);
364 do_test_keysend_payments(false, true);
365 do_test_keysend_payments(true, false);
366 do_test_keysend_payments(true, true);
369 fn do_test_keysend_payments(public_node: bool, with_retry: bool) {
370 let chanmon_cfgs = create_chanmon_cfgs(2);
371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
373 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
376 create_announced_chan_between_nodes(&nodes, 0, 1);
378 create_chan_between_nodes(&nodes[0], &nodes[1]);
380 let payer_pubkey = nodes[0].node.get_our_node_id();
381 let payee_pubkey = nodes[1].node.get_our_node_id();
382 let route_params = RouteParameters::from_payment_params_and_value(
383 PaymentParameters::for_keysend(payee_pubkey, 40, false), 10000);
385 let network_graph = nodes[0].network_graph;
386 let channels = nodes[0].node.list_usable_channels();
387 let first_hops = channels.iter().collect::<Vec<_>>();
388 let first_hops = if public_node { None } else { Some(first_hops.as_slice()) };
390 let scorer = test_utils::TestScorer::new();
391 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
392 let route = find_route(
393 &payer_pubkey, &route_params, &network_graph, first_hops,
394 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
398 let test_preimage = PaymentPreimage([42; 32]);
400 nodes[0].node.send_spontaneous_payment_with_retry(Some(test_preimage),
401 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0),
402 route_params, Retry::Attempts(1)).unwrap()
404 nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
405 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap()
408 check_added_monitors!(nodes[0], 1);
409 let send_event = SendEvent::from_node(&nodes[0]);
410 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
411 do_commitment_signed_dance(&nodes[1], &nodes[0], &send_event.commitment_msg, false, false);
412 expect_pending_htlcs_forwardable!(nodes[1]);
413 // Previously, a refactor caused us to stop including the payment preimage in the onion which
414 // is sent as a part of keysend payments. Thus, to be extra careful here, we scope the preimage
415 // above to demonstrate that we have no way to get the preimage at this point except by
416 // extracting it from the onion nodes[1] received.
417 let event = nodes[1].node.get_and_clear_pending_events();
418 assert_eq!(event.len(), 1);
419 if let Event::PaymentClaimable { purpose: PaymentPurpose::SpontaneousPayment(preimage), .. } = event[0] {
420 claim_payment(&nodes[0], &[&nodes[1]], preimage);
425 fn test_mpp_keysend() {
426 let mut mpp_keysend_config = test_default_channel_config();
427 mpp_keysend_config.accept_mpp_keysend = true;
428 let chanmon_cfgs = create_chanmon_cfgs(4);
429 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
430 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(mpp_keysend_config)]);
431 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
433 create_announced_chan_between_nodes(&nodes, 0, 1);
434 create_announced_chan_between_nodes(&nodes, 0, 2);
435 create_announced_chan_between_nodes(&nodes, 1, 3);
436 create_announced_chan_between_nodes(&nodes, 2, 3);
437 let network_graph = nodes[0].network_graph;
439 let payer_pubkey = nodes[0].node.get_our_node_id();
440 let payee_pubkey = nodes[3].node.get_our_node_id();
441 let recv_value = 15_000_000;
442 let route_params = RouteParameters::from_payment_params_and_value(
443 PaymentParameters::for_keysend(payee_pubkey, 40, true), recv_value);
444 let scorer = test_utils::TestScorer::new();
445 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
446 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger,
447 &scorer, &Default::default(), &random_seed_bytes).unwrap();
449 let payment_preimage = PaymentPreimage([42; 32]);
450 let payment_secret = PaymentSecret(payment_preimage.0);
451 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
452 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_preimage.0)).unwrap();
453 check_added_monitors!(nodes[0], 2);
455 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
456 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
457 assert_eq!(events.len(), 2);
459 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
460 pass_along_path(&nodes[0], expected_route[0], recv_value, payment_hash.clone(),
461 Some(payment_secret), ev.clone(), false, Some(payment_preimage));
463 let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
464 pass_along_path(&nodes[0], expected_route[1], recv_value, payment_hash.clone(),
465 Some(payment_secret), ev.clone(), true, Some(payment_preimage));
466 claim_payment_along_route(&nodes[0], expected_route, false, payment_preimage);
470 fn test_reject_mpp_keysend_htlc() {
471 // This test enforces that we reject MPP keysend HTLCs if our config states we don't support
472 // MPP keysend. When receiving a payment, if we don't support MPP keysend we'll reject the
473 // payment if it's keysend and has a payment secret, never reaching our payment validation
474 // logic. To check that we enforce rejecting MPP keysends in our payment logic, here we send
475 // keysend payments without payment secrets, then modify them by adding payment secrets in the
476 // final node in between receiving the HTLCs and actually processing them.
477 let mut reject_mpp_keysend_cfg = test_default_channel_config();
478 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
480 let chanmon_cfgs = create_chanmon_cfgs(4);
481 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
482 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, Some(reject_mpp_keysend_cfg)]);
483 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
484 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
485 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
486 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
487 let (update_a, _, chan_4_channel_id, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
488 let chan_4_id = update_a.contents.short_channel_id;
490 let (mut route, payment_hash, payment_preimage, _) = get_route_and_payment_hash!(nodes[0], nodes[3], amount);
492 // Pay along nodes[1]
493 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
494 route.paths[0].hops[0].short_channel_id = chan_1_id;
495 route.paths[0].hops[1].short_channel_id = chan_3_id;
497 let payment_id_0 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
498 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_0).unwrap();
499 check_added_monitors!(nodes[0], 1);
501 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
502 let update_add_0 = update_0.update_add_htlcs[0].clone();
503 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
504 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
505 expect_pending_htlcs_forwardable!(nodes[1]);
507 check_added_monitors!(&nodes[1], 1);
508 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[3].node.get_our_node_id());
509 let update_add_1 = update_1.update_add_htlcs[0].clone();
510 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
511 commitment_signed_dance!(nodes[3], nodes[1], update_1.commitment_signed, false, true);
513 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
514 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
515 for f in pending_forwards.iter_mut() {
517 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
518 match forward_info.routing {
519 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
520 *payment_data = Some(msgs::FinalOnionHopData {
521 payment_secret: PaymentSecret([42; 32]),
522 total_msat: amount * 2,
525 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
532 expect_pending_htlcs_forwardable!(nodes[3]);
534 // Pay along nodes[2]
535 route.paths[0].hops[0].pubkey = nodes[2].node.get_our_node_id();
536 route.paths[0].hops[0].short_channel_id = chan_2_id;
537 route.paths[0].hops[1].short_channel_id = chan_4_id;
539 let payment_id_1 = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
540 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage), RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
541 check_added_monitors!(nodes[0], 1);
543 let update_2 = get_htlc_update_msgs!(nodes[0], nodes[2].node.get_our_node_id());
544 let update_add_2 = update_2.update_add_htlcs[0].clone();
545 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_2);
546 commitment_signed_dance!(nodes[2], nodes[0], &update_2.commitment_signed, false, true);
547 expect_pending_htlcs_forwardable!(nodes[2]);
549 check_added_monitors!(&nodes[2], 1);
550 let update_3 = get_htlc_update_msgs!(nodes[2], nodes[3].node.get_our_node_id());
551 let update_add_3 = update_3.update_add_htlcs[0].clone();
552 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &update_add_3);
553 commitment_signed_dance!(nodes[3], nodes[2], update_3.commitment_signed, false, true);
555 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
556 for (_, pending_forwards) in nodes[3].node.forward_htlcs.lock().unwrap().iter_mut() {
557 for f in pending_forwards.iter_mut() {
559 &mut HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo { ref mut forward_info, .. }) => {
560 match forward_info.routing {
561 PendingHTLCRouting::ReceiveKeysend { ref mut payment_data, .. } => {
562 *payment_data = Some(msgs::FinalOnionHopData {
563 payment_secret: PaymentSecret([42; 32]),
564 total_msat: amount * 2,
567 _ => panic!("Expected PendingHTLCRouting::ReceiveKeysend"),
574 expect_pending_htlcs_forwardable!(nodes[3]);
575 check_added_monitors!(nodes[3], 1);
577 // Fail back along nodes[2]
578 let update_fail_0 = get_htlc_update_msgs!(&nodes[3], &nodes[2].node.get_our_node_id());
579 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &update_fail_0.update_fail_htlcs[0]);
580 commitment_signed_dance!(nodes[2], nodes[3], update_fail_0.commitment_signed, false);
581 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 }]);
582 check_added_monitors!(nodes[2], 1);
584 let update_fail_1 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
585 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail_1.update_fail_htlcs[0]);
586 commitment_signed_dance!(nodes[0], nodes[2], update_fail_1.commitment_signed, false);
588 expect_payment_failed_conditions(&nodes[0], payment_hash, true, PaymentFailedConditions::new());
589 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
594 fn no_pending_leak_on_initial_send_failure() {
595 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
596 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
597 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
598 // pending payment forever and never time it out.
599 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
600 // try, and then check that no pending payment is being tracked.
601 let chanmon_cfgs = create_chanmon_cfgs(2);
602 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
603 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
604 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
606 create_announced_chan_between_nodes(&nodes, 0, 1);
608 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
610 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
611 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
613 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
614 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
615 ), true, APIError::ChannelUnavailable { ref err },
616 assert_eq!(err, "Peer for first hop currently disconnected"));
618 assert!(!nodes[0].node.has_pending_payments());
621 fn do_retry_with_no_persist(confirm_before_reload: bool) {
622 // If we send a pending payment and `send_payment` returns success, we should always either
623 // return a payment failure event or a payment success event, and on failure the payment should
626 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
627 // always persisted asynchronously), the ChannelManager has to reload some payment data from
628 // ChannelMonitor(s) in some cases. This tests that reloading.
630 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
631 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
632 // which has separate codepaths for "commitment transaction already confirmed" and not.
633 let chanmon_cfgs = create_chanmon_cfgs(3);
634 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
636 let new_chain_monitor;
637 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
638 let nodes_0_deserialized;
639 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
641 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
642 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
644 // Serialize the ChannelManager prior to sending payments
645 let nodes_0_serialized = nodes[0].node.encode();
647 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
649 let amt_msat = 1_000_000;
650 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
651 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
652 let route_params = route.route_params.unwrap().clone();
653 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
654 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
655 check_added_monitors!(nodes[0], 1);
657 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
658 assert_eq!(events.len(), 1);
659 let payment_event = SendEvent::from_event(events.pop().unwrap());
660 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
662 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
663 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
664 // which would prevent retry.
665 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
666 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
668 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
669 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
670 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
671 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
673 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[2]));
675 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
676 if confirm_before_reload {
677 mine_transaction(&nodes[0], &as_commitment_tx);
678 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
681 // The ChannelMonitor should always be the latest version, as we're required to persist it
682 // during the `commitment_signed_dance!()`.
683 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
684 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
686 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
687 // force-close the channel.
688 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
689 assert!(nodes[0].node.list_channels().is_empty());
690 assert!(nodes[0].node.has_pending_payments());
691 nodes[0].node.timer_tick_occurred();
692 if !confirm_before_reload {
693 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
694 assert_eq!(as_broadcasted_txn.len(), 1);
695 assert_eq!(as_broadcasted_txn[0].txid(), as_commitment_tx.txid());
697 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
699 check_added_monitors!(nodes[0], 1);
701 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
702 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
703 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
705 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
707 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
708 // error, as the channel has hit the chain.
709 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
710 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
712 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
713 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
714 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
715 assert_eq!(as_err.len(), 2);
717 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
718 assert_eq!(node_id, nodes[1].node.get_our_node_id());
719 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
720 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 {}",
721 &nodes[1].node.get_our_node_id())) }, [nodes[0].node.get_our_node_id()], 100000);
722 check_added_monitors!(nodes[1], 1);
723 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
725 _ => panic!("Unexpected event"),
727 check_closed_broadcast!(nodes[1], false);
729 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
730 // we close in a moment.
731 nodes[2].node.claim_funds(payment_preimage_1);
732 check_added_monitors!(nodes[2], 1);
733 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
735 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
736 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
737 check_added_monitors!(nodes[1], 1);
738 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
739 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, true, false);
741 if confirm_before_reload {
742 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
743 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
746 // Create a new channel on which to retry the payment before we fail the payment via the
747 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
748 // connecting several blocks while creating the channel (implying time has passed).
749 create_announced_chan_between_nodes(&nodes, 0, 1);
750 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
752 mine_transaction(&nodes[1], &as_commitment_tx);
753 let bs_htlc_claim_txn = {
754 let mut txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
755 assert_eq!(txn.len(), 2);
756 check_spends!(txn[0], funding_tx);
757 check_spends!(txn[1], as_commitment_tx);
761 if !confirm_before_reload {
762 mine_transaction(&nodes[0], &as_commitment_tx);
763 let txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
764 assert_eq!(txn.len(), 1);
765 assert_eq!(txn[0].txid(), as_commitment_tx.txid());
767 mine_transaction(&nodes[0], &bs_htlc_claim_txn);
768 expect_payment_sent(&nodes[0], payment_preimage_1, None, true, false);
769 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
770 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
771 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
772 assert_eq!(txn.len(), 2);
773 (txn.remove(0), txn.remove(0))
775 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
776 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
777 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn.input[0].previous_output {
778 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
780 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
782 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
783 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
785 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
786 // reloaded) via a route over the new channel, which work without issue and eventually be
787 // received and claimed at the recipient just like any other payment.
788 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
790 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
791 // and not the original fee. We also update node[1]'s relevant config as
792 // do_claim_payment_along_route expects us to never overpay.
794 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
795 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
796 .unwrap().lock().unwrap();
797 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
798 let mut new_config = channel.context().config();
799 new_config.forwarding_fee_base_msat += 100_000;
800 channel.context_mut().update_config(&new_config);
801 new_route.paths[0].hops[0].fee_msat += 100_000;
804 // Force expiration of the channel's previous config.
805 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
806 nodes[1].node.timer_tick_occurred();
809 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
810 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
811 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
812 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
813 check_added_monitors!(nodes[0], 1);
814 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
815 assert_eq!(events.len(), 1);
816 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
817 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
818 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
822 fn retry_with_no_persist() {
823 do_retry_with_no_persist(true);
824 do_retry_with_no_persist(false);
827 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
828 // Test that an off-chain completed payment is not retryable on restart. This was previously
829 // broken for dust payments, but we test for both dust and non-dust payments.
831 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
833 let chanmon_cfgs = create_chanmon_cfgs(3);
834 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
836 let mut manually_accept_config = test_default_channel_config();
837 manually_accept_config.manually_accept_inbound_channels = true;
840 let first_new_chain_monitor;
841 let second_persister;
842 let second_new_chain_monitor;
844 let third_new_chain_monitor;
846 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
847 let first_nodes_0_deserialized;
848 let second_nodes_0_deserialized;
849 let third_nodes_0_deserialized;
851 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
853 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
854 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
855 confirm_transaction(&nodes[0], &funding_tx);
856 confirm_transaction(&nodes[1], &funding_tx);
857 // Ignore the announcement_signatures messages
858 nodes[0].node.get_and_clear_pending_msg_events();
859 nodes[1].node.get_and_clear_pending_msg_events();
860 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
862 // Serialize the ChannelManager prior to sending payments
863 let mut nodes_0_serialized = nodes[0].node.encode();
865 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
866 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 });
868 // The ChannelMonitor should always be the latest version, as we're required to persist it
869 // during the `commitment_signed_dance!()`.
870 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
872 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);
873 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
875 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
876 // force-close the channel.
877 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager, [nodes[1].node.get_our_node_id()], 100000);
878 nodes[0].node.timer_tick_occurred();
879 assert!(nodes[0].node.list_channels().is_empty());
880 assert!(nodes[0].node.has_pending_payments());
881 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
882 check_added_monitors!(nodes[0], 1);
884 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
885 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
887 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
889 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
890 // error, as the channel has hit the chain.
891 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
892 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
894 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
895 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
896 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
897 assert_eq!(as_err.len(), 2);
898 let bs_commitment_tx;
900 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
901 assert_eq!(node_id, nodes[1].node.get_our_node_id());
902 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
903 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())) }
904 , [nodes[0].node.get_our_node_id()], 100000);
905 check_added_monitors!(nodes[1], 1);
906 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
908 _ => panic!("Unexpected event"),
910 check_closed_broadcast!(nodes[1], false);
912 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
913 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
914 // incoming HTLCs with the same payment hash later.
915 nodes[2].node.fail_htlc_backwards(&payment_hash);
916 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
917 check_added_monitors!(nodes[2], 1);
919 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
920 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
921 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
922 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
923 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
925 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
926 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
927 // after the commitment transaction, so always connect the commitment transaction.
928 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
929 if nodes[0].connect_style.borrow().updates_best_block_first() {
930 let _ = nodes[0].tx_broadcaster.txn_broadcast();
932 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
934 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
935 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
936 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
937 assert_eq!(as_htlc_timeout.len(), 1);
938 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
940 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
941 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
943 if nodes[0].connect_style.borrow().updates_best_block_first() {
944 let _ = nodes[0].tx_broadcaster.txn_broadcast();
947 // Create a new channel on which to retry the payment before we fail the payment via the
948 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
949 // connecting several blocks while creating the channel (implying time has passed).
950 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
951 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
952 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
954 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
955 // confirming, we will fail as it's considered still-pending...
956 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
957 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
958 Err(PaymentSendFailure::DuplicatePayment) => {},
959 _ => panic!("Unexpected error")
961 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
963 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
964 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
965 // (which should also still work).
966 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
967 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
968 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
970 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
971 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
972 nodes_0_serialized = nodes[0].node.encode();
974 // After the payment failed, we're free to send it again.
975 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
976 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
977 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
979 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);
980 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
982 nodes[0].node.test_process_background_events();
983 check_added_monitors(&nodes[0], 1);
985 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
986 reconnect_args.send_channel_ready = (true, true);
987 reconnect_nodes(reconnect_args);
989 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
990 // the payment is not (spuriously) listed as still pending.
991 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
992 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
993 check_added_monitors!(nodes[0], 1);
994 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
995 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
997 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
998 Err(PaymentSendFailure::DuplicatePayment) => {},
999 _ => panic!("Unexpected error")
1001 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1003 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1004 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
1005 nodes_0_serialized = nodes[0].node.encode();
1007 // Check that after reload we can send the payment again (though we shouldn't, since it was
1008 // claimed previously).
1009 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);
1010 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
1012 nodes[0].node.test_process_background_events();
1013 check_added_monitors(&nodes[0], 1);
1015 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1017 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
1018 Err(PaymentSendFailure::DuplicatePayment) => {},
1019 _ => panic!("Unexpected error")
1021 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1025 fn test_completed_payment_not_retryable_on_reload() {
1026 do_test_completed_payment_not_retryable_on_reload(true);
1027 do_test_completed_payment_not_retryable_on_reload(false);
1031 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
1032 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
1033 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
1034 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
1035 // the ChannelMonitor tells it to.
1037 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
1038 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
1039 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
1040 let chanmon_cfgs = create_chanmon_cfgs(2);
1041 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1043 let new_chain_monitor;
1044 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1045 let nodes_0_deserialized;
1046 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1048 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
1050 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
1052 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
1053 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
1054 check_closed_broadcast!(nodes[0], true);
1055 check_added_monitors!(nodes[0], 1);
1056 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
1058 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1059 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
1061 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
1062 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
1063 let (commitment_tx, htlc_timeout_tx) = {
1064 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
1065 assert_eq!(txn.len(), 2);
1066 check_spends!(txn[0], funding_tx);
1067 check_spends!(txn[1], txn[0]);
1068 (txn.remove(0), txn.remove(0))
1071 nodes[1].node.claim_funds(payment_preimage);
1072 check_added_monitors!(nodes[1], 1);
1073 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
1075 mine_transaction(&nodes[1], &commitment_tx);
1076 check_closed_broadcast!(nodes[1], true);
1077 check_added_monitors!(nodes[1], 1);
1078 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
1079 let htlc_success_tx = {
1080 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
1081 assert_eq!(txn.len(), 1);
1082 check_spends!(txn[0], commitment_tx);
1086 mine_transaction(&nodes[0], &commitment_tx);
1088 if confirm_commitment_tx {
1089 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
1092 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { vec![htlc_timeout_tx] } else { vec![htlc_success_tx] });
1094 if payment_timeout {
1095 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
1096 connect_block(&nodes[0], &claim_block);
1097 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
1100 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
1101 // returning InProgress. This should cause the claim event to never make its way to the
1103 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
1104 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
1106 if payment_timeout {
1107 connect_blocks(&nodes[0], 1);
1109 connect_block(&nodes[0], &claim_block);
1112 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
1113 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
1114 .get_mut(&funding_txo).unwrap().drain().collect();
1115 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
1116 // If we're testing connection idempotency we may get substantially more.
1117 assert!(mon_updates.len() >= 1);
1118 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
1119 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1121 // If we persist the ChannelManager here, we should get the PaymentSent event after
1123 let mut chan_manager_serialized = Vec::new();
1124 if !persist_manager_post_event {
1125 chan_manager_serialized = nodes[0].node.encode();
1128 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
1129 // payment sent event.
1130 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1131 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
1132 for update in mon_updates {
1133 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
1135 if payment_timeout {
1136 expect_payment_failed!(nodes[0], payment_hash, false);
1138 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1141 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
1143 if persist_manager_post_event {
1144 chan_manager_serialized = nodes[0].node.encode();
1147 // Now reload nodes[0]...
1148 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
1150 if persist_manager_post_event {
1151 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1152 } else if payment_timeout {
1153 expect_payment_failed!(nodes[0], payment_hash, false);
1155 expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
1158 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
1159 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
1160 // payment events should kick in, leaving us with no pending events here.
1161 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
1162 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
1163 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1164 check_added_monitors(&nodes[0], 1);
1168 fn test_dup_htlc_onchain_fails_on_reload() {
1169 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
1170 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
1171 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
1172 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
1173 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
1174 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
1178 fn test_fulfill_restart_failure() {
1179 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
1180 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
1181 // again, or fail it, giving us free money.
1183 // Of course probably they won't fail it and give us free money, but because we have code to
1184 // handle it, we should test the logic for it anyway. We do that here.
1185 let chanmon_cfgs = create_chanmon_cfgs(2);
1186 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1188 let new_chain_monitor;
1189 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1190 let nodes_1_deserialized;
1191 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1193 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1194 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
1196 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
1197 // pre-fulfill, which we do by serializing it here.
1198 let chan_manager_serialized = nodes[1].node.encode();
1199 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
1201 nodes[1].node.claim_funds(payment_preimage);
1202 check_added_monitors!(nodes[1], 1);
1203 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
1205 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1206 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
1207 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
1209 // Now reload nodes[1]...
1210 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
1212 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1213 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
1215 nodes[1].node.fail_htlc_backwards(&payment_hash);
1216 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1217 check_added_monitors!(nodes[1], 1);
1218 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1219 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1220 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1221 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1222 // it had already considered the payment fulfilled, and now they just got free money.
1223 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1227 fn get_ldk_payment_preimage() {
1228 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1229 let chanmon_cfgs = create_chanmon_cfgs(2);
1230 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1231 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1232 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1233 create_announced_chan_between_nodes(&nodes, 0, 1);
1235 let amt_msat = 60_000;
1236 let expiry_secs = 60 * 60;
1237 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
1239 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1240 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
1241 let scorer = test_utils::TestScorer::new();
1242 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1243 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1244 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
1245 let route = get_route( &nodes[0].node.get_our_node_id(), &route_params,
1246 &nodes[0].network_graph.read_only(),
1247 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()), nodes[0].logger,
1248 &scorer, &Default::default(), &random_seed_bytes).unwrap();
1249 nodes[0].node.send_payment_with_route(&route, payment_hash,
1250 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1251 check_added_monitors!(nodes[0], 1);
1253 // Make sure to use `get_payment_preimage`
1254 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1255 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1256 assert_eq!(events.len(), 1);
1257 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1258 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1262 fn sent_probe_is_probe_of_sending_node() {
1263 let chanmon_cfgs = create_chanmon_cfgs(3);
1264 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1265 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1266 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1268 create_announced_chan_between_nodes(&nodes, 0, 1);
1269 create_announced_chan_between_nodes(&nodes, 1, 2);
1271 // First check we refuse to build a single-hop probe
1272 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1273 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1275 // Then build an actual two-hop probing path
1276 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1278 match nodes[0].node.send_probe(route.paths[0].clone()) {
1279 Ok((payment_hash, payment_id)) => {
1280 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1281 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1282 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1287 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1288 check_added_monitors!(nodes[0], 1);
1292 fn successful_probe_yields_event() {
1293 let chanmon_cfgs = create_chanmon_cfgs(3);
1294 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1295 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1296 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1298 create_announced_chan_between_nodes(&nodes, 0, 1);
1299 create_announced_chan_between_nodes(&nodes, 1, 2);
1301 let recv_value = 100_000;
1302 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], recv_value);
1304 let res = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1306 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[2]]];
1308 send_probe_along_route(&nodes[0], expected_route);
1310 expect_probe_successful_events(&nodes[0], vec![res]);
1312 assert!(!nodes[0].node.has_pending_payments());
1316 fn failed_probe_yields_event() {
1317 let chanmon_cfgs = create_chanmon_cfgs(3);
1318 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1319 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1320 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1322 create_announced_chan_between_nodes(&nodes, 0, 1);
1323 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1325 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1327 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 9_998_000);
1329 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1331 // node[0] -- update_add_htlcs -> node[1]
1332 check_added_monitors!(nodes[0], 1);
1333 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1334 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1335 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1336 check_added_monitors!(nodes[1], 0);
1337 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1338 expect_pending_htlcs_forwardable!(nodes[1]);
1340 // node[0] <- update_fail_htlcs -- node[1]
1341 check_added_monitors!(nodes[1], 1);
1342 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1343 // Skip the PendingHTLCsForwardable event
1344 let _events = nodes[1].node.get_and_clear_pending_events();
1345 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1346 check_added_monitors!(nodes[0], 0);
1347 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1349 let mut events = nodes[0].node.get_and_clear_pending_events();
1350 assert_eq!(events.len(), 1);
1351 match events.drain(..).next().unwrap() {
1352 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1353 assert_eq!(payment_id, ev_pid);
1354 assert_eq!(payment_hash, ev_ph);
1358 assert!(!nodes[0].node.has_pending_payments());
1362 fn onchain_failed_probe_yields_event() {
1363 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1365 let chanmon_cfgs = create_chanmon_cfgs(3);
1366 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1367 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1368 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1370 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1371 create_announced_chan_between_nodes(&nodes, 1, 2);
1373 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1375 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1376 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], payment_params, 1_000);
1377 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1379 // node[0] -- update_add_htlcs -> node[1]
1380 check_added_monitors!(nodes[0], 1);
1381 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1382 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1383 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1384 check_added_monitors!(nodes[1], 0);
1385 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1386 expect_pending_htlcs_forwardable!(nodes[1]);
1388 check_added_monitors!(nodes[1], 1);
1389 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1391 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1392 // Node A, which after 6 confirmations should result in a probe failure event.
1393 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1394 confirm_transaction(&nodes[0], &bs_txn[0]);
1395 check_closed_broadcast!(&nodes[0], true);
1396 check_added_monitors!(nodes[0], 1);
1398 let mut events = nodes[0].node.get_and_clear_pending_events();
1399 assert_eq!(events.len(), 2);
1400 let mut found_probe_failed = false;
1401 for event in events.drain(..) {
1403 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1404 assert_eq!(payment_id, ev_pid);
1405 assert_eq!(payment_hash, ev_ph);
1406 found_probe_failed = true;
1408 Event::ChannelClosed { .. } => {},
1412 assert!(found_probe_failed);
1413 assert!(!nodes[0].node.has_pending_payments());
1417 fn preflight_probes_yield_event_skip_private_hop() {
1418 let chanmon_cfgs = create_chanmon_cfgs(5);
1419 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1421 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1422 let mut no_htlc_limit_config = test_default_channel_config();
1423 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1425 let user_configs = std::iter::repeat(no_htlc_limit_config).take(5).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1426 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &user_configs);
1427 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1429 // Setup channel topology:
1430 // N0 -(1M:0)- N1 -(1M:0)- N2 -(70k:0)- N3 -(50k:0)- N4
1432 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1433 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
1434 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 70_000, 0);
1435 create_unannounced_chan_between_nodes_with_value(&nodes, 3, 4, 50_000, 0);
1437 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1438 invoice_features.set_basic_mpp_optional();
1440 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
1441 .with_bolt11_features(invoice_features).unwrap();
1443 let recv_value = 50_000_000;
1444 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1445 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1447 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[2], &nodes[3]]];
1449 assert_eq!(res.len(), expected_route.len());
1451 send_probe_along_route(&nodes[0], expected_route);
1453 expect_probe_successful_events(&nodes[0], res.clone());
1455 assert!(!nodes[0].node.has_pending_payments());
1459 fn preflight_probes_yield_event() {
1460 let chanmon_cfgs = create_chanmon_cfgs(4);
1461 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1463 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1464 let mut no_htlc_limit_config = test_default_channel_config();
1465 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1467 let user_configs = std::iter::repeat(no_htlc_limit_config).take(4).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1468 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &user_configs);
1469 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1471 // Setup channel topology:
1472 // (1M:0)- N1 -(30k:0)
1476 // (1M:0)- N2 -(70k:0)
1478 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1479 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1480 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 30_000, 0);
1481 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 70_000, 0);
1483 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1484 invoice_features.set_basic_mpp_optional();
1486 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
1487 .with_bolt11_features(invoice_features).unwrap();
1489 let recv_value = 50_000_000;
1490 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1491 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1493 let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
1495 assert_eq!(res.len(), expected_route.len());
1497 send_probe_along_route(&nodes[0], expected_route);
1499 expect_probe_successful_events(&nodes[0], res.clone());
1501 assert!(!nodes[0].node.has_pending_payments());
1505 fn preflight_probes_yield_event_and_skip() {
1506 let chanmon_cfgs = create_chanmon_cfgs(5);
1507 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1509 // We alleviate the HTLC max-in-flight limit, as otherwise we'd always be limited through that.
1510 let mut no_htlc_limit_config = test_default_channel_config();
1511 no_htlc_limit_config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
1513 let user_configs = std::iter::repeat(no_htlc_limit_config).take(5).map(|c| Some(c)).collect::<Vec<Option<UserConfig>>>();
1514 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &user_configs);
1515 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1517 // Setup channel topology:
1518 // (30k:0)- N2 -(1M:0)
1520 // N0 -(100k:0)-> N1 N4
1522 // (70k:0)- N3 -(1M:0)
1524 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1525 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 30_000, 0);
1526 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 70_000, 0);
1527 create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 1_000_000, 0);
1528 create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0);
1530 let mut invoice_features = Bolt11InvoiceFeatures::empty();
1531 invoice_features.set_basic_mpp_optional();
1533 let payment_params = PaymentParameters::from_node_id(nodes[4].node.get_our_node_id(), TEST_FINAL_CLTV)
1534 .with_bolt11_features(invoice_features).unwrap();
1536 let recv_value = 80_000_000;
1537 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
1538 let res = nodes[0].node.send_preflight_probes(route_params, None).unwrap();
1540 let expected_route : &[&[&Node]] = &[&[&nodes[1], &nodes[2], &nodes[4]]];
1542 // We check that only one probe was sent, the other one was skipped due to limited liquidity.
1543 assert_eq!(res.len(), 1);
1545 send_probe_along_route(&nodes[0], expected_route);
1547 expect_probe_successful_events(&nodes[0], res.clone());
1549 assert!(!nodes[0].node.has_pending_payments());
1553 fn claimed_send_payment_idempotent() {
1554 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1555 let chanmon_cfgs = create_chanmon_cfgs(2);
1556 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1557 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1558 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1560 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1562 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1563 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1565 macro_rules! check_send_rejected {
1567 // If we try to resend a new payment with a different payment_hash but with the same
1568 // payment_id, it should be rejected.
1569 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1570 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1572 Err(PaymentSendFailure::DuplicatePayment) => {},
1573 _ => panic!("Unexpected send result: {:?}", send_result),
1576 // Further, if we try to send a spontaneous payment with the same payment_id it should
1577 // also be rejected.
1578 let send_result = nodes[0].node.send_spontaneous_payment(
1579 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1581 Err(PaymentSendFailure::DuplicatePayment) => {},
1582 _ => panic!("Unexpected send result: {:?}", send_result),
1587 check_send_rejected!();
1589 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1590 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1591 // we must remain just as idempotent as we were before.
1592 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1594 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1595 nodes[0].node.timer_tick_occurred();
1598 check_send_rejected!();
1600 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1601 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1602 // the payment complete. However, they could have called `send_payment` while the event was
1603 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1604 // after the event is handled a duplicate payment should sitll be rejected.
1605 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1606 check_send_rejected!();
1608 // If relatively little time has passed, a duplicate payment should still fail.
1609 nodes[0].node.timer_tick_occurred();
1610 check_send_rejected!();
1612 // However, after some time has passed (at least more than the one timer tick above), a
1613 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1614 // references to the old payment data.
1615 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1616 nodes[0].node.timer_tick_occurred();
1619 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1620 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1621 check_added_monitors!(nodes[0], 1);
1622 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1623 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1627 fn abandoned_send_payment_idempotent() {
1628 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1630 let chanmon_cfgs = create_chanmon_cfgs(2);
1631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1633 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1635 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1637 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1638 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1640 macro_rules! check_send_rejected {
1642 // If we try to resend a new payment with a different payment_hash but with the same
1643 // payment_id, it should be rejected.
1644 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1645 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1647 Err(PaymentSendFailure::DuplicatePayment) => {},
1648 _ => panic!("Unexpected send result: {:?}", send_result),
1651 // Further, if we try to send a spontaneous payment with the same payment_id it should
1652 // also be rejected.
1653 let send_result = nodes[0].node.send_spontaneous_payment(
1654 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1656 Err(PaymentSendFailure::DuplicatePayment) => {},
1657 _ => panic!("Unexpected send result: {:?}", send_result),
1662 check_send_rejected!();
1664 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1665 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1667 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1669 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1670 nodes[0].node.timer_tick_occurred();
1672 check_send_rejected!();
1674 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1676 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1677 // failed payment back.
1678 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1679 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1680 check_added_monitors!(nodes[0], 1);
1681 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1682 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1685 #[derive(PartialEq)]
1686 enum InterceptTest {
1693 fn test_trivial_inflight_htlc_tracking(){
1694 // In this test, we test three scenarios:
1695 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1696 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1697 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1698 let chanmon_cfgs = create_chanmon_cfgs(3);
1699 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1700 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1701 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1703 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1704 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1706 // Send and claim the payment. Inflight HTLCs should be empty.
1707 let (_, payment_hash, _, payment_id) = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1708 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1710 let mut node_0_per_peer_lock;
1711 let mut node_0_peer_state_lock;
1712 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1714 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1715 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1716 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1717 channel_1.context().get_short_channel_id().unwrap()
1719 assert_eq!(chan_1_used_liquidity, None);
1722 let mut node_1_per_peer_lock;
1723 let mut node_1_peer_state_lock;
1724 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1726 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1727 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1728 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1729 channel_2.context().get_short_channel_id().unwrap()
1732 assert_eq!(chan_2_used_liquidity, None);
1734 let pending_payments = nodes[0].node.list_recent_payments();
1735 assert_eq!(pending_payments.len(), 1);
1736 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash), payment_id });
1738 // Remove fulfilled payment
1739 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1740 nodes[0].node.timer_tick_occurred();
1743 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1744 let (payment_preimage, payment_hash, _, payment_id) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1745 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1747 let mut node_0_per_peer_lock;
1748 let mut node_0_peer_state_lock;
1749 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1751 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1752 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1753 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1754 channel_1.context().get_short_channel_id().unwrap()
1756 // First hop accounts for expected 1000 msat fee
1757 assert_eq!(chan_1_used_liquidity, Some(501000));
1760 let mut node_1_per_peer_lock;
1761 let mut node_1_peer_state_lock;
1762 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1764 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1765 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1766 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1767 channel_2.context().get_short_channel_id().unwrap()
1770 assert_eq!(chan_2_used_liquidity, Some(500000));
1772 let pending_payments = nodes[0].node.list_recent_payments();
1773 assert_eq!(pending_payments.len(), 1);
1774 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_id, payment_hash, total_msat: 500000 });
1776 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1777 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1779 // Remove fulfilled payment
1780 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1781 nodes[0].node.timer_tick_occurred();
1784 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1786 let mut node_0_per_peer_lock;
1787 let mut node_0_peer_state_lock;
1788 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1790 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1791 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1792 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1793 channel_1.context().get_short_channel_id().unwrap()
1795 assert_eq!(chan_1_used_liquidity, None);
1798 let mut node_1_per_peer_lock;
1799 let mut node_1_peer_state_lock;
1800 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1802 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1803 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1804 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1805 channel_2.context().get_short_channel_id().unwrap()
1807 assert_eq!(chan_2_used_liquidity, None);
1810 let pending_payments = nodes[0].node.list_recent_payments();
1811 assert_eq!(pending_payments.len(), 0);
1815 fn test_holding_cell_inflight_htlcs() {
1816 let chanmon_cfgs = create_chanmon_cfgs(2);
1817 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1818 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1819 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1820 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1822 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1823 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1825 // Queue up two payments - one will be delivered right away, one immediately goes into the
1826 // holding cell as nodes[0] is AwaitingRAA.
1828 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1829 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1830 check_added_monitors!(nodes[0], 1);
1831 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1832 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1833 check_added_monitors!(nodes[0], 0);
1836 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1839 let mut node_0_per_peer_lock;
1840 let mut node_0_peer_state_lock;
1841 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1843 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1844 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1845 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1846 channel.context().get_short_channel_id().unwrap()
1849 assert_eq!(used_liquidity, Some(2000000));
1852 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1853 nodes[0].node.get_and_clear_pending_msg_events();
1857 fn intercepted_payment() {
1858 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1859 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1860 // payment or (b) fail the payment.
1861 do_test_intercepted_payment(InterceptTest::Forward);
1862 do_test_intercepted_payment(InterceptTest::Fail);
1863 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1864 do_test_intercepted_payment(InterceptTest::Timeout);
1867 fn do_test_intercepted_payment(test: InterceptTest) {
1868 let chanmon_cfgs = create_chanmon_cfgs(3);
1869 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1871 let mut zero_conf_chan_config = test_default_channel_config();
1872 zero_conf_chan_config.manually_accept_inbound_channels = true;
1873 let mut intercept_forwards_config = test_default_channel_config();
1874 intercept_forwards_config.accept_intercept_htlcs = true;
1875 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1877 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1878 let scorer = test_utils::TestScorer::new();
1879 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1881 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1883 let amt_msat = 100_000;
1884 let intercept_scid = nodes[1].node.get_intercept_scid();
1885 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1886 .with_route_hints(vec![
1887 RouteHint(vec![RouteHintHop {
1888 src_node_id: nodes[1].node.get_our_node_id(),
1889 short_channel_id: intercept_scid,
1892 proportional_millionths: 0,
1894 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1895 htlc_minimum_msat: None,
1896 htlc_maximum_msat: None,
1899 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap();
1900 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
1901 let route = get_route(
1902 &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
1903 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
1906 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1907 nodes[0].node.send_payment_with_route(&route, payment_hash,
1908 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1909 let payment_event = {
1911 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1912 assert_eq!(added_monitors.len(), 1);
1913 added_monitors.clear();
1915 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1916 assert_eq!(events.len(), 1);
1917 SendEvent::from_event(events.remove(0))
1919 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1920 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1922 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1923 let events = nodes[1].node.get_and_clear_pending_events();
1924 assert_eq!(events.len(), 1);
1925 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1926 crate::events::Event::HTLCIntercepted {
1927 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1929 assert_eq!(pmt_hash, payment_hash);
1930 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1931 assert_eq!(short_channel_id, intercept_scid);
1932 (intercept_id, expected_outbound_amount_msat)
1937 // Check for unknown channel id error.
1938 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();
1939 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable {
1940 err: format!("Channel with id {} not found for the passed counterparty node_id {}",
1941 log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1943 if test == InterceptTest::Fail {
1944 // Ensure we can fail the intercepted payment back.
1945 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1946 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1947 nodes[1].node.process_pending_htlc_forwards();
1948 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1949 check_added_monitors!(&nodes[1], 1);
1950 assert!(update_fail.update_fail_htlcs.len() == 1);
1951 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1952 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1953 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1955 // Ensure the payment fails with the expected error.
1956 let fail_conditions = PaymentFailedConditions::new()
1957 .blamed_scid(intercept_scid)
1958 .blamed_chan_closed(true)
1959 .expected_htlc_error_data(0x4000 | 10, &[]);
1960 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1961 } else if test == InterceptTest::Forward {
1962 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1963 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
1964 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();
1965 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable {
1966 err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
1967 temp_chan_id, nodes[2].node.get_our_node_id()) });
1968 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1970 // Open the just-in-time channel so the payment can then be forwarded.
1971 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1973 // Finally, forward the intercepted payment through and claim it.
1974 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1975 expect_pending_htlcs_forwardable!(nodes[1]);
1977 let payment_event = {
1979 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1980 assert_eq!(added_monitors.len(), 1);
1981 added_monitors.clear();
1983 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1984 assert_eq!(events.len(), 1);
1985 SendEvent::from_event(events.remove(0))
1987 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1988 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1989 expect_pending_htlcs_forwardable!(nodes[2]);
1991 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1992 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1993 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1994 let events = nodes[0].node.get_and_clear_pending_events();
1995 assert_eq!(events.len(), 2);
1997 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1998 assert_eq!(payment_preimage, *ev_preimage);
1999 assert_eq!(payment_hash, *ev_hash);
2000 assert_eq!(fee_paid_msat, &Some(1000));
2002 _ => panic!("Unexpected event")
2005 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
2006 assert_eq!(hash, Some(payment_hash));
2008 _ => panic!("Unexpected event")
2010 check_added_monitors(&nodes[0], 1);
2011 } else if test == InterceptTest::Timeout {
2012 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
2013 connect_block(&nodes[0], &block);
2014 connect_block(&nodes[1], &block);
2015 for _ in 0..TEST_FINAL_CLTV {
2016 block.header.prev_blockhash = block.block_hash();
2017 connect_block(&nodes[0], &block);
2018 connect_block(&nodes[1], &block);
2020 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
2021 check_added_monitors!(nodes[1], 1);
2022 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2023 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
2024 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
2025 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
2026 assert!(htlc_timeout_updates.update_fee.is_none());
2028 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
2029 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
2030 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
2032 // Check for unknown intercept id error.
2033 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
2034 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();
2035 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2036 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
2037 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
2042 fn accept_underpaying_htlcs_config() {
2043 do_accept_underpaying_htlcs_config(1);
2044 do_accept_underpaying_htlcs_config(2);
2045 do_accept_underpaying_htlcs_config(3);
2048 fn do_accept_underpaying_htlcs_config(num_mpp_parts: usize) {
2049 let chanmon_cfgs = create_chanmon_cfgs(3);
2050 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2051 let mut intercept_forwards_config = test_default_channel_config();
2052 intercept_forwards_config.accept_intercept_htlcs = true;
2053 let mut underpay_config = test_default_channel_config();
2054 underpay_config.channel_config.accept_underpaying_htlcs = true;
2055 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(underpay_config)]);
2056 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2058 let mut chan_ids = Vec::new();
2059 for _ in 0..num_mpp_parts {
2060 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000, 0);
2061 let channel_id = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 2_000_000, 0).0.channel_id;
2062 chan_ids.push(channel_id);
2065 // Send the initial payment.
2066 let amt_msat = 900_000;
2067 let skimmed_fee_msat = 20;
2068 let mut route_hints = Vec::new();
2069 for _ in 0..num_mpp_parts {
2070 route_hints.push(RouteHint(vec![RouteHintHop {
2071 src_node_id: nodes[1].node.get_our_node_id(),
2072 short_channel_id: nodes[1].node.get_intercept_scid(),
2075 proportional_millionths: 0,
2077 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
2078 htlc_minimum_msat: None,
2079 htlc_maximum_msat: Some(amt_msat / num_mpp_parts as u64 + 5),
2082 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2083 .with_route_hints(route_hints).unwrap()
2084 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap();
2085 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2086 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
2087 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2088 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2089 check_added_monitors!(nodes[0], num_mpp_parts); // one monitor per path
2090 let mut events: Vec<SendEvent> = nodes[0].node.get_and_clear_pending_msg_events().into_iter().map(|e| SendEvent::from_event(e)).collect();
2091 assert_eq!(events.len(), num_mpp_parts);
2093 // Forward the intercepted payments.
2094 for (idx, ev) in events.into_iter().enumerate() {
2095 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &ev.msgs[0]);
2096 do_commitment_signed_dance(&nodes[1], &nodes[0], &ev.commitment_msg, false, true);
2098 let events = nodes[1].node.get_and_clear_pending_events();
2099 assert_eq!(events.len(), 1);
2100 let (intercept_id, expected_outbound_amt_msat) = match events[0] {
2101 crate::events::Event::HTLCIntercepted {
2102 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, ..
2104 assert_eq!(pmt_hash, payment_hash);
2105 (intercept_id, expected_outbound_amount_msat)
2109 nodes[1].node.forward_intercepted_htlc(intercept_id, &chan_ids[idx],
2110 nodes[2].node.get_our_node_id(), expected_outbound_amt_msat - skimmed_fee_msat).unwrap();
2111 expect_pending_htlcs_forwardable!(nodes[1]);
2112 let payment_event = {
2114 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2115 assert_eq!(added_monitors.len(), 1);
2116 added_monitors.clear();
2118 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2119 assert_eq!(events.len(), 1);
2120 SendEvent::from_event(events.remove(0))
2122 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
2123 do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event.commitment_msg, false, true);
2124 if idx == num_mpp_parts - 1 {
2125 expect_pending_htlcs_forwardable!(nodes[2]);
2129 // Claim the payment and check that the skimmed fee is as expected.
2130 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
2131 let events = nodes[2].node.get_and_clear_pending_events();
2132 assert_eq!(events.len(), 1);
2134 crate::events::Event::PaymentClaimable {
2135 ref payment_hash, ref purpose, amount_msat, counterparty_skimmed_fee_msat, receiver_node_id, ..
2137 assert_eq!(payment_hash, payment_hash);
2138 assert_eq!(amt_msat - skimmed_fee_msat * num_mpp_parts as u64, amount_msat);
2139 assert_eq!(skimmed_fee_msat * num_mpp_parts as u64, counterparty_skimmed_fee_msat);
2140 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2142 crate::events::PaymentPurpose::InvoicePayment { payment_preimage: ev_payment_preimage,
2143 payment_secret: ev_payment_secret, .. } =>
2145 assert_eq!(payment_preimage, ev_payment_preimage.unwrap());
2146 assert_eq!(payment_secret, *ev_payment_secret);
2151 _ => panic!("Unexpected event"),
2153 let mut expected_paths_vecs = Vec::new();
2154 let mut expected_paths = Vec::new();
2155 for _ in 0..num_mpp_parts { expected_paths_vecs.push(vec!(&nodes[1], &nodes[2])); }
2156 for i in 0..num_mpp_parts { expected_paths.push(&expected_paths_vecs[i][..]); }
2157 let total_fee_msat = do_claim_payment_along_route_with_extra_penultimate_hop_fees(
2158 &nodes[0], &expected_paths[..], &vec![skimmed_fee_msat as u32; num_mpp_parts][..], false,
2160 // The sender doesn't know that the penultimate hop took an extra fee.
2161 expect_payment_sent(&nodes[0], payment_preimage,
2162 Some(Some(total_fee_msat - skimmed_fee_msat * num_mpp_parts as u64)), true, true);
2165 #[derive(PartialEq)]
2176 fn automatic_retries() {
2177 do_automatic_retries(AutoRetry::Success);
2178 do_automatic_retries(AutoRetry::Spontaneous);
2179 do_automatic_retries(AutoRetry::FailAttempts);
2180 do_automatic_retries(AutoRetry::FailTimeout);
2181 do_automatic_retries(AutoRetry::FailOnRestart);
2182 do_automatic_retries(AutoRetry::FailOnRetry);
2184 fn do_automatic_retries(test: AutoRetry) {
2185 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
2187 let chanmon_cfgs = create_chanmon_cfgs(3);
2188 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2190 let new_chain_monitor;
2192 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2193 let node_0_deserialized;
2195 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2196 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2197 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2199 // Marshall data to send the payment
2200 #[cfg(feature = "std")]
2201 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2202 #[cfg(not(feature = "std"))]
2203 let payment_expiry_secs = 60 * 60;
2204 let amt_msat = 1000;
2205 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2206 invoice_features.set_variable_length_onion_required();
2207 invoice_features.set_payment_secret_required();
2208 invoice_features.set_basic_mpp_optional();
2209 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
2210 .with_expiry_time(payment_expiry_secs as u64)
2211 .with_bolt11_features(invoice_features).unwrap();
2212 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2213 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
2215 macro_rules! pass_failed_attempt_with_retry_along_path {
2216 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
2217 // Send a payment attempt that fails due to lack of liquidity on the second hop
2218 check_added_monitors!(nodes[0], 1);
2219 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2220 let mut update_add = update_0.update_add_htlcs[0].clone();
2221 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
2222 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
2223 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2224 nodes[1].node.process_pending_htlc_forwards();
2225 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
2226 vec![HTLCDestination::NextHopChannel {
2227 node_id: Some(nodes[2].node.get_our_node_id()),
2228 channel_id: $failing_channel_id,
2230 nodes[1].node.process_pending_htlc_forwards();
2231 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2232 check_added_monitors!(&nodes[1], 1);
2233 assert!(update_1.update_fail_htlcs.len() == 1);
2234 let fail_msg = update_1.update_fail_htlcs[0].clone();
2235 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
2236 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
2238 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
2239 let mut events = nodes[0].node.get_and_clear_pending_events();
2240 assert_eq!(events.len(), 2);
2242 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2243 assert_eq!(payment_hash, ev_payment_hash);
2244 assert_eq!(payment_failed_permanently, false);
2246 _ => panic!("Unexpected event"),
2248 if $expect_pending_htlcs_forwardable {
2250 Event::PendingHTLCsForwardable { .. } => {},
2251 _ => panic!("Unexpected event"),
2255 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
2256 assert_eq!(payment_hash, ev_payment_hash);
2258 _ => panic!("Unexpected event"),
2264 if test == AutoRetry::Success {
2265 // Test that we can succeed on the first retry.
2266 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2267 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2268 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2270 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2271 // attempt, since the initial second hop channel will be excluded from pathfinding
2272 create_announced_chan_between_nodes(&nodes, 1, 2);
2274 // We retry payments in `process_pending_htlc_forwards`
2275 nodes[0].node.process_pending_htlc_forwards();
2276 check_added_monitors!(nodes[0], 1);
2277 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2278 assert_eq!(msg_events.len(), 1);
2279 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
2280 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2281 } else if test == AutoRetry::Spontaneous {
2282 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
2283 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
2284 Retry::Attempts(1)).unwrap();
2285 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2287 // Open a new channel with liquidity on the second hop so we can find a route for the retry
2288 // attempt, since the initial second hop channel will be excluded from pathfinding
2289 create_announced_chan_between_nodes(&nodes, 1, 2);
2291 // We retry payments in `process_pending_htlc_forwards`
2292 nodes[0].node.process_pending_htlc_forwards();
2293 check_added_monitors!(nodes[0], 1);
2294 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2295 assert_eq!(msg_events.len(), 1);
2296 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
2297 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
2298 } else if test == AutoRetry::FailAttempts {
2299 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
2300 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2301 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2302 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2304 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2305 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2306 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2308 // We retry payments in `process_pending_htlc_forwards`
2309 nodes[0].node.process_pending_htlc_forwards();
2310 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
2312 // Ensure we won't retry a second time.
2313 nodes[0].node.process_pending_htlc_forwards();
2314 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2315 assert_eq!(msg_events.len(), 0);
2316 } else if test == AutoRetry::FailTimeout {
2317 #[cfg(not(feature = "no-std"))] {
2318 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
2319 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2320 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
2321 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2323 // Advance the time so the second attempt fails due to timeout.
2324 SinceEpoch::advance(Duration::from_secs(61));
2326 // Make sure we don't retry again.
2327 nodes[0].node.process_pending_htlc_forwards();
2328 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2329 assert_eq!(msg_events.len(), 0);
2331 let mut events = nodes[0].node.get_and_clear_pending_events();
2332 assert_eq!(events.len(), 1);
2334 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2335 assert_eq!(payment_hash, *ev_payment_hash);
2336 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2337 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2339 _ => panic!("Unexpected event"),
2342 } else if test == AutoRetry::FailOnRestart {
2343 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
2344 // attempts remaining prior to restart.
2345 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2346 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
2347 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2349 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
2350 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
2351 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
2353 // Ensure the first retry attempt fails, with 1 retry attempt remaining
2354 nodes[0].node.process_pending_htlc_forwards();
2355 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
2357 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
2358 let node_encoded = nodes[0].node.encode();
2359 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
2360 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
2362 let mut events = nodes[0].node.get_and_clear_pending_events();
2363 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
2364 // Make sure we don't retry again.
2365 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2366 assert_eq!(msg_events.len(), 0);
2368 let mut events = nodes[0].node.get_and_clear_pending_events();
2369 assert_eq!(events.len(), 1);
2371 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2372 assert_eq!(payment_hash, *ev_payment_hash);
2373 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2374 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2376 _ => panic!("Unexpected event"),
2378 } else if test == AutoRetry::FailOnRetry {
2379 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2380 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2381 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
2383 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
2384 // fail to find a route.
2385 nodes[0].node.process_pending_htlc_forwards();
2386 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2387 assert_eq!(msg_events.len(), 0);
2389 let mut events = nodes[0].node.get_and_clear_pending_events();
2390 assert_eq!(events.len(), 1);
2392 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2393 assert_eq!(payment_hash, *ev_payment_hash);
2394 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2395 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
2397 _ => panic!("Unexpected event"),
2403 fn auto_retry_partial_failure() {
2404 // Test that we'll retry appropriately on send partial failure and retry partial failure.
2405 let chanmon_cfgs = create_chanmon_cfgs(2);
2406 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2407 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2408 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2410 // Open three channels, the first has plenty of liquidity, the second and third have ~no
2411 // available liquidity, causing any outbound payments routed over it to fail immediately.
2412 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2413 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;
2414 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;
2416 // Marshall data to send the payment
2417 let amt_msat = 10_000_000;
2418 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2419 #[cfg(feature = "std")]
2420 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2421 #[cfg(not(feature = "std"))]
2422 let payment_expiry_secs = 60 * 60;
2423 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2424 invoice_features.set_variable_length_onion_required();
2425 invoice_features.set_payment_secret_required();
2426 invoice_features.set_basic_mpp_optional();
2427 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2428 .with_expiry_time(payment_expiry_secs as u64)
2429 .with_bolt11_features(invoice_features).unwrap();
2431 // Configure the initial send path
2432 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2433 route_params.max_total_routing_fee_msat = None;
2435 let send_route = Route {
2437 Path { hops: vec![RouteHop {
2438 pubkey: nodes[1].node.get_our_node_id(),
2439 node_features: nodes[1].node.node_features(),
2440 short_channel_id: chan_1_id,
2441 channel_features: nodes[1].node.channel_features(),
2442 fee_msat: amt_msat / 2,
2443 cltv_expiry_delta: 100,
2444 maybe_announced_channel: true,
2445 }], blinded_tail: None },
2446 Path { hops: vec![RouteHop {
2447 pubkey: nodes[1].node.get_our_node_id(),
2448 node_features: nodes[1].node.node_features(),
2449 short_channel_id: chan_2_id,
2450 channel_features: nodes[1].node.channel_features(),
2451 fee_msat: amt_msat / 2,
2452 cltv_expiry_delta: 100,
2453 maybe_announced_channel: true,
2454 }], blinded_tail: None },
2456 route_params: Some(route_params.clone()),
2458 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2460 // Configure the retry1 paths
2461 let mut payment_params = route_params.payment_params.clone();
2462 payment_params.previously_failed_channels.push(chan_2_id);
2463 let mut retry_1_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 2);
2464 retry_1_params.max_total_routing_fee_msat = None;
2466 let retry_1_route = Route {
2468 Path { hops: vec![RouteHop {
2469 pubkey: nodes[1].node.get_our_node_id(),
2470 node_features: nodes[1].node.node_features(),
2471 short_channel_id: chan_1_id,
2472 channel_features: nodes[1].node.channel_features(),
2473 fee_msat: amt_msat / 4,
2474 cltv_expiry_delta: 100,
2475 maybe_announced_channel: true,
2476 }], blinded_tail: None },
2477 Path { hops: vec![RouteHop {
2478 pubkey: nodes[1].node.get_our_node_id(),
2479 node_features: nodes[1].node.node_features(),
2480 short_channel_id: chan_3_id,
2481 channel_features: nodes[1].node.channel_features(),
2482 fee_msat: amt_msat / 4,
2483 cltv_expiry_delta: 100,
2484 maybe_announced_channel: true,
2485 }], blinded_tail: None },
2487 route_params: Some(retry_1_params.clone()),
2489 nodes[0].router.expect_find_route(retry_1_params.clone(), Ok(retry_1_route));
2491 // Configure the retry2 path
2492 let mut payment_params = retry_1_params.payment_params.clone();
2493 payment_params.previously_failed_channels.push(chan_3_id);
2494 let mut retry_2_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat / 4);
2495 retry_2_params.max_total_routing_fee_msat = None;
2497 let retry_2_route = Route {
2499 Path { hops: vec![RouteHop {
2500 pubkey: nodes[1].node.get_our_node_id(),
2501 node_features: nodes[1].node.node_features(),
2502 short_channel_id: chan_1_id,
2503 channel_features: nodes[1].node.channel_features(),
2504 fee_msat: amt_msat / 4,
2505 cltv_expiry_delta: 100,
2506 maybe_announced_channel: true,
2507 }], blinded_tail: None },
2509 route_params: Some(retry_2_params.clone()),
2511 nodes[0].router.expect_find_route(retry_2_params, Ok(retry_2_route));
2513 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
2514 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2515 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
2516 let payment_failed_events = nodes[0].node.get_and_clear_pending_events();
2517 assert_eq!(payment_failed_events.len(), 2);
2518 match payment_failed_events[0] {
2519 Event::PaymentPathFailed { .. } => {},
2520 _ => panic!("Unexpected event"),
2522 match payment_failed_events[1] {
2523 Event::PaymentPathFailed { .. } => {},
2524 _ => panic!("Unexpected event"),
2527 // Pass the first part of the payment along the path.
2528 check_added_monitors!(nodes[0], 1); // only one HTLC actually made it out
2529 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2531 // Only one HTLC/channel update actually made it out
2532 assert_eq!(msg_events.len(), 1);
2533 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
2535 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2536 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2537 check_added_monitors!(nodes[1], 1);
2538 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2540 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2541 check_added_monitors!(nodes[0], 1);
2542 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
2544 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2545 check_added_monitors!(nodes[0], 1);
2546 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2548 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2549 check_added_monitors!(nodes[1], 1);
2551 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
2552 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
2553 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
2554 check_added_monitors!(nodes[1], 1);
2555 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2557 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2558 check_added_monitors!(nodes[0], 1);
2560 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2561 check_added_monitors!(nodes[0], 1);
2562 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2564 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2565 check_added_monitors!(nodes[1], 1);
2567 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2568 nodes[1].node.process_pending_htlc_forwards();
2569 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2570 nodes[1].node.claim_funds(payment_preimage);
2571 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2572 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2573 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2575 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2576 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
2577 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2578 check_added_monitors!(nodes[0], 1);
2579 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2581 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2582 check_added_monitors!(nodes[1], 4);
2583 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2585 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2586 check_added_monitors!(nodes[1], 1);
2587 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2589 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2590 check_added_monitors!(nodes[0], 1);
2591 expect_payment_path_successful!(nodes[0]);
2593 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2594 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2595 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2596 check_added_monitors!(nodes[0], 1);
2597 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2599 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2600 check_added_monitors!(nodes[1], 1);
2602 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2603 check_added_monitors!(nodes[1], 1);
2604 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2606 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2607 check_added_monitors!(nodes[0], 1);
2608 let events = nodes[0].node.get_and_clear_pending_events();
2609 assert_eq!(events.len(), 2);
2610 if let Event::PaymentPathSuccessful { .. } = events[0] {} else { panic!(); }
2611 if let Event::PaymentPathSuccessful { .. } = events[1] {} else { panic!(); }
2615 fn auto_retry_zero_attempts_send_error() {
2616 let chanmon_cfgs = create_chanmon_cfgs(2);
2617 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2618 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2619 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2621 // Open a single channel that does not have sufficient liquidity for the payment we want to
2623 let chan_id = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 989_000_000).0.contents.short_channel_id;
2625 // Marshall data to send the payment
2626 let amt_msat = 10_000_000;
2627 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(amt_msat), None);
2628 #[cfg(feature = "std")]
2629 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2630 #[cfg(not(feature = "std"))]
2631 let payment_expiry_secs = 60 * 60;
2632 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2633 invoice_features.set_variable_length_onion_required();
2634 invoice_features.set_payment_secret_required();
2635 invoice_features.set_basic_mpp_optional();
2636 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2637 .with_expiry_time(payment_expiry_secs as u64)
2638 .with_bolt11_features(invoice_features).unwrap();
2639 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2641 // Override the route search to return a route, rather than failing at the route-finding step.
2642 let send_route = Route {
2644 Path { hops: vec![RouteHop {
2645 pubkey: nodes[1].node.get_our_node_id(),
2646 node_features: nodes[1].node.node_features(),
2647 short_channel_id: chan_id,
2648 channel_features: nodes[1].node.channel_features(),
2650 cltv_expiry_delta: 100,
2651 maybe_announced_channel: true,
2652 }], blinded_tail: None },
2654 route_params: Some(route_params.clone()),
2656 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
2658 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2659 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2660 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2661 let events = nodes[0].node.get_and_clear_pending_events();
2662 assert_eq!(events.len(), 2);
2663 if let Event::PaymentPathFailed { .. } = events[0] { } else { panic!(); }
2664 if let Event::PaymentFailed { .. } = events[1] { } else { panic!(); }
2665 check_added_monitors!(nodes[0], 0);
2669 fn fails_paying_after_rejected_by_payee() {
2670 let chanmon_cfgs = create_chanmon_cfgs(2);
2671 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2672 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2673 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2675 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2677 // Marshall data to send the payment
2678 let amt_msat = 20_000;
2679 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2680 #[cfg(feature = "std")]
2681 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2682 #[cfg(not(feature = "std"))]
2683 let payment_expiry_secs = 60 * 60;
2684 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2685 invoice_features.set_variable_length_onion_required();
2686 invoice_features.set_payment_secret_required();
2687 invoice_features.set_basic_mpp_optional();
2688 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2689 .with_expiry_time(payment_expiry_secs as u64)
2690 .with_bolt11_features(invoice_features).unwrap();
2691 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2693 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2694 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2695 check_added_monitors!(nodes[0], 1);
2696 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2697 assert_eq!(events.len(), 1);
2698 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2699 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2700 check_added_monitors!(nodes[1], 0);
2701 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2702 expect_pending_htlcs_forwardable!(nodes[1]);
2703 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2705 nodes[1].node.fail_htlc_backwards(&payment_hash);
2706 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2707 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2711 fn retry_multi_path_single_failed_payment() {
2712 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2713 let chanmon_cfgs = create_chanmon_cfgs(2);
2714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2716 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2718 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2719 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2721 let amt_msat = 100_010_000;
2723 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2724 #[cfg(feature = "std")]
2725 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2726 #[cfg(not(feature = "std"))]
2727 let payment_expiry_secs = 60 * 60;
2728 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2729 invoice_features.set_variable_length_onion_required();
2730 invoice_features.set_payment_secret_required();
2731 invoice_features.set_basic_mpp_optional();
2732 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2733 .with_expiry_time(payment_expiry_secs as u64)
2734 .with_bolt11_features(invoice_features).unwrap();
2735 let mut route_params = RouteParameters::from_payment_params_and_value(
2736 payment_params.clone(), amt_msat);
2737 route_params.max_total_routing_fee_msat = None;
2739 let chans = nodes[0].node.list_usable_channels();
2740 let mut route = Route {
2742 Path { hops: vec![RouteHop {
2743 pubkey: nodes[1].node.get_our_node_id(),
2744 node_features: nodes[1].node.node_features(),
2745 short_channel_id: chans[0].short_channel_id.unwrap(),
2746 channel_features: nodes[1].node.channel_features(),
2748 cltv_expiry_delta: 100,
2749 maybe_announced_channel: true,
2750 }], blinded_tail: None },
2751 Path { hops: vec![RouteHop {
2752 pubkey: nodes[1].node.get_our_node_id(),
2753 node_features: nodes[1].node.node_features(),
2754 short_channel_id: chans[1].short_channel_id.unwrap(),
2755 channel_features: nodes[1].node.channel_features(),
2756 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2757 cltv_expiry_delta: 100,
2758 maybe_announced_channel: true,
2759 }], blinded_tail: None },
2761 route_params: Some(route_params.clone()),
2763 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2764 // On retry, split the payment across both channels.
2765 route.paths[0].hops[0].fee_msat = 50_000_001;
2766 route.paths[1].hops[0].fee_msat = 50_000_000;
2767 let mut pay_params = route.route_params.clone().unwrap().payment_params;
2768 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2770 let mut retry_params = RouteParameters::from_payment_params_and_value(pay_params, 100_000_000);
2771 retry_params.max_total_routing_fee_msat = None;
2772 route.route_params = Some(retry_params.clone());
2773 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2776 let scorer = chanmon_cfgs[0].scorer.read().unwrap();
2777 // The initial send attempt, 2 paths
2778 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2779 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2780 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2781 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2782 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2785 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2786 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2787 let events = nodes[0].node.get_and_clear_pending_events();
2788 assert_eq!(events.len(), 1);
2790 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2791 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2792 short_channel_id: Some(expected_scid), .. } =>
2794 assert_eq!(payment_hash, ev_payment_hash);
2795 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2797 _ => panic!("Unexpected event"),
2799 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2800 assert_eq!(htlc_msgs.len(), 2);
2801 check_added_monitors!(nodes[0], 2);
2805 fn immediate_retry_on_failure() {
2806 // Tests that we can/will retry immediately after a failure
2807 let chanmon_cfgs = create_chanmon_cfgs(2);
2808 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2809 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2810 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2812 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2813 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2815 let amt_msat = 100_000_001;
2816 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2817 #[cfg(feature = "std")]
2818 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2819 #[cfg(not(feature = "std"))]
2820 let payment_expiry_secs = 60 * 60;
2821 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2822 invoice_features.set_variable_length_onion_required();
2823 invoice_features.set_payment_secret_required();
2824 invoice_features.set_basic_mpp_optional();
2825 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2826 .with_expiry_time(payment_expiry_secs as u64)
2827 .with_bolt11_features(invoice_features).unwrap();
2828 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2830 let chans = nodes[0].node.list_usable_channels();
2831 let mut route = Route {
2833 Path { hops: vec![RouteHop {
2834 pubkey: nodes[1].node.get_our_node_id(),
2835 node_features: nodes[1].node.node_features(),
2836 short_channel_id: chans[0].short_channel_id.unwrap(),
2837 channel_features: nodes[1].node.channel_features(),
2838 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2839 cltv_expiry_delta: 100,
2840 maybe_announced_channel: true,
2841 }], blinded_tail: None },
2843 route_params: Some(route_params.clone()),
2845 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2846 // On retry, split the payment across both channels.
2847 route.paths.push(route.paths[0].clone());
2848 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2849 route.paths[0].hops[0].fee_msat = 50_000_000;
2850 route.paths[1].hops[0].fee_msat = 50_000_001;
2851 let mut pay_params = route_params.payment_params.clone();
2852 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2853 let retry_params = RouteParameters::from_payment_params_and_value(pay_params, amt_msat);
2854 route.route_params = Some(retry_params.clone());
2855 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2857 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2858 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2859 let events = nodes[0].node.get_and_clear_pending_events();
2860 assert_eq!(events.len(), 1);
2862 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2863 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2864 short_channel_id: Some(expected_scid), .. } =>
2866 assert_eq!(payment_hash, ev_payment_hash);
2867 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2869 _ => panic!("Unexpected event"),
2871 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2872 assert_eq!(htlc_msgs.len(), 2);
2873 check_added_monitors!(nodes[0], 2);
2877 fn no_extra_retries_on_back_to_back_fail() {
2878 // In a previous release, we had a race where we may exceed the payment retry count if we
2879 // get two failures in a row with the second indicating that all paths had failed (this field,
2880 // `all_paths_failed`, has since been removed).
2881 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2882 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2883 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2884 // pending which we will see later. Thus, when we previously removed the retry tracking map
2885 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2886 // retry entry even though more events for the same payment were still pending. This led to
2887 // us retrying a payment again even though we'd already given up on it.
2889 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2890 // is used to remove the payment retry counter entries instead. This tests for the specific
2891 // excess-retry case while also testing `PaymentFailed` generation.
2893 let chanmon_cfgs = create_chanmon_cfgs(3);
2894 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2895 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2896 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2898 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2899 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2901 let amt_msat = 200_000_000;
2902 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2903 #[cfg(feature = "std")]
2904 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2905 #[cfg(not(feature = "std"))]
2906 let payment_expiry_secs = 60 * 60;
2907 let mut invoice_features = Bolt11InvoiceFeatures::empty();
2908 invoice_features.set_variable_length_onion_required();
2909 invoice_features.set_payment_secret_required();
2910 invoice_features.set_basic_mpp_optional();
2911 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2912 .with_expiry_time(payment_expiry_secs as u64)
2913 .with_bolt11_features(invoice_features).unwrap();
2914 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
2915 route_params.max_total_routing_fee_msat = None;
2917 let mut route = Route {
2919 Path { hops: vec![RouteHop {
2920 pubkey: nodes[1].node.get_our_node_id(),
2921 node_features: nodes[1].node.node_features(),
2922 short_channel_id: chan_1_scid,
2923 channel_features: nodes[1].node.channel_features(),
2924 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2925 cltv_expiry_delta: 100,
2926 maybe_announced_channel: true,
2928 pubkey: nodes[2].node.get_our_node_id(),
2929 node_features: nodes[2].node.node_features(),
2930 short_channel_id: chan_2_scid,
2931 channel_features: nodes[2].node.channel_features(),
2932 fee_msat: 100_000_000,
2933 cltv_expiry_delta: 100,
2934 maybe_announced_channel: true,
2935 }], blinded_tail: None },
2936 Path { hops: vec![RouteHop {
2937 pubkey: nodes[1].node.get_our_node_id(),
2938 node_features: nodes[1].node.node_features(),
2939 short_channel_id: chan_1_scid,
2940 channel_features: nodes[1].node.channel_features(),
2941 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2942 cltv_expiry_delta: 100,
2943 maybe_announced_channel: true,
2945 pubkey: nodes[2].node.get_our_node_id(),
2946 node_features: nodes[2].node.node_features(),
2947 short_channel_id: chan_2_scid,
2948 channel_features: nodes[2].node.channel_features(),
2949 fee_msat: 100_000_000,
2950 cltv_expiry_delta: 100,
2951 maybe_announced_channel: true,
2952 }], blinded_tail: None }
2954 route_params: Some(route_params.clone()),
2956 route.route_params.as_mut().unwrap().max_total_routing_fee_msat = None;
2957 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2958 let mut second_payment_params = route_params.payment_params.clone();
2959 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2960 // On retry, we'll only return one path
2961 route.paths.remove(1);
2962 route.paths[0].hops[1].fee_msat = amt_msat;
2963 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat);
2964 retry_params.max_total_routing_fee_msat = None;
2965 route.route_params = Some(retry_params.clone());
2966 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
2968 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2969 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2970 let htlc_updates = SendEvent::from_node(&nodes[0]);
2971 check_added_monitors!(nodes[0], 1);
2972 assert_eq!(htlc_updates.msgs.len(), 1);
2974 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2975 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2976 check_added_monitors!(nodes[1], 1);
2977 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2979 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2980 check_added_monitors!(nodes[0], 1);
2981 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2983 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2984 check_added_monitors!(nodes[0], 1);
2985 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2987 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2988 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2989 check_added_monitors!(nodes[1], 1);
2990 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2992 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2993 check_added_monitors!(nodes[1], 1);
2994 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2996 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2997 check_added_monitors!(nodes[0], 1);
2999 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3000 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
3001 check_added_monitors!(nodes[0], 1);
3002 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3004 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
3005 check_added_monitors!(nodes[1], 1);
3006 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3008 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
3009 check_added_monitors!(nodes[1], 1);
3010 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3012 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
3013 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
3014 check_added_monitors!(nodes[0], 1);
3016 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
3017 check_added_monitors!(nodes[0], 1);
3018 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3020 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
3021 check_added_monitors!(nodes[1], 1);
3022 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
3023 check_added_monitors!(nodes[1], 1);
3024 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3026 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
3027 check_added_monitors!(nodes[0], 1);
3029 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
3030 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
3033 // Previously, we retried payments in an event consumer, which would retry each
3034 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
3035 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
3036 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
3037 // by adding the `PaymentFailed` event.
3039 // Because we now retry payments as a batch, we simply return a single-path route in the
3040 // second, batched, request, have that fail, ensure the payment was abandoned.
3041 let mut events = nodes[0].node.get_and_clear_pending_events();
3042 assert_eq!(events.len(), 3);
3044 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3045 assert_eq!(payment_hash, ev_payment_hash);
3046 assert_eq!(payment_failed_permanently, false);
3048 _ => panic!("Unexpected event"),
3051 Event::PendingHTLCsForwardable { .. } => {},
3052 _ => panic!("Unexpected event"),
3055 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3056 assert_eq!(payment_hash, ev_payment_hash);
3057 assert_eq!(payment_failed_permanently, false);
3059 _ => panic!("Unexpected event"),
3062 nodes[0].node.process_pending_htlc_forwards();
3063 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3064 check_added_monitors!(nodes[0], 1);
3066 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3067 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3068 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3069 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3070 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
3072 let mut events = nodes[0].node.get_and_clear_pending_events();
3073 assert_eq!(events.len(), 2);
3075 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3076 assert_eq!(payment_hash, ev_payment_hash);
3077 assert_eq!(payment_failed_permanently, false);
3079 _ => panic!("Unexpected event"),
3082 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
3083 assert_eq!(payment_hash, *ev_payment_hash);
3084 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
3085 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
3087 _ => panic!("Unexpected event"),
3092 fn test_simple_partial_retry() {
3093 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
3094 // full amount of the payment, rather than only the missing amount. Here we simply test for
3095 // this by sending a payment with two parts, failing one, and retrying the second. Note that
3096 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
3098 let chanmon_cfgs = create_chanmon_cfgs(3);
3099 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3100 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3101 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3103 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3104 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
3106 let amt_msat = 200_000_000;
3107 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3108 #[cfg(feature = "std")]
3109 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3110 #[cfg(not(feature = "std"))]
3111 let payment_expiry_secs = 60 * 60;
3112 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3113 invoice_features.set_variable_length_onion_required();
3114 invoice_features.set_payment_secret_required();
3115 invoice_features.set_basic_mpp_optional();
3116 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3117 .with_expiry_time(payment_expiry_secs as u64)
3118 .with_bolt11_features(invoice_features).unwrap();
3119 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
3120 route_params.max_total_routing_fee_msat = None;
3122 let mut route = Route {
3124 Path { hops: vec![RouteHop {
3125 pubkey: nodes[1].node.get_our_node_id(),
3126 node_features: nodes[1].node.node_features(),
3127 short_channel_id: chan_1_scid,
3128 channel_features: nodes[1].node.channel_features(),
3129 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
3130 cltv_expiry_delta: 100,
3131 maybe_announced_channel: true,
3133 pubkey: nodes[2].node.get_our_node_id(),
3134 node_features: nodes[2].node.node_features(),
3135 short_channel_id: chan_2_scid,
3136 channel_features: nodes[2].node.channel_features(),
3137 fee_msat: 100_000_000,
3138 cltv_expiry_delta: 100,
3139 maybe_announced_channel: true,
3140 }], blinded_tail: None },
3141 Path { hops: vec![RouteHop {
3142 pubkey: nodes[1].node.get_our_node_id(),
3143 node_features: nodes[1].node.node_features(),
3144 short_channel_id: chan_1_scid,
3145 channel_features: nodes[1].node.channel_features(),
3147 cltv_expiry_delta: 100,
3148 maybe_announced_channel: true,
3150 pubkey: nodes[2].node.get_our_node_id(),
3151 node_features: nodes[2].node.node_features(),
3152 short_channel_id: chan_2_scid,
3153 channel_features: nodes[2].node.channel_features(),
3154 fee_msat: 100_000_000,
3155 cltv_expiry_delta: 100,
3156 maybe_announced_channel: true,
3157 }], blinded_tail: None }
3159 route_params: Some(route_params.clone()),
3162 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3164 let mut second_payment_params = route_params.payment_params.clone();
3165 second_payment_params.previously_failed_channels = vec![chan_2_scid];
3166 // On retry, we'll only be asked for one path (or 100k sats)
3167 route.paths.remove(0);
3168 let mut retry_params = RouteParameters::from_payment_params_and_value(second_payment_params, amt_msat / 2);
3169 retry_params.max_total_routing_fee_msat = None;
3170 route.route_params = Some(retry_params.clone());
3171 nodes[0].router.expect_find_route(retry_params, Ok(route.clone()));
3173 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3174 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
3175 let htlc_updates = SendEvent::from_node(&nodes[0]);
3176 check_added_monitors!(nodes[0], 1);
3177 assert_eq!(htlc_updates.msgs.len(), 1);
3179 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
3180 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
3181 check_added_monitors!(nodes[1], 1);
3182 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3184 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
3185 check_added_monitors!(nodes[0], 1);
3186 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
3188 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
3189 check_added_monitors!(nodes[0], 1);
3190 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3192 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
3193 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
3194 check_added_monitors!(nodes[1], 1);
3195 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3197 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
3198 check_added_monitors!(nodes[1], 1);
3199 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3201 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
3202 check_added_monitors!(nodes[0], 1);
3204 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
3205 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
3206 check_added_monitors!(nodes[0], 1);
3207 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3209 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
3210 check_added_monitors!(nodes[1], 1);
3212 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
3213 check_added_monitors!(nodes[1], 1);
3215 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3217 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
3218 check_added_monitors!(nodes[0], 1);
3220 let mut events = nodes[0].node.get_and_clear_pending_events();
3221 assert_eq!(events.len(), 2);
3223 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
3224 assert_eq!(payment_hash, ev_payment_hash);
3225 assert_eq!(payment_failed_permanently, false);
3227 _ => panic!("Unexpected event"),
3230 Event::PendingHTLCsForwardable { .. } => {},
3231 _ => panic!("Unexpected event"),
3234 nodes[0].node.process_pending_htlc_forwards();
3235 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
3236 check_added_monitors!(nodes[0], 1);
3238 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
3239 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
3241 expect_pending_htlcs_forwardable!(nodes[1]);
3242 check_added_monitors!(nodes[1], 1);
3244 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
3245 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
3246 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
3247 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
3249 expect_pending_htlcs_forwardable!(nodes[2]);
3250 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
3254 #[cfg(feature = "std")]
3255 fn test_threaded_payment_retries() {
3256 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
3257 // a single thread and would happily let multiple threads run retries at the same time. Because
3258 // retries are done by first calculating the amount we need to retry, then dropping the
3259 // relevant lock, then actually sending, we would happily let multiple threads retry the same
3260 // amount at the same time, overpaying our original HTLC!
3261 let chanmon_cfgs = create_chanmon_cfgs(4);
3262 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3263 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3264 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3266 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
3267 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
3268 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
3269 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
3271 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
3272 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
3273 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
3274 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
3276 let amt_msat = 100_000_000;
3277 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
3278 #[cfg(feature = "std")]
3279 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
3280 #[cfg(not(feature = "std"))]
3281 let payment_expiry_secs = 60 * 60;
3282 let mut invoice_features = Bolt11InvoiceFeatures::empty();
3283 invoice_features.set_variable_length_onion_required();
3284 invoice_features.set_payment_secret_required();
3285 invoice_features.set_basic_mpp_optional();
3286 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
3287 .with_expiry_time(payment_expiry_secs as u64)
3288 .with_bolt11_features(invoice_features).unwrap();
3289 let mut route_params = RouteParameters {
3290 payment_params, final_value_msat: amt_msat, max_total_routing_fee_msat: Some(500_000),
3293 let mut route = Route {
3295 Path { hops: vec![RouteHop {
3296 pubkey: nodes[1].node.get_our_node_id(),
3297 node_features: nodes[1].node.node_features(),
3298 short_channel_id: chan_1_scid,
3299 channel_features: nodes[1].node.channel_features(),
3301 cltv_expiry_delta: 100,
3302 maybe_announced_channel: true,
3304 pubkey: nodes[3].node.get_our_node_id(),
3305 node_features: nodes[2].node.node_features(),
3306 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
3307 channel_features: nodes[2].node.channel_features(),
3308 fee_msat: amt_msat / 1000,
3309 cltv_expiry_delta: 100,
3310 maybe_announced_channel: true,
3311 }], blinded_tail: None },
3312 Path { hops: vec![RouteHop {
3313 pubkey: nodes[2].node.get_our_node_id(),
3314 node_features: nodes[2].node.node_features(),
3315 short_channel_id: chan_3_scid,
3316 channel_features: nodes[2].node.channel_features(),
3318 cltv_expiry_delta: 100,
3319 maybe_announced_channel: true,
3321 pubkey: nodes[3].node.get_our_node_id(),
3322 node_features: nodes[3].node.node_features(),
3323 short_channel_id: chan_4_scid,
3324 channel_features: nodes[3].node.channel_features(),
3325 fee_msat: amt_msat - amt_msat / 1000,
3326 cltv_expiry_delta: 100,
3327 maybe_announced_channel: true,
3328 }], blinded_tail: None }
3330 route_params: Some(route_params.clone()),
3332 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3334 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3335 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
3336 check_added_monitors!(nodes[0], 2);
3337 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3338 assert_eq!(send_msg_events.len(), 2);
3339 send_msg_events.retain(|msg|
3340 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
3341 // Drop the commitment update for nodes[2], we can just let that one sit pending
3343 *node_id == nodes[1].node.get_our_node_id()
3344 } else { panic!(); }
3347 // from here on out, the retry `RouteParameters` amount will be amt/1000
3348 route_params.final_value_msat /= 1000;
3349 route.route_params = Some(route_params.clone());
3352 let end_time = Instant::now() + Duration::from_secs(1);
3353 macro_rules! thread_body { () => { {
3354 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
3355 let node_ref = NodePtr::from_node(&nodes[0]);
3358 let node_a = unsafe { &*node_ref.0 };
3359 while Instant::now() < end_time {
3360 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3361 // Ignore if we have any pending events, just always pretend we just got a
3362 // PendingHTLCsForwardable
3363 node_a.node.process_pending_htlc_forwards();
3367 let mut threads = Vec::new();
3368 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
3370 // Back in the main thread, poll pending messages and make sure that we never have more than
3371 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
3372 // there are HTLC messages shoved in while its running. This allows us to test that we never
3373 // generate an additional update_add_htlc until we've fully failed the first.
3374 let mut previously_failed_channels = Vec::new();
3376 assert_eq!(send_msg_events.len(), 1);
3377 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
3378 assert_eq!(send_event.msgs.len(), 1);
3380 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
3381 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
3383 // Note that we only push one route into `expect_find_route` at a time, because that's all
3384 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
3385 // we should still ultimately fail for the same reason - because we're trying to send too
3386 // many HTLCs at once.
3387 let mut new_route_params = route_params.clone();
3388 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
3389 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
3390 new_route_params.max_total_routing_fee_msat.as_mut().map(|m| *m -= 100_000);
3391 route.paths[0].hops[1].short_channel_id += 1;
3392 route.route_params = Some(new_route_params.clone());
3393 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
3395 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3396 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
3397 // The "normal" commitment_signed_dance delivers the final RAA and then calls
3398 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
3399 // This races with our other threads which may generate an add-HTLCs commitment update via
3400 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
3401 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
3402 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
3403 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
3405 let cur_time = Instant::now();
3406 if cur_time > end_time {
3407 for thread in threads.drain(..) { thread.join().unwrap(); }
3410 // Make sure we have some events to handle when we go around...
3411 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
3412 nodes[0].node.process_pending_htlc_forwards();
3413 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3414 check_added_monitors!(nodes[0], 2);
3416 if cur_time > end_time {
3422 fn do_no_missing_sent_on_reload(persist_manager_with_payment: bool, at_midpoint: bool) {
3423 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
3424 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
3425 // it was last persisted.
3426 let chanmon_cfgs = create_chanmon_cfgs(2);
3427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3428 let (persister_a, persister_b, persister_c);
3429 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
3430 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3431 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
3432 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3434 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
3436 let mut nodes_0_serialized = Vec::new();
3437 if !persist_manager_with_payment {
3438 nodes_0_serialized = nodes[0].node.encode();
3441 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3443 if persist_manager_with_payment {
3444 nodes_0_serialized = nodes[0].node.encode();
3447 nodes[1].node.claim_funds(our_payment_preimage);
3448 check_added_monitors!(nodes[1], 1);
3449 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
3452 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3453 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3454 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
3455 check_added_monitors!(nodes[0], 1);
3457 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3458 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
3459 commitment_signed_dance!(nodes[0], nodes[1], htlc_fulfill_updates.commitment_signed, false);
3460 // Ignore the PaymentSent event which is now pending on nodes[0] - if we were to handle it we'd
3461 // be expected to ignore the eventual conflicting PaymentFailed, but by not looking at it we
3462 // expect to get the PaymentSent again later.
3463 check_added_monitors(&nodes[0], 0);
3466 // The ChannelMonitor should always be the latest version, as we're required to persist it
3467 // during the commitment signed handling.
3468 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3469 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
3471 let events = nodes[0].node.get_and_clear_pending_events();
3472 assert_eq!(events.len(), 2);
3473 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
3474 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
3475 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
3476 // the double-claim that would otherwise appear at the end of this test.
3477 nodes[0].node.timer_tick_occurred();
3478 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3479 assert_eq!(as_broadcasted_txn.len(), 1);
3481 // Ensure that, even after some time, if we restart we still include *something* in the current
3482 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
3483 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
3484 // A naive implementation of the fix here would wipe the pending payments set, causing a
3485 // failure event when we restart.
3486 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3488 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3489 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);
3490 let events = nodes[0].node.get_and_clear_pending_events();
3491 assert!(events.is_empty());
3493 // Ensure that we don't generate any further events even after the channel-closing commitment
3494 // transaction is confirmed on-chain.
3495 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
3496 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
3498 let events = nodes[0].node.get_and_clear_pending_events();
3499 assert!(events.is_empty());
3501 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
3502 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);
3503 let events = nodes[0].node.get_and_clear_pending_events();
3504 assert!(events.is_empty());
3505 check_added_monitors(&nodes[0], 1);
3509 fn no_missing_sent_on_midpoint_reload() {
3510 do_no_missing_sent_on_reload(false, true);
3511 do_no_missing_sent_on_reload(true, true);
3515 fn no_missing_sent_on_reload() {
3516 do_no_missing_sent_on_reload(false, false);
3517 do_no_missing_sent_on_reload(true, false);
3520 fn do_claim_from_closed_chan(fail_payment: bool) {
3521 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
3522 // received had been closed between when the HTLC was received and when we went to claim it.
3523 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
3524 // presumably the sender may retry later. Long ago it also reduced total code in the claim
3527 // However, this doesn't make sense if you're trying to do an atomic swap or some other
3528 // protocol that requires atomicity with some other action - if your money got claimed
3529 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
3530 // is an over-optimization - there should be a very, very low likelihood that a channel closes
3531 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
3532 // Since we now have code to handle this anyway we should allow it.
3534 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
3535 // CLTVs on the paths to different value resulting in a different claim deadline.
3536 let chanmon_cfgs = create_chanmon_cfgs(4);
3537 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3538 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3539 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3541 create_announced_chan_between_nodes(&nodes, 0, 1);
3542 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3543 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3544 create_announced_chan_between_nodes(&nodes, 2, 3);
3546 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
3547 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3548 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
3549 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000_000);
3550 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3551 None, nodes[0].node.compute_inflight_htlcs()).unwrap();
3552 // Make sure the route is ordered as the B->D path before C->D
3553 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3554 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
3556 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
3557 // the HTLC is being relayed.
3558 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
3559 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
3560 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
3562 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3563 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
3564 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
3565 check_added_monitors(&nodes[0], 2);
3566 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
3567 send_msgs.sort_by(|a, _| {
3569 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
3570 let node_b_id = nodes[1].node.get_our_node_id();
3571 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
3574 assert_eq!(send_msgs.len(), 2);
3575 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
3576 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
3577 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
3578 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
3580 match receive_event.unwrap() {
3581 Event::PaymentClaimable { claim_deadline, .. } => {
3582 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
3587 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
3589 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
3590 - if fail_payment { 0 } else { 2 });
3592 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
3593 // and expire both immediately, though, by connecting another 4 blocks.
3594 let reason = HTLCDestination::FailedPayment { payment_hash };
3595 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
3596 connect_blocks(&nodes[3], 4);
3597 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
3598 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
3600 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
3601 check_closed_event!(&nodes[1], 1, ClosureReason::HolderForceClosed, false,
3602 [nodes[3].node.get_our_node_id()], 1000000);
3603 check_closed_broadcast(&nodes[1], 1, true);
3604 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3605 assert_eq!(bs_tx.len(), 1);
3607 mine_transaction(&nodes[3], &bs_tx[0]);
3608 check_added_monitors(&nodes[3], 1);
3609 check_closed_broadcast(&nodes[3], 1, true);
3610 check_closed_event!(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false,
3611 [nodes[1].node.get_our_node_id()], 1000000);
3613 nodes[3].node.claim_funds(payment_preimage);
3614 check_added_monitors(&nodes[3], 2);
3615 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
3617 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3618 assert_eq!(ds_tx.len(), 1);
3619 check_spends!(&ds_tx[0], &bs_tx[0]);
3621 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
3622 check_added_monitors(&nodes[1], 1);
3623 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
3625 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
3626 check_added_monitors(&nodes[1], 1);
3627 assert_eq!(bs_claims.len(), 1);
3628 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
3629 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3630 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
3631 } else { panic!(); }
3633 expect_payment_sent!(nodes[0], payment_preimage);
3635 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3636 assert_eq!(ds_claim_msgs.len(), 1);
3637 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3638 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3639 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3640 check_added_monitors(&nodes[2], 1);
3641 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3642 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3644 } else { panic!(); };
3646 assert_eq!(cs_claim_msgs.len(), 1);
3647 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3648 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3649 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3650 } else { panic!(); }
3652 expect_payment_path_successful!(nodes[0]);
3657 fn claim_from_closed_chan() {
3658 do_claim_from_closed_chan(true);
3659 do_claim_from_closed_chan(false);
3663 fn test_custom_tlvs_basic() {
3664 do_test_custom_tlvs(false, false, false);
3665 do_test_custom_tlvs(true, false, false);
3669 fn test_custom_tlvs_explicit_claim() {
3670 // Test that when receiving even custom TLVs the user must explicitly accept in case they
3672 do_test_custom_tlvs(false, true, false);
3673 do_test_custom_tlvs(false, true, true);
3676 fn do_test_custom_tlvs(spontaneous: bool, even_tlvs: bool, known_tlvs: bool) {
3677 let chanmon_cfgs = create_chanmon_cfgs(2);
3678 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3679 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None; 2]);
3680 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3682 create_announced_chan_between_nodes(&nodes, 0, 1);
3684 let amt_msat = 100_000;
3685 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], &nodes[1], amt_msat);
3686 let payment_id = PaymentId(our_payment_hash.0);
3687 let custom_tlvs = vec![
3688 (if even_tlvs { 5482373482 } else { 5482373483 }, vec![1, 2, 3, 4]),
3689 (5482373487, vec![0x42u8; 16]),
3691 let onion_fields = RecipientOnionFields {
3692 payment_secret: if spontaneous { None } else { Some(our_payment_secret) },
3693 payment_metadata: None,
3694 custom_tlvs: custom_tlvs.clone()
3697 nodes[0].node.send_spontaneous_payment(&route, Some(our_payment_preimage), onion_fields, payment_id).unwrap();
3699 nodes[0].node.send_payment_with_route(&route, our_payment_hash, onion_fields, payment_id).unwrap();
3701 check_added_monitors(&nodes[0], 1);
3703 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3704 let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
3705 let mut payment_event = SendEvent::from_event(ev);
3707 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3708 check_added_monitors!(&nodes[1], 0);
3709 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3710 expect_pending_htlcs_forwardable!(nodes[1]);
3712 let events = nodes[1].node.get_and_clear_pending_events();
3713 assert_eq!(events.len(), 1);
3715 Event::PaymentClaimable { ref onion_fields, .. } => {
3716 assert_eq!(onion_fields.clone().unwrap().custom_tlvs().clone(), custom_tlvs);
3718 _ => panic!("Unexpected event"),
3721 match (known_tlvs, even_tlvs) {
3723 nodes[1].node.claim_funds_with_known_custom_tlvs(our_payment_preimage);
3724 let expected_total_fee_msat = pass_claimed_payment_along_route(&nodes[0], &[&[&nodes[1]]], &[0; 1], false, our_payment_preimage);
3725 expect_payment_sent!(&nodes[0], our_payment_preimage, Some(expected_total_fee_msat));
3728 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3731 nodes[1].node.claim_funds(our_payment_preimage);
3732 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3733 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], expected_destinations);
3734 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, our_payment_hash, PaymentFailureReason::RecipientRejected);
3740 fn test_retry_custom_tlvs() {
3741 // Test that custom TLVs are successfully sent on retries
3742 let chanmon_cfgs = create_chanmon_cfgs(3);
3743 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3744 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3745 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3747 create_announced_chan_between_nodes(&nodes, 0, 1);
3748 let (chan_2_update, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 2, 1);
3751 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3753 let amt_msat = 1_000_000;
3754 let (mut route, payment_hash, payment_preimage, payment_secret) =
3755 get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
3757 // Initiate the payment
3758 let payment_id = PaymentId(payment_hash.0);
3759 let mut route_params = route.route_params.clone().unwrap();
3761 let custom_tlvs = vec![((1 << 16) + 1, vec![0x42u8; 16])];
3762 let onion_fields = RecipientOnionFields::secret_only(payment_secret);
3763 let onion_fields = onion_fields.with_custom_tlvs(custom_tlvs.clone()).unwrap();
3765 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
3766 nodes[0].node.send_payment(payment_hash, onion_fields,
3767 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3768 check_added_monitors!(nodes[0], 1); // one monitor per path
3770 // Add the HTLC along the first hop.
3771 let htlc_updates = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
3772 let msgs::CommitmentUpdate { update_add_htlcs, commitment_signed, .. } = htlc_updates;
3773 assert_eq!(update_add_htlcs.len(), 1);
3774 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_htlcs[0]);
3775 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
3777 // Attempt to forward the payment and complete the path's failure.
3778 expect_pending_htlcs_forwardable!(&nodes[1]);
3779 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1],
3780 vec![HTLCDestination::NextHopChannel {
3781 node_id: Some(nodes[2].node.get_our_node_id()),
3782 channel_id: chan_2_id
3784 check_added_monitors!(nodes[1], 1);
3786 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3787 let msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } = htlc_updates;
3788 assert_eq!(update_fail_htlcs.len(), 1);
3789 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3790 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
3792 let mut events = nodes[0].node.get_and_clear_pending_events();
3794 Event::PendingHTLCsForwardable { .. } => {},
3795 _ => panic!("Unexpected event")
3798 expect_payment_failed_conditions_event(events, payment_hash, false,
3799 PaymentFailedConditions::new().mpp_parts_remain());
3801 // Rebalance the channel so the retry of the payment can succeed.
3802 send_payment(&nodes[2], &vec!(&nodes[1])[..], 1_500_000);
3804 // Retry the payment and make sure it succeeds
3805 route_params.payment_params.previously_failed_channels.push(chan_2_update.contents.short_channel_id);
3806 route.route_params = Some(route_params.clone());
3807 nodes[0].router.expect_find_route(route_params, Ok(route));
3808 nodes[0].node.process_pending_htlc_forwards();
3809 check_added_monitors!(nodes[0], 1);
3810 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3811 assert_eq!(events.len(), 1);
3812 let payment_claimable = pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000,
3813 payment_hash, Some(payment_secret), events.pop().unwrap(), true, None).unwrap();
3814 match payment_claimable {
3815 Event::PaymentClaimable { onion_fields, .. } => {
3816 assert_eq!(&onion_fields.unwrap().custom_tlvs()[..], &custom_tlvs[..]);
3818 _ => panic!("Unexpected event"),
3820 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
3824 fn test_custom_tlvs_consistency() {
3825 let even_type_1 = 1 << 16;
3826 let odd_type_1 = (1 << 16)+ 1;
3827 let even_type_2 = (1 << 16) + 2;
3828 let odd_type_2 = (1 << 16) + 3;
3829 let value_1 = || vec![1, 2, 3, 4];
3830 let differing_value_1 = || vec![1, 2, 3, 5];
3831 let value_2 = || vec![42u8; 16];
3833 // Drop missing odd tlvs
3834 do_test_custom_tlvs_consistency(
3835 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3836 vec![(odd_type_1, value_1())],
3837 Some(vec![(odd_type_1, value_1())]),
3839 // Drop non-matching odd tlvs
3840 do_test_custom_tlvs_consistency(
3841 vec![(odd_type_1, value_1()), (odd_type_2, value_2())],
3842 vec![(odd_type_1, differing_value_1()), (odd_type_2, value_2())],
3843 Some(vec![(odd_type_2, value_2())]),
3845 // Fail missing even tlvs
3846 do_test_custom_tlvs_consistency(
3847 vec![(odd_type_1, value_1()), (even_type_2, value_2())],
3848 vec![(odd_type_1, value_1())],
3851 // Fail non-matching even tlvs
3852 do_test_custom_tlvs_consistency(
3853 vec![(even_type_1, value_1()), (odd_type_2, value_2())],
3854 vec![(even_type_1, differing_value_1()), (odd_type_2, value_2())],
3859 fn do_test_custom_tlvs_consistency(first_tlvs: Vec<(u64, Vec<u8>)>, second_tlvs: Vec<(u64, Vec<u8>)>,
3860 expected_receive_tlvs: Option<Vec<(u64, Vec<u8>)>>) {
3862 let chanmon_cfgs = create_chanmon_cfgs(4);
3863 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3864 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3865 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3867 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
3868 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
3869 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
3870 let chan_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
3872 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3873 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
3874 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
3875 assert_eq!(route.paths.len(), 2);
3876 route.paths.sort_by(|path_a, _| {
3877 // Sort the path so that the path through nodes[1] comes first
3878 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
3879 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
3882 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
3883 let payment_id = PaymentId([42; 32]);
3884 let amt_msat = 15_000_000;
3887 let onion_fields = RecipientOnionFields {
3888 payment_secret: Some(our_payment_secret),
3889 payment_metadata: None,
3890 custom_tlvs: first_tlvs
3892 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
3893 onion_fields.clone(), payment_id, &route).unwrap();
3894 let cur_height = nodes[0].best_block_info().1;
3895 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
3896 onion_fields.clone(), amt_msat, cur_height, payment_id,
3897 &None, session_privs[0]).unwrap();
3898 check_added_monitors!(nodes[0], 1);
3901 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3902 assert_eq!(events.len(), 1);
3903 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], amt_msat, our_payment_hash,
3904 Some(our_payment_secret), events.pop().unwrap(), false, None);
3906 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
3909 let onion_fields = RecipientOnionFields {
3910 payment_secret: Some(our_payment_secret),
3911 payment_metadata: None,
3912 custom_tlvs: second_tlvs
3914 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
3915 onion_fields.clone(), amt_msat, cur_height, payment_id, &None, session_privs[1]).unwrap();
3916 check_added_monitors!(nodes[0], 1);
3919 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3920 assert_eq!(events.len(), 1);
3921 let payment_event = SendEvent::from_event(events.pop().unwrap());
3923 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3924 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
3926 expect_pending_htlcs_forwardable!(nodes[2]);
3927 check_added_monitors!(nodes[2], 1);
3929 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
3930 assert_eq!(events.len(), 1);
3931 let payment_event = SendEvent::from_event(events.pop().unwrap());
3933 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
3934 check_added_monitors!(nodes[3], 0);
3935 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
3937 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3938 nodes[3].node.process_pending_htlc_forwards();
3940 if let Some(expected_tlvs) = expected_receive_tlvs {
3941 // Claim and match expected
3942 let events = nodes[3].node.get_and_clear_pending_events();
3943 assert_eq!(events.len(), 1);
3945 Event::PaymentClaimable { ref onion_fields, .. } => {
3946 assert_eq!(onion_fields.clone().unwrap().custom_tlvs, expected_tlvs);
3948 _ => panic!("Unexpected event"),
3951 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]],
3952 false, our_payment_preimage);
3953 expect_payment_sent(&nodes[0], our_payment_preimage, Some(Some(2000)), true, true);
3956 let expected_destinations = vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }];
3957 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], expected_destinations);
3958 check_added_monitors!(nodes[3], 1);
3960 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
3961 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
3962 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
3964 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![
3965 HTLCDestination::NextHopChannel {
3966 node_id: Some(nodes[3].node.get_our_node_id()),
3967 channel_id: chan_2_3.2
3969 check_added_monitors!(nodes[2], 1);
3971 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
3972 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
3973 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
3975 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true,
3976 PaymentFailedConditions::new().mpp_parts_remain());
3980 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3981 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3982 // another results in the HTLC being rejected.
3984 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3985 // first of which we'll deliver and the second of which we'll fail and then re-send with
3986 // modified payment metadata, which will in turn result in it being failed by the recipient.
3987 let chanmon_cfgs = create_chanmon_cfgs(4);
3988 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3990 let new_chain_monitor;
3992 let mut config = test_default_channel_config();
3993 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3994 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3995 let nodes_0_deserialized;
3997 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3999 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
4000 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
4001 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
4002 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
4004 // Pay more than half of each channel's max, requiring MPP
4005 let amt_msat = 750_000_000;
4006 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
4007 let payment_id = PaymentId(payment_hash.0);
4008 let payment_metadata = vec![44, 49, 52, 142];
4010 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
4011 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
4012 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
4014 // Send the MPP payment, delivering the updated commitment state to nodes[1].
4015 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
4016 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata), custom_tlvs: vec![],
4017 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
4018 check_added_monitors!(nodes[0], 2);
4020 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
4021 assert_eq!(send_events.len(), 2);
4022 let first_send = SendEvent::from_event(send_events.pop().unwrap());
4023 let second_send = SendEvent::from_event(send_events.pop().unwrap());
4025 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
4026 (&first_send, &second_send)
4028 (&second_send, &first_send)
4030 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
4031 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
4033 expect_pending_htlcs_forwardable!(nodes[1]);
4034 check_added_monitors(&nodes[1], 1);
4035 let b_forward_ev = SendEvent::from_node(&nodes[1]);
4036 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
4037 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
4039 expect_pending_htlcs_forwardable!(nodes[3]);
4041 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
4042 // will result in nodes[2] failing the HTLC back.
4043 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4044 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
4046 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
4047 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
4049 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
4050 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
4051 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
4053 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
4054 assert_eq!(payment_fail_retryable_evs.len(), 2);
4055 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
4056 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
4058 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
4059 // stored for our payment.
4061 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
4064 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
4065 // the payment state.
4067 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
4068 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
4069 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
4070 persister, new_chain_monitor, nodes_0_deserialized);
4071 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
4072 reconnect_nodes(ReconnectArgs::new(&nodes[1], &nodes[3]));
4074 let mut reconnect_args = ReconnectArgs::new(&nodes[2], &nodes[3]);
4075 reconnect_args.send_channel_ready = (true, true);
4076 reconnect_nodes(reconnect_args);
4078 // Create a new channel between C and D as A will refuse to retry on the existing one because
4080 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
4082 // Now retry the failed HTLC.
4083 nodes[0].node.process_pending_htlc_forwards();
4084 check_added_monitors(&nodes[0], 1);
4085 let as_resend = SendEvent::from_node(&nodes[0]);
4086 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
4087 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
4089 expect_pending_htlcs_forwardable!(nodes[2]);
4090 check_added_monitors(&nodes[2], 1);
4091 let cs_forward = SendEvent::from_node(&nodes[2]);
4092 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
4093 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
4095 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
4096 // the payment metadata was modified, failing only the one modified HTLC and retaining the
4099 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
4100 nodes[3].node.process_pending_htlc_forwards();
4101 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
4102 &[HTLCDestination::FailedPayment {payment_hash}]);
4103 nodes[3].node.process_pending_htlc_forwards();
4105 check_added_monitors(&nodes[3], 1);
4106 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
4108 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
4109 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
4110 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
4111 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
4113 expect_pending_htlcs_forwardable!(nodes[3]);
4114 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
4115 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
4120 fn test_payment_metadata_consistency() {
4121 do_test_payment_metadata_consistency(true, true);
4122 do_test_payment_metadata_consistency(true, false);
4123 do_test_payment_metadata_consistency(false, true);
4124 do_test_payment_metadata_consistency(false, false);
4128 fn test_htlc_forward_considers_anchor_outputs_value() {
4131 // 1) Forwarding nodes don't forward HTLCs that would cause their balance to dip below the
4132 // reserve when considering the value of anchor outputs.
4134 // 2) Recipients of `update_add_htlc` properly reject HTLCs that would cause the initiator's
4135 // balance to dip below the reserve when considering the value of anchor outputs.
4136 let mut config = test_default_channel_config();
4137 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
4138 config.manually_accept_inbound_channels = true;
4139 config.channel_config.forwarding_fee_base_msat = 0;
4140 config.channel_config.forwarding_fee_proportional_millionths = 0;
4142 // Set up a test network of three nodes that replicates a production failure leading to the
4143 // discovery of this bug.
4144 let chanmon_cfgs = create_chanmon_cfgs(3);
4145 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4146 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(config)]);
4147 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4149 const CHAN_AMT: u64 = 1_000_000;
4150 const PUSH_MSAT: u64 = 900_000_000;
4151 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, CHAN_AMT, 500_000_000);
4152 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, CHAN_AMT, PUSH_MSAT);
4154 let channel_reserve_msat = get_holder_selected_channel_reserve_satoshis(CHAN_AMT, &config) * 1000;
4155 let commitment_fee_msat = commit_tx_fee_msat(
4156 *nodes[1].fee_estimator.sat_per_kw.lock().unwrap(), 2, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()
4158 let anchor_outpus_value_msat = ANCHOR_OUTPUT_VALUE_SATOSHI * 2 * 1000;
4159 let sendable_balance_msat = CHAN_AMT * 1000 - PUSH_MSAT - channel_reserve_msat - commitment_fee_msat - anchor_outpus_value_msat;
4160 let channel_details = nodes[1].node.list_channels().into_iter().find(|channel| channel.channel_id == chan_id_2).unwrap();
4161 assert!(sendable_balance_msat >= channel_details.next_outbound_htlc_minimum_msat);
4162 assert!(sendable_balance_msat <= channel_details.next_outbound_htlc_limit_msat);
4164 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], sendable_balance_msat);
4165 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], sendable_balance_msat);
4167 // Send out an HTLC that would cause the forwarding node to dip below its reserve when
4168 // considering the value of anchor outputs.
4169 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(
4170 nodes[0], nodes[2], sendable_balance_msat + anchor_outpus_value_msat
4172 nodes[0].node.send_payment_with_route(
4173 &route, payment_hash, RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
4175 check_added_monitors!(nodes[0], 1);
4177 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4178 assert_eq!(events.len(), 1);
4179 let mut update_add_htlc = if let MessageSendEvent::UpdateHTLCs { updates, .. } = events.pop().unwrap() {
4180 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
4181 check_added_monitors(&nodes[1], 0);
4182 commitment_signed_dance!(nodes[1], nodes[0], &updates.commitment_signed, false);
4183 updates.update_add_htlcs[0].clone()
4185 panic!("Unexpected event");
4188 // The forwarding node should reject forwarding it as expected.
4189 expect_pending_htlcs_forwardable!(nodes[1]);
4190 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1], vec![HTLCDestination::NextHopChannel {
4191 node_id: Some(nodes[2].node.get_our_node_id()),
4192 channel_id: chan_id_2
4194 check_added_monitors(&nodes[1], 1);
4196 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
4197 assert_eq!(events.len(), 1);
4198 if let MessageSendEvent::UpdateHTLCs { updates, .. } = events.pop().unwrap() {
4199 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4200 check_added_monitors(&nodes[0], 0);
4201 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4203 panic!("Unexpected event");
4206 expect_payment_failed!(nodes[0], payment_hash, false);
4208 // Assume that the forwarding node did forward it, and make sure the recipient rejects it as an
4209 // invalid update and closes the channel.
4210 update_add_htlc.channel_id = chan_id_2;
4211 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
4212 check_closed_event(&nodes[2], 1, ClosureReason::ProcessingError {
4213 err: "Remote HTLC add would put them under remote reserve value".to_owned()
4214 }, false, &[nodes[1].node.get_our_node_id()], 1_000_000);
4215 check_closed_broadcast(&nodes[2], 1, true);
4216 check_added_monitors(&nodes[2], 1);
4220 fn peel_payment_onion_custom_tlvs() {
4221 let chanmon_cfgs = create_chanmon_cfgs(2);
4222 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4223 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4224 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4225 create_announced_chan_between_nodes(&nodes, 0, 1);
4226 let secp_ctx = Secp256k1::new();
4228 let amt_msat = 1000;
4229 let payment_params = PaymentParameters::for_keysend(nodes[1].node.get_our_node_id(),
4230 TEST_FINAL_CLTV, false);
4231 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amt_msat);
4232 let route = functional_test_utils::get_route(&nodes[0], &route_params).unwrap();
4233 let mut recipient_onion = RecipientOnionFields::spontaneous_empty()
4234 .with_custom_tlvs(vec![(414141, vec![42; 1200])]).unwrap();
4235 let prng_seed = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
4236 let session_priv = SecretKey::from_slice(&prng_seed[..]).expect("RNG is busted");
4237 let keysend_preimage = PaymentPreimage([42; 32]);
4238 let payment_hash = PaymentHash(Sha256::hash(&keysend_preimage.0).to_byte_array());
4240 let (onion_routing_packet, first_hop_msat, cltv_expiry) = onion_utils::create_payment_onion(
4241 &secp_ctx, &route.paths[0], &session_priv, amt_msat, recipient_onion.clone(),
4242 nodes[0].best_block_info().1, &payment_hash, &Some(keysend_preimage), prng_seed
4245 let update_add = msgs::UpdateAddHTLC {
4246 channel_id: ChannelId([0; 32]),
4248 amount_msat: first_hop_msat,
4251 skimmed_fee_msat: None,
4252 onion_routing_packet,
4253 blinding_point: None,
4255 let peeled_onion = crate::ln::onion_payment::peel_payment_onion(
4256 &update_add, &&chanmon_cfgs[1].keys_manager, &&chanmon_cfgs[1].logger, &secp_ctx,
4257 nodes[1].best_block_info().1, true, false
4259 assert_eq!(peeled_onion.incoming_amt_msat, Some(amt_msat));
4260 match peeled_onion.routing {
4261 PendingHTLCRouting::ReceiveKeysend {
4262 payment_data, payment_metadata, custom_tlvs, ..
4264 #[cfg(not(c_bindings))]
4265 assert_eq!(&custom_tlvs, recipient_onion.custom_tlvs());
4267 assert_eq!(custom_tlvs, recipient_onion.custom_tlvs());
4268 assert!(payment_metadata.is_none());
4269 assert!(payment_data.is_none());