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, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::chain::keysinterface::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
19 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails};
20 use crate::ln::features::InvoiceFeatures;
22 use crate::ln::msgs::ChannelMessageHandler;
23 use crate::ln::outbound_payment::Retry;
24 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
25 use crate::routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RouteParameters};
26 use crate::routing::scoring::ChannelUsage;
27 use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure};
28 use crate::util::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
32 use bitcoin::{Block, BlockHeader, TxMerkleNode};
33 use bitcoin::hashes::Hash;
34 use bitcoin::network::constants::Network;
36 use crate::prelude::*;
38 use crate::ln::functional_test_utils::*;
39 use crate::routing::gossip::NodeId;
40 #[cfg(feature = "std")]
42 crate::util::time::tests::SinceEpoch,
43 std::time::{SystemTime, Instant, Duration}
48 let chanmon_cfgs = create_chanmon_cfgs(4);
49 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
50 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
51 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
53 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
54 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
55 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
56 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
58 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
59 let path = route.paths[0].clone();
60 route.paths.push(path);
61 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
62 route.paths[0][0].short_channel_id = chan_1_id;
63 route.paths[0][1].short_channel_id = chan_3_id;
64 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
65 route.paths[1][0].short_channel_id = chan_2_id;
66 route.paths[1][1].short_channel_id = chan_4_id;
67 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
68 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
73 let chanmon_cfgs = create_chanmon_cfgs(4);
74 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
75 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
76 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
78 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
79 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
80 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
81 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
83 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
85 let amt_msat = 1_000_000;
86 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
87 let path = route.paths[0].clone();
88 route.paths.push(path);
89 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
90 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
91 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
92 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
93 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
94 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
96 // Initiate the MPP payment.
97 let payment_id = PaymentId(payment_hash.0);
98 let mut route_params = RouteParameters {
99 payment_params: route.payment_params.clone().unwrap(),
100 final_value_msat: amt_msat,
103 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
104 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
105 check_added_monitors!(nodes[0], 2); // one monitor per path
106 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
107 assert_eq!(events.len(), 2);
109 // Pass half of the payment along the success path.
110 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
111 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
113 // Add the HTLC along the first hop.
114 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
115 let (update_add, commitment_signed) = match fail_path_msgs_1 {
116 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
117 assert_eq!(update_add_htlcs.len(), 1);
118 assert!(update_fail_htlcs.is_empty());
119 assert!(update_fulfill_htlcs.is_empty());
120 assert!(update_fail_malformed_htlcs.is_empty());
121 assert!(update_fee.is_none());
122 (update_add_htlcs[0].clone(), commitment_signed.clone())
124 _ => panic!("Unexpected event"),
126 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
127 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
129 // Attempt to forward the payment and complete the 2nd path's failure.
130 expect_pending_htlcs_forwardable!(&nodes[2]);
131 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_4_id }]);
132 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
133 assert!(htlc_updates.update_add_htlcs.is_empty());
134 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
135 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
136 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
137 check_added_monitors!(nodes[2], 1);
138 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
139 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
140 let mut events = nodes[0].node.get_and_clear_pending_events();
142 Event::PendingHTLCsForwardable { .. } => {},
143 _ => panic!("Unexpected event")
146 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
148 // Rebalance the channel so the second half of the payment can succeed.
149 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
151 // Retry the second half of the payment and make sure it succeeds.
152 route.paths.remove(0);
153 route_params.final_value_msat = 1_000_000;
154 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
155 nodes[0].router.expect_find_route(route_params, Ok(route));
156 nodes[0].node.process_pending_htlc_forwards();
157 check_added_monitors!(nodes[0], 1);
158 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
159 assert_eq!(events.len(), 1);
160 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
161 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
164 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
165 let chanmon_cfgs = create_chanmon_cfgs(4);
166 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
167 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
168 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
170 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
171 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
172 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
173 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
175 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
176 let path = route.paths[0].clone();
177 route.paths.push(path);
178 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
179 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
180 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
181 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
182 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
183 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
185 // Initiate the MPP payment.
186 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
187 check_added_monitors!(nodes[0], 2); // one monitor per path
188 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
189 assert_eq!(events.len(), 2);
191 // Pass half of the payment along the first path.
192 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
193 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
195 if send_partial_mpp {
196 // Time out the partial MPP
197 for _ in 0..MPP_TIMEOUT_TICKS {
198 nodes[3].node.timer_tick_occurred();
201 // Failed HTLC from node 3 -> 1
202 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
203 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
204 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
205 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
206 check_added_monitors!(nodes[3], 1);
207 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
209 // Failed HTLC from node 1 -> 0
210 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 }]);
211 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
212 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
213 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
214 check_added_monitors!(nodes[1], 1);
215 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
217 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
219 // Pass half of the payment along the second path.
220 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
221 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
223 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
224 for _ in 0..MPP_TIMEOUT_TICKS {
225 nodes[3].node.timer_tick_occurred();
228 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
233 fn mpp_receive_timeout() {
234 do_mpp_receive_timeout(true);
235 do_mpp_receive_timeout(false);
239 fn no_pending_leak_on_initial_send_failure() {
240 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
241 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
242 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
243 // pending payment forever and never time it out.
244 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
245 // try, and then check that no pending payment is being tracked.
246 let chanmon_cfgs = create_chanmon_cfgs(2);
247 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
248 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
249 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
251 create_announced_chan_between_nodes(&nodes, 0, 1);
253 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
255 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
256 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
258 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)),
259 true, APIError::ChannelUnavailable { ref err },
260 assert_eq!(err, "Peer for first hop currently disconnected"));
262 assert!(!nodes[0].node.has_pending_payments());
265 fn do_retry_with_no_persist(confirm_before_reload: bool) {
266 // If we send a pending payment and `send_payment` returns success, we should always either
267 // return a payment failure event or a payment success event, and on failure the payment should
270 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
271 // always persisted asynchronously), the ChannelManager has to reload some payment data from
272 // ChannelMonitor(s) in some cases. This tests that reloading.
274 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
275 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
276 // which has separate codepaths for "commitment transaction already confirmed" and not.
277 let chanmon_cfgs = create_chanmon_cfgs(3);
278 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
279 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
280 let persister: test_utils::TestPersister;
281 let new_chain_monitor: test_utils::TestChainMonitor;
282 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
283 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
285 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
286 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
288 // Serialize the ChannelManager prior to sending payments
289 let nodes_0_serialized = nodes[0].node.encode();
291 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
293 let amt_msat = 1_000_000;
294 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
295 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
296 let route_params = RouteParameters {
297 payment_params: route.payment_params.clone().unwrap(),
298 final_value_msat: amt_msat,
300 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
301 check_added_monitors!(nodes[0], 1);
303 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
304 assert_eq!(events.len(), 1);
305 let payment_event = SendEvent::from_event(events.pop().unwrap());
306 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
308 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
309 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
310 // which would prevent retry.
311 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
312 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
314 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
315 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
316 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
317 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
319 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
321 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
322 if confirm_before_reload {
323 mine_transaction(&nodes[0], &as_commitment_tx);
324 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
327 // The ChannelMonitor should always be the latest version, as we're required to persist it
328 // during the `commitment_signed_dance!()`.
329 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
330 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
332 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
333 // force-close the channel.
334 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
335 assert!(nodes[0].node.list_channels().is_empty());
336 assert!(nodes[0].node.has_pending_payments());
337 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
338 assert_eq!(as_broadcasted_txn.len(), 1);
339 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
341 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
342 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
343 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
345 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
346 // error, as the channel has hit the chain.
347 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
348 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
349 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
350 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
351 assert_eq!(as_err.len(), 1);
353 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
354 assert_eq!(node_id, nodes[1].node.get_our_node_id());
355 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
356 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: 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()) });
357 check_added_monitors!(nodes[1], 1);
358 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
360 _ => panic!("Unexpected event"),
362 check_closed_broadcast!(nodes[1], false);
364 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
365 // we close in a moment.
366 nodes[2].node.claim_funds(payment_preimage_1);
367 check_added_monitors!(nodes[2], 1);
368 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
370 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
371 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
372 check_added_monitors!(nodes[1], 1);
373 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
374 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
376 if confirm_before_reload {
377 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
378 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
381 // Create a new channel on which to retry the payment before we fail the payment via the
382 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
383 // connecting several blocks while creating the channel (implying time has passed).
384 create_announced_chan_between_nodes(&nodes, 0, 1);
385 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
387 mine_transaction(&nodes[1], &as_commitment_tx);
388 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
389 assert_eq!(bs_htlc_claim_txn.len(), 1);
390 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
392 if !confirm_before_reload {
393 mine_transaction(&nodes[0], &as_commitment_tx);
395 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
396 expect_payment_sent!(nodes[0], payment_preimage_1);
397 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
398 let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
399 assert_eq!(as_htlc_timeout_txn.len(), 2);
400 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1]);
401 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
402 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
403 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
404 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
406 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
408 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
409 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
411 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
412 // reloaded) via a route over the new channel, which work without issue and eventually be
413 // received and claimed at the recipient just like any other payment.
414 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
416 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
417 // and not the original fee. We also update node[1]'s relevant config as
418 // do_claim_payment_along_route expects us to never overpay.
420 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
421 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
422 .unwrap().lock().unwrap();
423 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
424 let mut new_config = channel.config();
425 new_config.forwarding_fee_base_msat += 100_000;
426 channel.update_config(&new_config);
427 new_route.paths[0][0].fee_msat += 100_000;
430 // Force expiration of the channel's previous config.
431 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
432 nodes[1].node.timer_tick_occurred();
435 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
436 nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
437 check_added_monitors!(nodes[0], 1);
438 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
439 assert_eq!(events.len(), 1);
440 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
441 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
442 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
446 fn retry_with_no_persist() {
447 do_retry_with_no_persist(true);
448 do_retry_with_no_persist(false);
451 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
452 // Test that an off-chain completed payment is not retryable on restart. This was previously
453 // broken for dust payments, but we test for both dust and non-dust payments.
455 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
457 let chanmon_cfgs = create_chanmon_cfgs(3);
458 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
460 let mut manually_accept_config = test_default_channel_config();
461 manually_accept_config.manually_accept_inbound_channels = true;
463 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
465 let first_persister: test_utils::TestPersister;
466 let first_new_chain_monitor: test_utils::TestChainMonitor;
467 let first_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
468 let second_persister: test_utils::TestPersister;
469 let second_new_chain_monitor: test_utils::TestChainMonitor;
470 let second_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
471 let third_persister: test_utils::TestPersister;
472 let third_new_chain_monitor: test_utils::TestChainMonitor;
473 let third_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
475 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
477 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
478 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
479 confirm_transaction(&nodes[0], &funding_tx);
480 confirm_transaction(&nodes[1], &funding_tx);
481 // Ignore the announcement_signatures messages
482 nodes[0].node.get_and_clear_pending_msg_events();
483 nodes[1].node.get_and_clear_pending_msg_events();
484 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
486 // Serialize the ChannelManager prior to sending payments
487 let mut nodes_0_serialized = nodes[0].node.encode();
489 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
490 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 });
492 // The ChannelMonitor should always be the latest version, as we're required to persist it
493 // during the `commitment_signed_dance!()`.
494 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
496 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);
497 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
499 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
500 // force-close the channel.
501 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
502 assert!(nodes[0].node.list_channels().is_empty());
503 assert!(nodes[0].node.has_pending_payments());
504 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
506 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
507 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
509 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
510 // error, as the channel has hit the chain.
511 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
512 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
513 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
514 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
515 assert_eq!(as_err.len(), 1);
516 let bs_commitment_tx;
518 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
519 assert_eq!(node_id, nodes[1].node.get_our_node_id());
520 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
521 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: 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()) });
522 check_added_monitors!(nodes[1], 1);
523 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
525 _ => panic!("Unexpected event"),
527 check_closed_broadcast!(nodes[1], false);
529 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
530 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
531 // incoming HTLCs with the same payment hash later.
532 nodes[2].node.fail_htlc_backwards(&payment_hash);
533 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
534 check_added_monitors!(nodes[2], 1);
536 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
537 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
538 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
539 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
540 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
542 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
543 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
544 // after the commitment transaction, so always connect the commitment transaction.
545 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
546 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
548 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
549 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
550 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
551 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
552 assert_eq!(as_htlc_timeout.len(), 1);
554 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
555 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
556 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
557 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
560 // Create a new channel on which to retry the payment before we fail the payment via the
561 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
562 // connecting several blocks while creating the channel (implying time has passed).
563 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
564 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
565 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
567 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
568 // confirming, we will fail as it's considered still-pending...
569 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
570 match nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id) {
571 Err(PaymentSendFailure::DuplicatePayment) => {},
572 _ => panic!("Unexpected error")
574 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
576 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
577 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
578 // (which should also still work).
579 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
580 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
581 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
583 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
584 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
585 nodes_0_serialized = nodes[0].node.encode();
587 // After the payment failed, we're free to send it again.
588 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id).is_ok());
589 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
591 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);
592 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
594 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
596 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
597 // the payment is not (spuriously) listed as still pending.
598 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id).is_ok());
599 check_added_monitors!(nodes[0], 1);
600 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
601 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
603 match nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id) {
604 Err(PaymentSendFailure::DuplicatePayment) => {},
605 _ => panic!("Unexpected error")
607 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
609 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
610 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
611 nodes_0_serialized = nodes[0].node.encode();
613 // Check that after reload we can send the payment again (though we shouldn't, since it was
614 // claimed previously).
615 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);
616 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
618 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
620 match nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id) {
621 Err(PaymentSendFailure::DuplicatePayment) => {},
622 _ => panic!("Unexpected error")
624 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
628 fn test_completed_payment_not_retryable_on_reload() {
629 do_test_completed_payment_not_retryable_on_reload(true);
630 do_test_completed_payment_not_retryable_on_reload(false);
634 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
635 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
636 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
637 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
638 // the ChannelMonitor tells it to.
640 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
641 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
642 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
643 let chanmon_cfgs = create_chanmon_cfgs(2);
644 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
645 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
646 let persister: test_utils::TestPersister;
647 let new_chain_monitor: test_utils::TestChainMonitor;
648 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
649 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
651 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
653 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
655 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
656 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
657 check_closed_broadcast!(nodes[0], true);
658 check_added_monitors!(nodes[0], 1);
659 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
661 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
662 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
664 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
665 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
666 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
667 assert_eq!(node_txn.len(), 3);
668 assert_eq!(node_txn[0], node_txn[1]);
669 check_spends!(node_txn[1], funding_tx);
670 check_spends!(node_txn[2], node_txn[1]);
671 let timeout_txn = vec![node_txn[2].clone()];
673 nodes[1].node.claim_funds(payment_preimage);
674 check_added_monitors!(nodes[1], 1);
675 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
677 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
678 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
679 check_closed_broadcast!(nodes[1], true);
680 check_added_monitors!(nodes[1], 1);
681 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
682 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
683 assert_eq!(claim_txn.len(), 1);
684 check_spends!(claim_txn[0], node_txn[1]);
686 header.prev_blockhash = nodes[0].best_block_hash();
687 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
689 if confirm_commitment_tx {
690 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
693 header.prev_blockhash = nodes[0].best_block_hash();
694 let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
697 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
698 connect_block(&nodes[0], &claim_block);
699 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
702 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
703 // returning InProgress. This should cause the claim event to never make its way to the
705 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
706 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
709 connect_blocks(&nodes[0], 1);
711 connect_block(&nodes[0], &claim_block);
714 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
715 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
716 .get_mut(&funding_txo).unwrap().drain().collect();
717 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
718 // If we're testing connection idempotency we may get substantially more.
719 assert!(mon_updates.len() >= 1);
720 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
721 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
723 // If we persist the ChannelManager here, we should get the PaymentSent event after
725 let mut chan_manager_serialized = Vec::new();
726 if !persist_manager_post_event {
727 chan_manager_serialized = nodes[0].node.encode();
730 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
731 // payment sent event.
732 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
733 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
734 for update in mon_updates {
735 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
738 expect_payment_failed!(nodes[0], payment_hash, false);
740 expect_payment_sent!(nodes[0], payment_preimage);
743 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
745 if persist_manager_post_event {
746 chan_manager_serialized = nodes[0].node.encode();
749 // Now reload nodes[0]...
750 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
752 if persist_manager_post_event {
753 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
754 } else if payment_timeout {
755 expect_payment_failed!(nodes[0], payment_hash, false);
757 expect_payment_sent!(nodes[0], payment_preimage);
760 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
761 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
762 // payment events should kick in, leaving us with no pending events here.
763 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
764 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
765 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
769 fn test_dup_htlc_onchain_fails_on_reload() {
770 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
771 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
772 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
773 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
774 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
775 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
779 fn test_fulfill_restart_failure() {
780 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
781 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
782 // again, or fail it, giving us free money.
784 // Of course probably they won't fail it and give us free money, but because we have code to
785 // handle it, we should test the logic for it anyway. We do that here.
786 let chanmon_cfgs = create_chanmon_cfgs(2);
787 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
788 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
789 let persister: test_utils::TestPersister;
790 let new_chain_monitor: test_utils::TestChainMonitor;
791 let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
792 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
794 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
795 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
797 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
798 // pre-fulfill, which we do by serializing it here.
799 let chan_manager_serialized = nodes[1].node.encode();
800 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
802 nodes[1].node.claim_funds(payment_preimage);
803 check_added_monitors!(nodes[1], 1);
804 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
806 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
807 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
808 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
810 // Now reload nodes[1]...
811 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
813 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
814 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
816 nodes[1].node.fail_htlc_backwards(&payment_hash);
817 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
818 check_added_monitors!(nodes[1], 1);
819 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
820 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
821 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
822 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
823 // it had already considered the payment fulfilled, and now they just got free money.
824 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
828 fn get_ldk_payment_preimage() {
829 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
830 let chanmon_cfgs = create_chanmon_cfgs(2);
831 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
832 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
833 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
834 create_announced_chan_between_nodes(&nodes, 0, 1);
836 let amt_msat = 60_000;
837 let expiry_secs = 60 * 60;
838 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
840 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
841 .with_features(nodes[1].node.invoice_features());
842 let scorer = test_utils::TestScorer::new();
843 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
844 let random_seed_bytes = keys_manager.get_secure_random_bytes();
845 let route = get_route(
846 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
847 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
848 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
849 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
850 check_added_monitors!(nodes[0], 1);
852 // Make sure to use `get_payment_preimage`
853 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
854 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
855 assert_eq!(events.len(), 1);
856 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
857 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
861 fn sent_probe_is_probe_of_sending_node() {
862 let chanmon_cfgs = create_chanmon_cfgs(3);
863 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
864 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
865 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
867 create_announced_chan_between_nodes(&nodes, 0, 1);
868 create_announced_chan_between_nodes(&nodes, 1, 2);
870 // First check we refuse to build a single-hop probe
871 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
872 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
874 // Then build an actual two-hop probing path
875 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
877 match nodes[0].node.send_probe(route.paths[0].clone()) {
878 Ok((payment_hash, payment_id)) => {
879 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
880 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
881 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
886 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
887 check_added_monitors!(nodes[0], 1);
891 fn successful_probe_yields_event() {
892 let chanmon_cfgs = create_chanmon_cfgs(3);
893 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
894 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
895 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
897 create_announced_chan_between_nodes(&nodes, 0, 1);
898 create_announced_chan_between_nodes(&nodes, 1, 2);
900 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
902 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
904 // node[0] -- update_add_htlcs -> node[1]
905 check_added_monitors!(nodes[0], 1);
906 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
907 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
908 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
909 check_added_monitors!(nodes[1], 0);
910 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
911 expect_pending_htlcs_forwardable!(nodes[1]);
913 // node[1] -- update_add_htlcs -> node[2]
914 check_added_monitors!(nodes[1], 1);
915 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
916 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
917 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
918 check_added_monitors!(nodes[2], 0);
919 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
921 // node[1] <- update_fail_htlcs -- node[2]
922 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
923 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
924 check_added_monitors!(nodes[1], 0);
925 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
927 // node[0] <- update_fail_htlcs -- node[1]
928 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
929 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
930 check_added_monitors!(nodes[0], 0);
931 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
933 let mut events = nodes[0].node.get_and_clear_pending_events();
934 assert_eq!(events.len(), 1);
935 match events.drain(..).next().unwrap() {
936 crate::util::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
937 assert_eq!(payment_id, ev_pid);
938 assert_eq!(payment_hash, ev_ph);
942 assert!(!nodes[0].node.has_pending_payments());
946 fn failed_probe_yields_event() {
947 let chanmon_cfgs = create_chanmon_cfgs(3);
948 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
949 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
950 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
952 create_announced_chan_between_nodes(&nodes, 0, 1);
953 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
955 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
957 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
959 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
961 // node[0] -- update_add_htlcs -> node[1]
962 check_added_monitors!(nodes[0], 1);
963 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
964 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
965 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
966 check_added_monitors!(nodes[1], 0);
967 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
968 expect_pending_htlcs_forwardable!(nodes[1]);
970 // node[0] <- update_fail_htlcs -- node[1]
971 check_added_monitors!(nodes[1], 1);
972 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
973 // Skip the PendingHTLCsForwardable event
974 let _events = nodes[1].node.get_and_clear_pending_events();
975 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
976 check_added_monitors!(nodes[0], 0);
977 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
979 let mut events = nodes[0].node.get_and_clear_pending_events();
980 assert_eq!(events.len(), 1);
981 match events.drain(..).next().unwrap() {
982 crate::util::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
983 assert_eq!(payment_id, ev_pid);
984 assert_eq!(payment_hash, ev_ph);
988 assert!(!nodes[0].node.has_pending_payments());
992 fn onchain_failed_probe_yields_event() {
993 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
995 let chanmon_cfgs = create_chanmon_cfgs(3);
996 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
997 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
998 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1000 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1001 create_announced_chan_between_nodes(&nodes, 1, 2);
1003 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1005 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1006 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1007 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1009 // node[0] -- update_add_htlcs -> node[1]
1010 check_added_monitors!(nodes[0], 1);
1011 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1012 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1013 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1014 check_added_monitors!(nodes[1], 0);
1015 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1016 expect_pending_htlcs_forwardable!(nodes[1]);
1018 check_added_monitors!(nodes[1], 1);
1019 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1021 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1022 // Node A, which after 6 confirmations should result in a probe failure event.
1023 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1024 confirm_transaction(&nodes[0], &bs_txn[0]);
1025 check_closed_broadcast!(&nodes[0], true);
1026 check_added_monitors!(nodes[0], 1);
1028 let mut events = nodes[0].node.get_and_clear_pending_events();
1029 assert_eq!(events.len(), 2);
1030 let mut found_probe_failed = false;
1031 for event in events.drain(..) {
1033 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1034 assert_eq!(payment_id, ev_pid);
1035 assert_eq!(payment_hash, ev_ph);
1036 found_probe_failed = true;
1038 Event::ChannelClosed { .. } => {},
1042 assert!(found_probe_failed);
1043 assert!(!nodes[0].node.has_pending_payments());
1047 fn claimed_send_payment_idempotent() {
1048 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1049 let chanmon_cfgs = create_chanmon_cfgs(2);
1050 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1051 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1052 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1054 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1056 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1057 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1059 macro_rules! check_send_rejected {
1061 // If we try to resend a new payment with a different payment_hash but with the same
1062 // payment_id, it should be rejected.
1063 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1065 Err(PaymentSendFailure::DuplicatePayment) => {},
1066 _ => panic!("Unexpected send result: {:?}", send_result),
1069 // Further, if we try to send a spontaneous payment with the same payment_id it should
1070 // also be rejected.
1071 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1073 Err(PaymentSendFailure::DuplicatePayment) => {},
1074 _ => panic!("Unexpected send result: {:?}", send_result),
1079 check_send_rejected!();
1081 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1082 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1083 // we must remain just as idempotent as we were before.
1084 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1086 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1087 nodes[0].node.timer_tick_occurred();
1090 check_send_rejected!();
1092 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1093 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1094 // the payment complete. However, they could have called `send_payment` while the event was
1095 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1096 // after the event is handled a duplicate payment should sitll be rejected.
1097 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1098 check_send_rejected!();
1100 // If relatively little time has passed, a duplicate payment should still fail.
1101 nodes[0].node.timer_tick_occurred();
1102 check_send_rejected!();
1104 // However, after some time has passed (at least more than the one timer tick above), a
1105 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1106 // references to the old payment data.
1107 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1108 nodes[0].node.timer_tick_occurred();
1111 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1112 check_added_monitors!(nodes[0], 1);
1113 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1114 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1118 fn abandoned_send_payment_idempotent() {
1119 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1121 let chanmon_cfgs = create_chanmon_cfgs(2);
1122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1124 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1126 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1128 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1129 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1131 macro_rules! check_send_rejected {
1133 // If we try to resend a new payment with a different payment_hash but with the same
1134 // payment_id, it should be rejected.
1135 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1137 Err(PaymentSendFailure::DuplicatePayment) => {},
1138 _ => panic!("Unexpected send result: {:?}", send_result),
1141 // Further, if we try to send a spontaneous payment with the same payment_id it should
1142 // also be rejected.
1143 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1145 Err(PaymentSendFailure::DuplicatePayment) => {},
1146 _ => panic!("Unexpected send result: {:?}", send_result),
1151 check_send_rejected!();
1153 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1154 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1156 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1158 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1159 nodes[0].node.timer_tick_occurred();
1161 check_send_rejected!();
1163 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash);
1165 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1166 // failed payment back.
1167 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1168 check_added_monitors!(nodes[0], 1);
1169 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1170 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1173 #[derive(PartialEq)]
1174 enum InterceptTest {
1181 fn test_trivial_inflight_htlc_tracking(){
1182 // In this test, we test three scenarios:
1183 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1184 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1185 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1186 let chanmon_cfgs = create_chanmon_cfgs(3);
1187 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1188 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1189 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1191 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1192 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1194 // Send and claim the payment. Inflight HTLCs should be empty.
1195 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 500000);
1196 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1197 check_added_monitors!(nodes[0], 1);
1198 pass_along_route(&nodes[0], &[&vec!(&nodes[1], &nodes[2])[..]], 500000, payment_hash, payment_secret);
1199 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], payment_preimage);
1201 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1203 let mut node_0_per_peer_lock;
1204 let mut node_0_peer_state_lock;
1205 let mut node_1_per_peer_lock;
1206 let mut node_1_peer_state_lock;
1207 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1208 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1210 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1211 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1212 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1213 channel_1.get_short_channel_id().unwrap()
1215 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1216 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1217 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1218 channel_2.get_short_channel_id().unwrap()
1221 assert_eq!(chan_1_used_liquidity, None);
1222 assert_eq!(chan_2_used_liquidity, None);
1224 let pending_payments = nodes[0].node.list_recent_payments();
1225 assert_eq!(pending_payments.len(), 1);
1226 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1228 // Remove fulfilled payment
1229 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1230 nodes[0].node.timer_tick_occurred();
1233 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1234 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 500000);
1236 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1238 let mut node_0_per_peer_lock;
1239 let mut node_0_peer_state_lock;
1240 let mut node_1_per_peer_lock;
1241 let mut node_1_peer_state_lock;
1242 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1243 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1245 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1246 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1247 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1248 channel_1.get_short_channel_id().unwrap()
1250 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1251 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1252 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1253 channel_2.get_short_channel_id().unwrap()
1256 // First hop accounts for expected 1000 msat fee
1257 assert_eq!(chan_1_used_liquidity, Some(501000));
1258 assert_eq!(chan_2_used_liquidity, Some(500000));
1260 let pending_payments = nodes[0].node.list_recent_payments();
1261 assert_eq!(pending_payments.len(), 1);
1262 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1264 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1265 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1267 // Remove fulfilled payment
1268 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1269 nodes[0].node.timer_tick_occurred();
1273 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1275 let mut node_0_per_peer_lock;
1276 let mut node_0_peer_state_lock;
1277 let mut node_1_per_peer_lock;
1278 let mut node_1_peer_state_lock;
1279 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1280 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1282 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1283 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1284 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1285 channel_1.get_short_channel_id().unwrap()
1287 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1288 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1289 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1290 channel_2.get_short_channel_id().unwrap()
1293 assert_eq!(chan_1_used_liquidity, None);
1294 assert_eq!(chan_2_used_liquidity, None);
1297 let pending_payments = nodes[0].node.list_recent_payments();
1298 assert_eq!(pending_payments.len(), 0);
1302 fn test_holding_cell_inflight_htlcs() {
1303 let chanmon_cfgs = create_chanmon_cfgs(2);
1304 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1305 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1306 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1307 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1309 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1310 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1312 // Queue up two payments - one will be delivered right away, one immediately goes into the
1313 // holding cell as nodes[0] is AwaitingRAA.
1315 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1316 check_added_monitors!(nodes[0], 1);
1317 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1318 check_added_monitors!(nodes[0], 0);
1321 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1324 let mut node_0_per_peer_lock;
1325 let mut node_0_peer_state_lock;
1326 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1328 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1329 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1330 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1331 channel.get_short_channel_id().unwrap()
1334 assert_eq!(used_liquidity, Some(2000000));
1337 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1338 nodes[0].node.get_and_clear_pending_msg_events();
1342 fn intercepted_payment() {
1343 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1344 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1345 // payment or (b) fail the payment.
1346 do_test_intercepted_payment(InterceptTest::Forward);
1347 do_test_intercepted_payment(InterceptTest::Fail);
1348 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1349 do_test_intercepted_payment(InterceptTest::Timeout);
1352 fn do_test_intercepted_payment(test: InterceptTest) {
1353 let chanmon_cfgs = create_chanmon_cfgs(3);
1354 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1356 let mut zero_conf_chan_config = test_default_channel_config();
1357 zero_conf_chan_config.manually_accept_inbound_channels = true;
1358 let mut intercept_forwards_config = test_default_channel_config();
1359 intercept_forwards_config.accept_intercept_htlcs = true;
1360 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1362 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1363 let scorer = test_utils::TestScorer::new();
1364 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1366 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1368 let amt_msat = 100_000;
1369 let intercept_scid = nodes[1].node.get_intercept_scid();
1370 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1371 .with_route_hints(vec![
1372 RouteHint(vec![RouteHintHop {
1373 src_node_id: nodes[1].node.get_our_node_id(),
1374 short_channel_id: intercept_scid,
1377 proportional_millionths: 0,
1379 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1380 htlc_minimum_msat: None,
1381 htlc_maximum_msat: None,
1384 .with_features(nodes[2].node.invoice_features());
1385 let route_params = RouteParameters {
1387 final_value_msat: amt_msat,
1389 let route = get_route(
1390 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1391 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1392 route_params.payment_params.final_cltv_expiry_delta, nodes[0].logger, &scorer,
1396 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1397 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1398 let payment_event = {
1400 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1401 assert_eq!(added_monitors.len(), 1);
1402 added_monitors.clear();
1404 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1405 assert_eq!(events.len(), 1);
1406 SendEvent::from_event(events.remove(0))
1408 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1409 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1411 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1412 let events = nodes[1].node.get_and_clear_pending_events();
1413 assert_eq!(events.len(), 1);
1414 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1415 crate::util::events::Event::HTLCIntercepted {
1416 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1418 assert_eq!(pmt_hash, payment_hash);
1419 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1420 assert_eq!(short_channel_id, intercept_scid);
1421 (intercept_id, expected_outbound_amount_msat)
1426 // Check for unknown channel id error.
1427 let unknown_chan_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &[42; 32], nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1428 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1430 if test == InterceptTest::Fail {
1431 // Ensure we can fail the intercepted payment back.
1432 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1433 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1434 nodes[1].node.process_pending_htlc_forwards();
1435 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1436 check_added_monitors!(&nodes[1], 1);
1437 assert!(update_fail.update_fail_htlcs.len() == 1);
1438 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1439 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1440 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1442 // Ensure the payment fails with the expected error.
1443 let fail_conditions = PaymentFailedConditions::new()
1444 .blamed_scid(intercept_scid)
1445 .blamed_chan_closed(true)
1446 .expected_htlc_error_data(0x4000 | 10, &[]);
1447 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1448 } else if test == InterceptTest::Forward {
1449 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1450 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1451 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();
1452 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1453 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1455 // Open the just-in-time channel so the payment can then be forwarded.
1456 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1458 // Finally, forward the intercepted payment through and claim it.
1459 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1460 expect_pending_htlcs_forwardable!(nodes[1]);
1462 let payment_event = {
1464 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1465 assert_eq!(added_monitors.len(), 1);
1466 added_monitors.clear();
1468 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1469 assert_eq!(events.len(), 1);
1470 SendEvent::from_event(events.remove(0))
1472 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1473 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1474 expect_pending_htlcs_forwardable!(nodes[2]);
1476 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1477 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1478 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1479 let events = nodes[0].node.get_and_clear_pending_events();
1480 assert_eq!(events.len(), 2);
1482 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1483 assert_eq!(payment_preimage, *ev_preimage);
1484 assert_eq!(payment_hash, *ev_hash);
1485 assert_eq!(fee_paid_msat, &Some(1000));
1487 _ => panic!("Unexpected event")
1490 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1491 assert_eq!(hash, Some(payment_hash));
1493 _ => panic!("Unexpected event")
1495 } else if test == InterceptTest::Timeout {
1496 let mut block = Block {
1497 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1500 connect_block(&nodes[0], &block);
1501 connect_block(&nodes[1], &block);
1502 for _ in 0..TEST_FINAL_CLTV {
1503 block.header.prev_blockhash = block.block_hash();
1504 connect_block(&nodes[0], &block);
1505 connect_block(&nodes[1], &block);
1507 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1508 check_added_monitors!(nodes[1], 1);
1509 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1510 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1511 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1512 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1513 assert!(htlc_timeout_updates.update_fee.is_none());
1515 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1516 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1517 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1519 // Check for unknown intercept id error.
1520 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1521 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();
1522 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1523 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1524 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1528 #[derive(PartialEq)]
1539 fn automatic_retries() {
1540 do_automatic_retries(AutoRetry::Success);
1541 do_automatic_retries(AutoRetry::Spontaneous);
1542 do_automatic_retries(AutoRetry::FailAttempts);
1543 do_automatic_retries(AutoRetry::FailTimeout);
1544 do_automatic_retries(AutoRetry::FailOnRestart);
1545 do_automatic_retries(AutoRetry::FailOnRetry);
1547 fn do_automatic_retries(test: AutoRetry) {
1548 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1550 let chanmon_cfgs = create_chanmon_cfgs(3);
1551 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1552 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1555 let new_chain_monitor;
1556 let node_0_deserialized;
1558 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1559 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1560 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1562 // Marshall data to send the payment
1563 #[cfg(feature = "std")]
1564 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1565 #[cfg(not(feature = "std"))]
1566 let payment_expiry_secs = 60 * 60;
1567 let amt_msat = 1000;
1568 let mut invoice_features = InvoiceFeatures::empty();
1569 invoice_features.set_variable_length_onion_required();
1570 invoice_features.set_payment_secret_required();
1571 invoice_features.set_basic_mpp_optional();
1572 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1573 .with_expiry_time(payment_expiry_secs as u64)
1574 .with_features(invoice_features);
1575 let route_params = RouteParameters {
1577 final_value_msat: amt_msat,
1579 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1581 macro_rules! pass_failed_attempt_with_retry_along_path {
1582 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1583 // Send a payment attempt that fails due to lack of liquidity on the second hop
1584 check_added_monitors!(nodes[0], 1);
1585 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1586 let mut update_add = update_0.update_add_htlcs[0].clone();
1587 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1588 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1589 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1590 nodes[1].node.process_pending_htlc_forwards();
1591 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1592 vec![HTLCDestination::NextHopChannel {
1593 node_id: Some(nodes[2].node.get_our_node_id()),
1594 channel_id: $failing_channel_id,
1596 nodes[1].node.process_pending_htlc_forwards();
1597 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1598 check_added_monitors!(&nodes[1], 1);
1599 assert!(update_1.update_fail_htlcs.len() == 1);
1600 let fail_msg = update_1.update_fail_htlcs[0].clone();
1601 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1602 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1604 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1605 let mut events = nodes[0].node.get_and_clear_pending_events();
1606 assert_eq!(events.len(), 2);
1608 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1609 assert_eq!(payment_hash, ev_payment_hash);
1610 assert_eq!(payment_failed_permanently, false);
1612 _ => panic!("Unexpected event"),
1614 if $expect_pending_htlcs_forwardable {
1616 Event::PendingHTLCsForwardable { .. } => {},
1617 _ => panic!("Unexpected event"),
1621 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1622 assert_eq!(payment_hash, ev_payment_hash);
1624 _ => panic!("Unexpected event"),
1630 if test == AutoRetry::Success {
1631 // Test that we can succeed on the first retry.
1632 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1633 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1635 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1636 // attempt, since the initial second hop channel will be excluded from pathfinding
1637 create_announced_chan_between_nodes(&nodes, 1, 2);
1639 // We retry payments in `process_pending_htlc_forwards`
1640 nodes[0].node.process_pending_htlc_forwards();
1641 check_added_monitors!(nodes[0], 1);
1642 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1643 assert_eq!(msg_events.len(), 1);
1644 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1645 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1646 } else if test == AutoRetry::Spontaneous {
1647 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1648 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1650 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1651 // attempt, since the initial second hop channel will be excluded from pathfinding
1652 create_announced_chan_between_nodes(&nodes, 1, 2);
1654 // We retry payments in `process_pending_htlc_forwards`
1655 nodes[0].node.process_pending_htlc_forwards();
1656 check_added_monitors!(nodes[0], 1);
1657 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1658 assert_eq!(msg_events.len(), 1);
1659 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1660 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1661 } else if test == AutoRetry::FailAttempts {
1662 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1663 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1664 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1666 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1667 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1668 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1670 // We retry payments in `process_pending_htlc_forwards`
1671 nodes[0].node.process_pending_htlc_forwards();
1672 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1674 // Ensure we won't retry a second time.
1675 nodes[0].node.process_pending_htlc_forwards();
1676 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1677 assert_eq!(msg_events.len(), 0);
1678 } else if test == AutoRetry::FailTimeout {
1679 #[cfg(not(feature = "no-std"))] {
1680 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1681 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
1682 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1684 // Advance the time so the second attempt fails due to timeout.
1685 SinceEpoch::advance(Duration::from_secs(61));
1687 // Make sure we don't retry again.
1688 nodes[0].node.process_pending_htlc_forwards();
1689 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1690 assert_eq!(msg_events.len(), 0);
1692 let mut events = nodes[0].node.get_and_clear_pending_events();
1693 assert_eq!(events.len(), 1);
1695 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1696 assert_eq!(payment_hash, *ev_payment_hash);
1697 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1699 _ => panic!("Unexpected event"),
1702 } else if test == AutoRetry::FailOnRestart {
1703 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1704 // attempts remaining prior to restart.
1705 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1706 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1708 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1709 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1710 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1712 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1713 nodes[0].node.process_pending_htlc_forwards();
1714 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1716 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1717 let node_encoded = nodes[0].node.encode();
1718 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1719 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1721 let mut events = nodes[0].node.get_and_clear_pending_events();
1722 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
1723 // Make sure we don't retry again.
1724 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1725 assert_eq!(msg_events.len(), 0);
1727 let mut events = nodes[0].node.get_and_clear_pending_events();
1728 assert_eq!(events.len(), 1);
1730 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1731 assert_eq!(payment_hash, *ev_payment_hash);
1732 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1734 _ => panic!("Unexpected event"),
1736 } else if test == AutoRetry::FailOnRetry {
1737 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1738 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1740 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1741 // fail to find a route.
1742 nodes[0].node.process_pending_htlc_forwards();
1743 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1744 assert_eq!(msg_events.len(), 0);
1746 let mut events = nodes[0].node.get_and_clear_pending_events();
1747 assert_eq!(events.len(), 1);
1749 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1750 assert_eq!(payment_hash, *ev_payment_hash);
1751 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1753 _ => panic!("Unexpected event"),
1759 fn auto_retry_partial_failure() {
1760 // Test that we'll retry appropriately on send partial failure and retry partial failure.
1761 let chanmon_cfgs = create_chanmon_cfgs(2);
1762 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1763 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1764 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1766 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1767 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1768 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1770 // Marshall data to send the payment
1771 let amt_msat = 20_000;
1772 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1773 #[cfg(feature = "std")]
1774 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1775 #[cfg(not(feature = "std"))]
1776 let payment_expiry_secs = 60 * 60;
1777 let mut invoice_features = InvoiceFeatures::empty();
1778 invoice_features.set_variable_length_onion_required();
1779 invoice_features.set_payment_secret_required();
1780 invoice_features.set_basic_mpp_optional();
1781 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1782 .with_expiry_time(payment_expiry_secs as u64)
1783 .with_features(invoice_features);
1784 let route_params = RouteParameters {
1786 final_value_msat: amt_msat,
1789 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1790 // second (for the initial send path2 over chan_2) fails.
1791 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1792 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1793 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1794 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1795 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1796 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1797 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1799 // Configure the initial send, retry1 and retry2's paths.
1800 let send_route = Route {
1803 pubkey: nodes[1].node.get_our_node_id(),
1804 node_features: nodes[1].node.node_features(),
1805 short_channel_id: chan_1_id,
1806 channel_features: nodes[1].node.channel_features(),
1807 fee_msat: amt_msat / 2,
1808 cltv_expiry_delta: 100,
1811 pubkey: nodes[1].node.get_our_node_id(),
1812 node_features: nodes[1].node.node_features(),
1813 short_channel_id: chan_2_id,
1814 channel_features: nodes[1].node.channel_features(),
1815 fee_msat: amt_msat / 2,
1816 cltv_expiry_delta: 100,
1819 payment_params: Some(route_params.payment_params.clone()),
1821 let retry_1_route = Route {
1824 pubkey: nodes[1].node.get_our_node_id(),
1825 node_features: nodes[1].node.node_features(),
1826 short_channel_id: chan_1_id,
1827 channel_features: nodes[1].node.channel_features(),
1828 fee_msat: amt_msat / 4,
1829 cltv_expiry_delta: 100,
1832 pubkey: nodes[1].node.get_our_node_id(),
1833 node_features: nodes[1].node.node_features(),
1834 short_channel_id: chan_3_id,
1835 channel_features: nodes[1].node.channel_features(),
1836 fee_msat: amt_msat / 4,
1837 cltv_expiry_delta: 100,
1840 payment_params: Some(route_params.payment_params.clone()),
1842 let retry_2_route = Route {
1845 pubkey: nodes[1].node.get_our_node_id(),
1846 node_features: nodes[1].node.node_features(),
1847 short_channel_id: chan_1_id,
1848 channel_features: nodes[1].node.channel_features(),
1849 fee_msat: amt_msat / 4,
1850 cltv_expiry_delta: 100,
1853 payment_params: Some(route_params.payment_params.clone()),
1855 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1856 let mut payment_params = route_params.payment_params.clone();
1857 payment_params.previously_failed_channels.push(chan_2_id);
1858 nodes[0].router.expect_find_route(RouteParameters {
1859 payment_params, final_value_msat: amt_msat / 2,
1860 }, Ok(retry_1_route));
1861 let mut payment_params = route_params.payment_params.clone();
1862 payment_params.previously_failed_channels.push(chan_3_id);
1863 nodes[0].router.expect_find_route(RouteParameters {
1864 payment_params, final_value_msat: amt_msat / 4,
1865 }, Ok(retry_2_route));
1867 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1868 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1869 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1870 assert_eq!(closed_chan_events.len(), 4);
1871 match closed_chan_events[0] {
1872 Event::ChannelClosed { .. } => {},
1873 _ => panic!("Unexpected event"),
1875 match closed_chan_events[1] {
1876 Event::PaymentPathFailed { .. } => {},
1877 _ => panic!("Unexpected event"),
1879 match closed_chan_events[2] {
1880 Event::ChannelClosed { .. } => {},
1881 _ => panic!("Unexpected event"),
1883 match closed_chan_events[3] {
1884 Event::PaymentPathFailed { .. } => {},
1885 _ => panic!("Unexpected event"),
1888 // Pass the first part of the payment along the path.
1889 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1890 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1892 // First message is the first update_add, remaining messages are broadcasting channel updates and
1893 // errors for the permfailed channels
1894 assert_eq!(msg_events.len(), 5);
1895 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1897 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1898 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1899 check_added_monitors!(nodes[1], 1);
1900 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1902 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1903 check_added_monitors!(nodes[0], 1);
1904 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1906 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1907 check_added_monitors!(nodes[0], 1);
1908 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1910 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1911 check_added_monitors!(nodes[1], 1);
1913 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1914 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1915 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1916 check_added_monitors!(nodes[1], 1);
1917 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1919 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1920 check_added_monitors!(nodes[0], 1);
1922 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
1923 check_added_monitors!(nodes[0], 1);
1924 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1926 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1927 check_added_monitors!(nodes[1], 1);
1929 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1930 nodes[1].node.process_pending_htlc_forwards();
1931 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
1932 nodes[1].node.claim_funds(payment_preimage);
1933 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
1934 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1935 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
1937 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
1938 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
1939 check_added_monitors!(nodes[0], 1);
1940 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1942 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1943 check_added_monitors!(nodes[1], 4);
1944 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1946 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1947 check_added_monitors!(nodes[1], 1);
1948 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1950 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1951 check_added_monitors!(nodes[0], 1);
1953 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
1954 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
1955 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
1956 check_added_monitors!(nodes[0], 1);
1957 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1959 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
1960 check_added_monitors!(nodes[1], 1);
1962 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1963 check_added_monitors!(nodes[1], 1);
1964 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1966 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1967 check_added_monitors!(nodes[0], 1);
1968 expect_payment_sent!(nodes[0], payment_preimage);
1972 fn auto_retry_zero_attempts_send_error() {
1973 let chanmon_cfgs = create_chanmon_cfgs(2);
1974 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1975 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1976 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1978 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1979 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1981 // Marshall data to send the payment
1982 let amt_msat = 20_000;
1983 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1984 #[cfg(feature = "std")]
1985 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1986 #[cfg(not(feature = "std"))]
1987 let payment_expiry_secs = 60 * 60;
1988 let mut invoice_features = InvoiceFeatures::empty();
1989 invoice_features.set_variable_length_onion_required();
1990 invoice_features.set_payment_secret_required();
1991 invoice_features.set_basic_mpp_optional();
1992 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1993 .with_expiry_time(payment_expiry_secs as u64)
1994 .with_features(invoice_features);
1995 let route_params = RouteParameters {
1997 final_value_msat: amt_msat,
2000 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2001 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2002 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2003 let events = nodes[0].node.get_and_clear_pending_events();
2004 assert_eq!(events.len(), 3);
2005 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2006 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2007 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2008 check_added_monitors!(nodes[0], 2);
2012 fn fails_paying_after_rejected_by_payee() {
2013 let chanmon_cfgs = create_chanmon_cfgs(2);
2014 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2015 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2016 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2018 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2020 // Marshall data to send the payment
2021 let amt_msat = 20_000;
2022 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2023 #[cfg(feature = "std")]
2024 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2025 #[cfg(not(feature = "std"))]
2026 let payment_expiry_secs = 60 * 60;
2027 let mut invoice_features = InvoiceFeatures::empty();
2028 invoice_features.set_variable_length_onion_required();
2029 invoice_features.set_payment_secret_required();
2030 invoice_features.set_basic_mpp_optional();
2031 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2032 .with_expiry_time(payment_expiry_secs as u64)
2033 .with_features(invoice_features);
2034 let route_params = RouteParameters {
2036 final_value_msat: amt_msat,
2039 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2040 check_added_monitors!(nodes[0], 1);
2041 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2042 assert_eq!(events.len(), 1);
2043 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2044 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2045 check_added_monitors!(nodes[1], 0);
2046 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2047 expect_pending_htlcs_forwardable!(nodes[1]);
2048 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2050 nodes[1].node.fail_htlc_backwards(&payment_hash);
2051 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2052 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash);
2056 fn retry_multi_path_single_failed_payment() {
2057 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2058 let chanmon_cfgs = create_chanmon_cfgs(2);
2059 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2060 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2061 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2063 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2064 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2066 let amt_msat = 100_010_000;
2068 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2069 #[cfg(feature = "std")]
2070 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2071 #[cfg(not(feature = "std"))]
2072 let payment_expiry_secs = 60 * 60;
2073 let mut invoice_features = InvoiceFeatures::empty();
2074 invoice_features.set_variable_length_onion_required();
2075 invoice_features.set_payment_secret_required();
2076 invoice_features.set_basic_mpp_optional();
2077 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2078 .with_expiry_time(payment_expiry_secs as u64)
2079 .with_features(invoice_features);
2080 let route_params = RouteParameters {
2081 payment_params: payment_params.clone(),
2082 final_value_msat: amt_msat,
2085 let chans = nodes[0].node.list_usable_channels();
2086 let mut route = Route {
2089 pubkey: nodes[1].node.get_our_node_id(),
2090 node_features: nodes[1].node.node_features(),
2091 short_channel_id: chans[0].short_channel_id.unwrap(),
2092 channel_features: nodes[1].node.channel_features(),
2094 cltv_expiry_delta: 100,
2097 pubkey: nodes[1].node.get_our_node_id(),
2098 node_features: nodes[1].node.node_features(),
2099 short_channel_id: chans[1].short_channel_id.unwrap(),
2100 channel_features: nodes[1].node.channel_features(),
2101 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2102 cltv_expiry_delta: 100,
2105 payment_params: Some(payment_params),
2107 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2108 // On retry, split the payment across both channels.
2109 route.paths[0][0].fee_msat = 50_000_001;
2110 route.paths[1][0].fee_msat = 50_000_000;
2111 let mut pay_params = route.payment_params.clone().unwrap();
2112 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2113 nodes[0].router.expect_find_route(RouteParameters {
2114 payment_params: pay_params,
2115 // Note that the second request here requests the amount we originally failed to send,
2116 // not the amount remaining on the full payment, which should be changed.
2117 final_value_msat: 100_000_001,
2118 }, Ok(route.clone()));
2121 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2122 // The initial send attempt, 2 paths
2123 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2124 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2125 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2126 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2127 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2130 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2131 let events = nodes[0].node.get_and_clear_pending_events();
2132 assert_eq!(events.len(), 1);
2134 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2135 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2136 short_channel_id: Some(expected_scid), .. } =>
2138 assert_eq!(payment_hash, ev_payment_hash);
2139 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2140 assert!(err_msg.contains("max HTLC"));
2142 _ => panic!("Unexpected event"),
2144 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2145 assert_eq!(htlc_msgs.len(), 2);
2146 check_added_monitors!(nodes[0], 2);
2150 fn immediate_retry_on_failure() {
2151 // Tests that we can/will retry immediately after a failure
2152 let chanmon_cfgs = create_chanmon_cfgs(2);
2153 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2154 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2155 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2157 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2158 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2160 let amt_msat = 100_000_001;
2161 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2162 #[cfg(feature = "std")]
2163 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2164 #[cfg(not(feature = "std"))]
2165 let payment_expiry_secs = 60 * 60;
2166 let mut invoice_features = InvoiceFeatures::empty();
2167 invoice_features.set_variable_length_onion_required();
2168 invoice_features.set_payment_secret_required();
2169 invoice_features.set_basic_mpp_optional();
2170 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2171 .with_expiry_time(payment_expiry_secs as u64)
2172 .with_features(invoice_features);
2173 let route_params = RouteParameters {
2175 final_value_msat: amt_msat,
2178 let chans = nodes[0].node.list_usable_channels();
2179 let mut route = Route {
2182 pubkey: nodes[1].node.get_our_node_id(),
2183 node_features: nodes[1].node.node_features(),
2184 short_channel_id: chans[0].short_channel_id.unwrap(),
2185 channel_features: nodes[1].node.channel_features(),
2186 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2187 cltv_expiry_delta: 100,
2190 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2192 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2193 // On retry, split the payment across both channels.
2194 route.paths.push(route.paths[0].clone());
2195 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2196 route.paths[0][0].fee_msat = 50_000_000;
2197 route.paths[1][0].fee_msat = 50_000_001;
2198 let mut pay_params = route_params.payment_params.clone();
2199 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2200 nodes[0].router.expect_find_route(RouteParameters {
2201 payment_params: pay_params, final_value_msat: amt_msat,
2202 }, Ok(route.clone()));
2204 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2205 let events = nodes[0].node.get_and_clear_pending_events();
2206 assert_eq!(events.len(), 1);
2208 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2209 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2210 short_channel_id: Some(expected_scid), .. } =>
2212 assert_eq!(payment_hash, ev_payment_hash);
2213 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2214 assert!(err_msg.contains("max HTLC"));
2216 _ => panic!("Unexpected event"),
2218 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2219 assert_eq!(htlc_msgs.len(), 2);
2220 check_added_monitors!(nodes[0], 2);
2224 fn no_extra_retries_on_back_to_back_fail() {
2225 // In a previous release, we had a race where we may exceed the payment retry count if we
2226 // get two failures in a row with the second indicating that all paths had failed (this field,
2227 // `all_paths_failed`, has since been removed).
2228 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2229 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2230 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2231 // pending which we will see later. Thus, when we previously removed the retry tracking map
2232 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2233 // retry entry even though more events for the same payment were still pending. This led to
2234 // us retrying a payment again even though we'd already given up on it.
2236 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2237 // is used to remove the payment retry counter entries instead. This tests for the specific
2238 // excess-retry case while also testing `PaymentFailed` generation.
2240 let chanmon_cfgs = create_chanmon_cfgs(3);
2241 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2242 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2243 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2245 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2246 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2248 let amt_msat = 200_000_000;
2249 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2250 #[cfg(feature = "std")]
2251 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2252 #[cfg(not(feature = "std"))]
2253 let payment_expiry_secs = 60 * 60;
2254 let mut invoice_features = InvoiceFeatures::empty();
2255 invoice_features.set_variable_length_onion_required();
2256 invoice_features.set_payment_secret_required();
2257 invoice_features.set_basic_mpp_optional();
2258 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2259 .with_expiry_time(payment_expiry_secs as u64)
2260 .with_features(invoice_features);
2261 let route_params = RouteParameters {
2263 final_value_msat: amt_msat,
2266 let mut route = Route {
2269 pubkey: nodes[1].node.get_our_node_id(),
2270 node_features: nodes[1].node.node_features(),
2271 short_channel_id: chan_1_scid,
2272 channel_features: nodes[1].node.channel_features(),
2273 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2274 cltv_expiry_delta: 100,
2276 pubkey: nodes[2].node.get_our_node_id(),
2277 node_features: nodes[2].node.node_features(),
2278 short_channel_id: chan_2_scid,
2279 channel_features: nodes[2].node.channel_features(),
2280 fee_msat: 100_000_000,
2281 cltv_expiry_delta: 100,
2284 pubkey: nodes[1].node.get_our_node_id(),
2285 node_features: nodes[1].node.node_features(),
2286 short_channel_id: chan_1_scid,
2287 channel_features: nodes[1].node.channel_features(),
2288 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2289 cltv_expiry_delta: 100,
2291 pubkey: nodes[2].node.get_our_node_id(),
2292 node_features: nodes[2].node.node_features(),
2293 short_channel_id: chan_2_scid,
2294 channel_features: nodes[2].node.channel_features(),
2295 fee_msat: 100_000_000,
2296 cltv_expiry_delta: 100,
2299 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2301 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2302 let mut second_payment_params = route_params.payment_params.clone();
2303 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2304 // On retry, we'll only return one path
2305 route.paths.remove(1);
2306 route.paths[0][1].fee_msat = amt_msat;
2307 nodes[0].router.expect_find_route(RouteParameters {
2308 payment_params: second_payment_params,
2309 final_value_msat: amt_msat,
2310 }, Ok(route.clone()));
2312 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2313 let htlc_updates = SendEvent::from_node(&nodes[0]);
2314 check_added_monitors!(nodes[0], 1);
2315 assert_eq!(htlc_updates.msgs.len(), 1);
2317 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2318 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2319 check_added_monitors!(nodes[1], 1);
2320 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2322 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2323 check_added_monitors!(nodes[0], 1);
2324 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2326 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2327 check_added_monitors!(nodes[0], 1);
2328 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2330 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2331 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2332 check_added_monitors!(nodes[1], 1);
2333 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2335 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2336 check_added_monitors!(nodes[1], 1);
2337 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2339 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2340 check_added_monitors!(nodes[0], 1);
2342 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2343 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2344 check_added_monitors!(nodes[0], 1);
2345 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2347 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2348 check_added_monitors!(nodes[1], 1);
2349 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2351 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2352 check_added_monitors!(nodes[1], 1);
2353 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2355 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2356 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2357 check_added_monitors!(nodes[0], 1);
2359 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2360 check_added_monitors!(nodes[0], 1);
2361 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2363 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2364 check_added_monitors!(nodes[1], 1);
2365 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2366 check_added_monitors!(nodes[1], 1);
2367 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2369 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2370 check_added_monitors!(nodes[0], 1);
2372 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2373 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2376 // Previously, we retried payments in an event consumer, which would retry each
2377 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2378 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2379 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2380 // by adding the `PaymentFailed` event.
2382 // Because we now retry payments as a batch, we simply return a single-path route in the
2383 // second, batched, request, have that fail, ensure the payment was abandoned.
2384 let mut events = nodes[0].node.get_and_clear_pending_events();
2385 assert_eq!(events.len(), 3);
2387 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2388 assert_eq!(payment_hash, ev_payment_hash);
2389 assert_eq!(payment_failed_permanently, false);
2391 _ => panic!("Unexpected event"),
2394 Event::PendingHTLCsForwardable { .. } => {},
2395 _ => panic!("Unexpected event"),
2398 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2399 assert_eq!(payment_hash, ev_payment_hash);
2400 assert_eq!(payment_failed_permanently, false);
2402 _ => panic!("Unexpected event"),
2405 nodes[0].node.process_pending_htlc_forwards();
2406 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2407 check_added_monitors!(nodes[0], 1);
2409 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2410 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2411 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2412 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2413 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2415 let mut events = nodes[0].node.get_and_clear_pending_events();
2416 assert_eq!(events.len(), 2);
2418 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2419 assert_eq!(payment_hash, ev_payment_hash);
2420 assert_eq!(payment_failed_permanently, false);
2422 _ => panic!("Unexpected event"),
2425 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
2426 assert_eq!(payment_hash, *ev_payment_hash);
2427 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2429 _ => panic!("Unexpected event"),
2434 fn test_simple_partial_retry() {
2435 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2436 // full amount of the payment, rather than only the missing amount. Here we simply test for
2437 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2438 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2440 let chanmon_cfgs = create_chanmon_cfgs(3);
2441 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2442 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2443 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2445 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2446 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2448 let amt_msat = 200_000_000;
2449 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2450 #[cfg(feature = "std")]
2451 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2452 #[cfg(not(feature = "std"))]
2453 let payment_expiry_secs = 60 * 60;
2454 let mut invoice_features = InvoiceFeatures::empty();
2455 invoice_features.set_variable_length_onion_required();
2456 invoice_features.set_payment_secret_required();
2457 invoice_features.set_basic_mpp_optional();
2458 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2459 .with_expiry_time(payment_expiry_secs as u64)
2460 .with_features(invoice_features);
2461 let route_params = RouteParameters {
2463 final_value_msat: amt_msat,
2466 let mut route = Route {
2469 pubkey: nodes[1].node.get_our_node_id(),
2470 node_features: nodes[1].node.node_features(),
2471 short_channel_id: chan_1_scid,
2472 channel_features: nodes[1].node.channel_features(),
2473 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2474 cltv_expiry_delta: 100,
2476 pubkey: nodes[2].node.get_our_node_id(),
2477 node_features: nodes[2].node.node_features(),
2478 short_channel_id: chan_2_scid,
2479 channel_features: nodes[2].node.channel_features(),
2480 fee_msat: 100_000_000,
2481 cltv_expiry_delta: 100,
2484 pubkey: nodes[1].node.get_our_node_id(),
2485 node_features: nodes[1].node.node_features(),
2486 short_channel_id: chan_1_scid,
2487 channel_features: nodes[1].node.channel_features(),
2489 cltv_expiry_delta: 100,
2491 pubkey: nodes[2].node.get_our_node_id(),
2492 node_features: nodes[2].node.node_features(),
2493 short_channel_id: chan_2_scid,
2494 channel_features: nodes[2].node.channel_features(),
2495 fee_msat: 100_000_000,
2496 cltv_expiry_delta: 100,
2499 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2501 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2502 let mut second_payment_params = route_params.payment_params.clone();
2503 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2504 // On retry, we'll only be asked for one path (or 100k sats)
2505 route.paths.remove(0);
2506 nodes[0].router.expect_find_route(RouteParameters {
2507 payment_params: second_payment_params,
2508 final_value_msat: amt_msat / 2,
2509 }, Ok(route.clone()));
2511 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2512 let htlc_updates = SendEvent::from_node(&nodes[0]);
2513 check_added_monitors!(nodes[0], 1);
2514 assert_eq!(htlc_updates.msgs.len(), 1);
2516 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2517 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2518 check_added_monitors!(nodes[1], 1);
2519 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2521 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2522 check_added_monitors!(nodes[0], 1);
2523 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2525 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2526 check_added_monitors!(nodes[0], 1);
2527 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2529 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2530 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2531 check_added_monitors!(nodes[1], 1);
2532 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2534 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2535 check_added_monitors!(nodes[1], 1);
2536 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2538 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2539 check_added_monitors!(nodes[0], 1);
2541 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2542 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2543 check_added_monitors!(nodes[0], 1);
2544 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2546 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2547 check_added_monitors!(nodes[1], 1);
2549 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2550 check_added_monitors!(nodes[1], 1);
2552 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2554 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2555 check_added_monitors!(nodes[0], 1);
2557 let mut events = nodes[0].node.get_and_clear_pending_events();
2558 assert_eq!(events.len(), 2);
2560 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2561 assert_eq!(payment_hash, ev_payment_hash);
2562 assert_eq!(payment_failed_permanently, false);
2564 _ => panic!("Unexpected event"),
2567 Event::PendingHTLCsForwardable { .. } => {},
2568 _ => panic!("Unexpected event"),
2571 nodes[0].node.process_pending_htlc_forwards();
2572 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2573 check_added_monitors!(nodes[0], 1);
2575 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2576 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2578 expect_pending_htlcs_forwardable!(nodes[1]);
2579 check_added_monitors!(nodes[1], 1);
2581 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2582 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2583 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2584 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2586 expect_pending_htlcs_forwardable!(nodes[2]);
2587 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2591 #[cfg(feature = "std")]
2592 fn test_threaded_payment_retries() {
2593 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2594 // a single thread and would happily let multiple threads run retries at the same time. Because
2595 // retries are done by first calculating the amount we need to retry, then dropping the
2596 // relevant lock, then actually sending, we would happily let multiple threads retry the same
2597 // amount at the same time, overpaying our original HTLC!
2598 let chanmon_cfgs = create_chanmon_cfgs(4);
2599 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2600 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2601 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2603 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2604 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2605 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2606 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2608 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2609 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2610 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2611 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2613 let amt_msat = 100_000_000;
2614 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2615 #[cfg(feature = "std")]
2616 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2617 #[cfg(not(feature = "std"))]
2618 let payment_expiry_secs = 60 * 60;
2619 let mut invoice_features = InvoiceFeatures::empty();
2620 invoice_features.set_variable_length_onion_required();
2621 invoice_features.set_payment_secret_required();
2622 invoice_features.set_basic_mpp_optional();
2623 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2624 .with_expiry_time(payment_expiry_secs as u64)
2625 .with_features(invoice_features);
2626 let mut route_params = RouteParameters {
2628 final_value_msat: amt_msat,
2631 let mut route = Route {
2634 pubkey: nodes[1].node.get_our_node_id(),
2635 node_features: nodes[1].node.node_features(),
2636 short_channel_id: chan_1_scid,
2637 channel_features: nodes[1].node.channel_features(),
2639 cltv_expiry_delta: 100,
2641 pubkey: nodes[3].node.get_our_node_id(),
2642 node_features: nodes[2].node.node_features(),
2643 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2644 channel_features: nodes[2].node.channel_features(),
2645 fee_msat: amt_msat / 1000,
2646 cltv_expiry_delta: 100,
2649 pubkey: nodes[2].node.get_our_node_id(),
2650 node_features: nodes[2].node.node_features(),
2651 short_channel_id: chan_3_scid,
2652 channel_features: nodes[2].node.channel_features(),
2654 cltv_expiry_delta: 100,
2656 pubkey: nodes[3].node.get_our_node_id(),
2657 node_features: nodes[3].node.node_features(),
2658 short_channel_id: chan_4_scid,
2659 channel_features: nodes[3].node.channel_features(),
2660 fee_msat: amt_msat - amt_msat / 1000,
2661 cltv_expiry_delta: 100,
2664 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2666 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2668 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
2669 check_added_monitors!(nodes[0], 2);
2670 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2671 assert_eq!(send_msg_events.len(), 2);
2672 send_msg_events.retain(|msg|
2673 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
2674 // Drop the commitment update for nodes[2], we can just let that one sit pending
2676 *node_id == nodes[1].node.get_our_node_id()
2677 } else { panic!(); }
2680 // from here on out, the retry `RouteParameters` amount will be amt/1000
2681 route_params.final_value_msat /= 1000;
2684 let end_time = Instant::now() + Duration::from_secs(1);
2685 macro_rules! thread_body { () => { {
2686 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
2687 let node_ref = NodePtr::from_node(&nodes[0]);
2689 let node_a = unsafe { &*node_ref.0 };
2690 while Instant::now() < end_time {
2691 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2692 // Ignore if we have any pending events, just always pretend we just got a
2693 // PendingHTLCsForwardable
2694 node_a.node.process_pending_htlc_forwards();
2698 let mut threads = Vec::new();
2699 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
2701 // Back in the main thread, poll pending messages and make sure that we never have more than
2702 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
2703 // there are HTLC messages shoved in while its running. This allows us to test that we never
2704 // generate an additional update_add_htlc until we've fully failed the first.
2705 let mut previously_failed_channels = Vec::new();
2707 assert_eq!(send_msg_events.len(), 1);
2708 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
2709 assert_eq!(send_event.msgs.len(), 1);
2711 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
2712 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
2714 // Note that we only push one route into `expect_find_route` at a time, because that's all
2715 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
2716 // we should still ultimately fail for the same reason - because we're trying to send too
2717 // many HTLCs at once.
2718 let mut new_route_params = route_params.clone();
2719 previously_failed_channels.push(route.paths[0][1].short_channel_id);
2720 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
2721 route.paths[0][1].short_channel_id += 1;
2722 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
2724 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2725 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
2726 // The "normal" commitment_signed_dance delivers the final RAA and then calls
2727 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
2728 // This races with our other threads which may generate an add-HTLCs commitment update via
2729 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
2730 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
2731 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
2732 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
2734 let cur_time = Instant::now();
2735 if cur_time > end_time {
2736 for thread in threads.drain(..) { thread.join().unwrap(); }
2739 // Make sure we have some events to handle when we go around...
2740 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2741 nodes[0].node.process_pending_htlc_forwards();
2742 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2743 check_added_monitors!(nodes[0], 2);
2745 if cur_time > end_time {