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 payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1196 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1198 let mut node_0_per_peer_lock;
1199 let mut node_0_peer_state_lock;
1200 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1202 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1203 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1204 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1205 channel_1.get_short_channel_id().unwrap()
1207 assert_eq!(chan_1_used_liquidity, None);
1210 let mut node_1_per_peer_lock;
1211 let mut node_1_peer_state_lock;
1212 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1214 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1215 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1216 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1217 channel_2.get_short_channel_id().unwrap()
1220 assert_eq!(chan_2_used_liquidity, None);
1222 let pending_payments = nodes[0].node.list_recent_payments();
1223 assert_eq!(pending_payments.len(), 1);
1224 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1226 // Remove fulfilled payment
1227 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1228 nodes[0].node.timer_tick_occurred();
1231 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1232 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1233 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1235 let mut node_0_per_peer_lock;
1236 let mut node_0_peer_state_lock;
1237 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1239 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1240 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1241 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1242 channel_1.get_short_channel_id().unwrap()
1244 // First hop accounts for expected 1000 msat fee
1245 assert_eq!(chan_1_used_liquidity, Some(501000));
1248 let mut node_1_per_peer_lock;
1249 let mut node_1_peer_state_lock;
1250 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1252 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1253 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1254 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1255 channel_2.get_short_channel_id().unwrap()
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();
1272 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1274 let mut node_0_per_peer_lock;
1275 let mut node_0_peer_state_lock;
1276 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1278 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1279 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1280 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1281 channel_1.get_short_channel_id().unwrap()
1283 assert_eq!(chan_1_used_liquidity, None);
1286 let mut node_1_per_peer_lock;
1287 let mut node_1_peer_state_lock;
1288 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1290 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1291 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1292 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1293 channel_2.get_short_channel_id().unwrap()
1295 assert_eq!(chan_2_used_liquidity, None);
1298 let pending_payments = nodes[0].node.list_recent_payments();
1299 assert_eq!(pending_payments.len(), 0);
1303 fn test_holding_cell_inflight_htlcs() {
1304 let chanmon_cfgs = create_chanmon_cfgs(2);
1305 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1306 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1307 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1308 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1310 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1311 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1313 // Queue up two payments - one will be delivered right away, one immediately goes into the
1314 // holding cell as nodes[0] is AwaitingRAA.
1316 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1317 check_added_monitors!(nodes[0], 1);
1318 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1319 check_added_monitors!(nodes[0], 0);
1322 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1325 let mut node_0_per_peer_lock;
1326 let mut node_0_peer_state_lock;
1327 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1329 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1330 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1331 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1332 channel.get_short_channel_id().unwrap()
1335 assert_eq!(used_liquidity, Some(2000000));
1338 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1339 nodes[0].node.get_and_clear_pending_msg_events();
1343 fn intercepted_payment() {
1344 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1345 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1346 // payment or (b) fail the payment.
1347 do_test_intercepted_payment(InterceptTest::Forward);
1348 do_test_intercepted_payment(InterceptTest::Fail);
1349 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1350 do_test_intercepted_payment(InterceptTest::Timeout);
1353 fn do_test_intercepted_payment(test: InterceptTest) {
1354 let chanmon_cfgs = create_chanmon_cfgs(3);
1355 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1357 let mut zero_conf_chan_config = test_default_channel_config();
1358 zero_conf_chan_config.manually_accept_inbound_channels = true;
1359 let mut intercept_forwards_config = test_default_channel_config();
1360 intercept_forwards_config.accept_intercept_htlcs = true;
1361 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1363 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1364 let scorer = test_utils::TestScorer::new();
1365 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1367 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1369 let amt_msat = 100_000;
1370 let intercept_scid = nodes[1].node.get_intercept_scid();
1371 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1372 .with_route_hints(vec![
1373 RouteHint(vec![RouteHintHop {
1374 src_node_id: nodes[1].node.get_our_node_id(),
1375 short_channel_id: intercept_scid,
1378 proportional_millionths: 0,
1380 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1381 htlc_minimum_msat: None,
1382 htlc_maximum_msat: None,
1385 .with_features(nodes[2].node.invoice_features());
1386 let route_params = RouteParameters {
1388 final_value_msat: amt_msat,
1390 let route = get_route(
1391 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1392 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1393 route_params.payment_params.final_cltv_expiry_delta, nodes[0].logger, &scorer,
1397 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1398 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1399 let payment_event = {
1401 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1402 assert_eq!(added_monitors.len(), 1);
1403 added_monitors.clear();
1405 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1406 assert_eq!(events.len(), 1);
1407 SendEvent::from_event(events.remove(0))
1409 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1410 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1412 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1413 let events = nodes[1].node.get_and_clear_pending_events();
1414 assert_eq!(events.len(), 1);
1415 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1416 crate::util::events::Event::HTLCIntercepted {
1417 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1419 assert_eq!(pmt_hash, payment_hash);
1420 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1421 assert_eq!(short_channel_id, intercept_scid);
1422 (intercept_id, expected_outbound_amount_msat)
1427 // Check for unknown channel id error.
1428 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();
1429 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()) });
1431 if test == InterceptTest::Fail {
1432 // Ensure we can fail the intercepted payment back.
1433 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1434 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1435 nodes[1].node.process_pending_htlc_forwards();
1436 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1437 check_added_monitors!(&nodes[1], 1);
1438 assert!(update_fail.update_fail_htlcs.len() == 1);
1439 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1440 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1441 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1443 // Ensure the payment fails with the expected error.
1444 let fail_conditions = PaymentFailedConditions::new()
1445 .blamed_scid(intercept_scid)
1446 .blamed_chan_closed(true)
1447 .expected_htlc_error_data(0x4000 | 10, &[]);
1448 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1449 } else if test == InterceptTest::Forward {
1450 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1451 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1452 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();
1453 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1454 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1456 // Open the just-in-time channel so the payment can then be forwarded.
1457 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1459 // Finally, forward the intercepted payment through and claim it.
1460 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1461 expect_pending_htlcs_forwardable!(nodes[1]);
1463 let payment_event = {
1465 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1466 assert_eq!(added_monitors.len(), 1);
1467 added_monitors.clear();
1469 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1470 assert_eq!(events.len(), 1);
1471 SendEvent::from_event(events.remove(0))
1473 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1474 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1475 expect_pending_htlcs_forwardable!(nodes[2]);
1477 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1478 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1479 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1480 let events = nodes[0].node.get_and_clear_pending_events();
1481 assert_eq!(events.len(), 2);
1483 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1484 assert_eq!(payment_preimage, *ev_preimage);
1485 assert_eq!(payment_hash, *ev_hash);
1486 assert_eq!(fee_paid_msat, &Some(1000));
1488 _ => panic!("Unexpected event")
1491 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1492 assert_eq!(hash, Some(payment_hash));
1494 _ => panic!("Unexpected event")
1496 } else if test == InterceptTest::Timeout {
1497 let mut block = Block {
1498 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1501 connect_block(&nodes[0], &block);
1502 connect_block(&nodes[1], &block);
1503 for _ in 0..TEST_FINAL_CLTV {
1504 block.header.prev_blockhash = block.block_hash();
1505 connect_block(&nodes[0], &block);
1506 connect_block(&nodes[1], &block);
1508 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1509 check_added_monitors!(nodes[1], 1);
1510 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1511 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1512 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1513 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1514 assert!(htlc_timeout_updates.update_fee.is_none());
1516 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1517 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1518 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1520 // Check for unknown intercept id error.
1521 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1522 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();
1523 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1524 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1525 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1529 #[derive(PartialEq)]
1540 fn automatic_retries() {
1541 do_automatic_retries(AutoRetry::Success);
1542 do_automatic_retries(AutoRetry::Spontaneous);
1543 do_automatic_retries(AutoRetry::FailAttempts);
1544 do_automatic_retries(AutoRetry::FailTimeout);
1545 do_automatic_retries(AutoRetry::FailOnRestart);
1546 do_automatic_retries(AutoRetry::FailOnRetry);
1548 fn do_automatic_retries(test: AutoRetry) {
1549 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1551 let chanmon_cfgs = create_chanmon_cfgs(3);
1552 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1553 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1556 let new_chain_monitor;
1557 let node_0_deserialized;
1559 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1560 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1561 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1563 // Marshall data to send the payment
1564 #[cfg(feature = "std")]
1565 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1566 #[cfg(not(feature = "std"))]
1567 let payment_expiry_secs = 60 * 60;
1568 let amt_msat = 1000;
1569 let mut invoice_features = InvoiceFeatures::empty();
1570 invoice_features.set_variable_length_onion_required();
1571 invoice_features.set_payment_secret_required();
1572 invoice_features.set_basic_mpp_optional();
1573 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1574 .with_expiry_time(payment_expiry_secs as u64)
1575 .with_features(invoice_features);
1576 let route_params = RouteParameters {
1578 final_value_msat: amt_msat,
1580 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1582 macro_rules! pass_failed_attempt_with_retry_along_path {
1583 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1584 // Send a payment attempt that fails due to lack of liquidity on the second hop
1585 check_added_monitors!(nodes[0], 1);
1586 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1587 let mut update_add = update_0.update_add_htlcs[0].clone();
1588 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1589 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1590 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1591 nodes[1].node.process_pending_htlc_forwards();
1592 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1593 vec![HTLCDestination::NextHopChannel {
1594 node_id: Some(nodes[2].node.get_our_node_id()),
1595 channel_id: $failing_channel_id,
1597 nodes[1].node.process_pending_htlc_forwards();
1598 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1599 check_added_monitors!(&nodes[1], 1);
1600 assert!(update_1.update_fail_htlcs.len() == 1);
1601 let fail_msg = update_1.update_fail_htlcs[0].clone();
1602 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1603 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1605 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1606 let mut events = nodes[0].node.get_and_clear_pending_events();
1607 assert_eq!(events.len(), 2);
1609 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1610 assert_eq!(payment_hash, ev_payment_hash);
1611 assert_eq!(payment_failed_permanently, false);
1613 _ => panic!("Unexpected event"),
1615 if $expect_pending_htlcs_forwardable {
1617 Event::PendingHTLCsForwardable { .. } => {},
1618 _ => panic!("Unexpected event"),
1622 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1623 assert_eq!(payment_hash, ev_payment_hash);
1625 _ => panic!("Unexpected event"),
1631 if test == AutoRetry::Success {
1632 // Test that we can succeed on the first retry.
1633 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1634 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1636 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1637 // attempt, since the initial second hop channel will be excluded from pathfinding
1638 create_announced_chan_between_nodes(&nodes, 1, 2);
1640 // We retry payments in `process_pending_htlc_forwards`
1641 nodes[0].node.process_pending_htlc_forwards();
1642 check_added_monitors!(nodes[0], 1);
1643 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1644 assert_eq!(msg_events.len(), 1);
1645 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1646 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1647 } else if test == AutoRetry::Spontaneous {
1648 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1649 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1651 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1652 // attempt, since the initial second hop channel will be excluded from pathfinding
1653 create_announced_chan_between_nodes(&nodes, 1, 2);
1655 // We retry payments in `process_pending_htlc_forwards`
1656 nodes[0].node.process_pending_htlc_forwards();
1657 check_added_monitors!(nodes[0], 1);
1658 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1659 assert_eq!(msg_events.len(), 1);
1660 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1661 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1662 } else if test == AutoRetry::FailAttempts {
1663 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1664 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1665 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1667 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1668 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1669 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1671 // We retry payments in `process_pending_htlc_forwards`
1672 nodes[0].node.process_pending_htlc_forwards();
1673 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1675 // Ensure we won't retry a second time.
1676 nodes[0].node.process_pending_htlc_forwards();
1677 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1678 assert_eq!(msg_events.len(), 0);
1679 } else if test == AutoRetry::FailTimeout {
1680 #[cfg(not(feature = "no-std"))] {
1681 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1682 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();
1683 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1685 // Advance the time so the second attempt fails due to timeout.
1686 SinceEpoch::advance(Duration::from_secs(61));
1688 // Make sure we don't retry again.
1689 nodes[0].node.process_pending_htlc_forwards();
1690 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1691 assert_eq!(msg_events.len(), 0);
1693 let mut events = nodes[0].node.get_and_clear_pending_events();
1694 assert_eq!(events.len(), 1);
1696 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1697 assert_eq!(payment_hash, *ev_payment_hash);
1698 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1700 _ => panic!("Unexpected event"),
1703 } else if test == AutoRetry::FailOnRestart {
1704 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1705 // attempts remaining prior to restart.
1706 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1707 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1709 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1710 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1711 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1713 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1714 nodes[0].node.process_pending_htlc_forwards();
1715 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1717 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1718 let node_encoded = nodes[0].node.encode();
1719 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1720 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1722 let mut events = nodes[0].node.get_and_clear_pending_events();
1723 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
1724 // Make sure we don't retry again.
1725 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1726 assert_eq!(msg_events.len(), 0);
1728 let mut events = nodes[0].node.get_and_clear_pending_events();
1729 assert_eq!(events.len(), 1);
1731 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1732 assert_eq!(payment_hash, *ev_payment_hash);
1733 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1735 _ => panic!("Unexpected event"),
1737 } else if test == AutoRetry::FailOnRetry {
1738 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1739 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1741 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1742 // fail to find a route.
1743 nodes[0].node.process_pending_htlc_forwards();
1744 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1745 assert_eq!(msg_events.len(), 0);
1747 let mut events = nodes[0].node.get_and_clear_pending_events();
1748 assert_eq!(events.len(), 1);
1750 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1751 assert_eq!(payment_hash, *ev_payment_hash);
1752 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1754 _ => panic!("Unexpected event"),
1760 fn auto_retry_partial_failure() {
1761 // Test that we'll retry appropriately on send partial failure and retry partial failure.
1762 let chanmon_cfgs = create_chanmon_cfgs(2);
1763 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1764 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1765 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1767 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1768 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1769 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1771 // Marshall data to send the payment
1772 let amt_msat = 20_000;
1773 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1774 #[cfg(feature = "std")]
1775 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1776 #[cfg(not(feature = "std"))]
1777 let payment_expiry_secs = 60 * 60;
1778 let mut invoice_features = InvoiceFeatures::empty();
1779 invoice_features.set_variable_length_onion_required();
1780 invoice_features.set_payment_secret_required();
1781 invoice_features.set_basic_mpp_optional();
1782 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1783 .with_expiry_time(payment_expiry_secs as u64)
1784 .with_features(invoice_features);
1785 let route_params = RouteParameters {
1787 final_value_msat: amt_msat,
1790 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1791 // second (for the initial send path2 over chan_2) fails.
1792 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1793 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1794 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1795 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1796 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1797 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1798 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1800 // Configure the initial send, retry1 and retry2's paths.
1801 let send_route = Route {
1804 pubkey: nodes[1].node.get_our_node_id(),
1805 node_features: nodes[1].node.node_features(),
1806 short_channel_id: chan_1_id,
1807 channel_features: nodes[1].node.channel_features(),
1808 fee_msat: amt_msat / 2,
1809 cltv_expiry_delta: 100,
1812 pubkey: nodes[1].node.get_our_node_id(),
1813 node_features: nodes[1].node.node_features(),
1814 short_channel_id: chan_2_id,
1815 channel_features: nodes[1].node.channel_features(),
1816 fee_msat: amt_msat / 2,
1817 cltv_expiry_delta: 100,
1820 payment_params: Some(route_params.payment_params.clone()),
1822 let retry_1_route = Route {
1825 pubkey: nodes[1].node.get_our_node_id(),
1826 node_features: nodes[1].node.node_features(),
1827 short_channel_id: chan_1_id,
1828 channel_features: nodes[1].node.channel_features(),
1829 fee_msat: amt_msat / 4,
1830 cltv_expiry_delta: 100,
1833 pubkey: nodes[1].node.get_our_node_id(),
1834 node_features: nodes[1].node.node_features(),
1835 short_channel_id: chan_3_id,
1836 channel_features: nodes[1].node.channel_features(),
1837 fee_msat: amt_msat / 4,
1838 cltv_expiry_delta: 100,
1841 payment_params: Some(route_params.payment_params.clone()),
1843 let retry_2_route = Route {
1846 pubkey: nodes[1].node.get_our_node_id(),
1847 node_features: nodes[1].node.node_features(),
1848 short_channel_id: chan_1_id,
1849 channel_features: nodes[1].node.channel_features(),
1850 fee_msat: amt_msat / 4,
1851 cltv_expiry_delta: 100,
1854 payment_params: Some(route_params.payment_params.clone()),
1856 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1857 let mut payment_params = route_params.payment_params.clone();
1858 payment_params.previously_failed_channels.push(chan_2_id);
1859 nodes[0].router.expect_find_route(RouteParameters {
1860 payment_params, final_value_msat: amt_msat / 2,
1861 }, Ok(retry_1_route));
1862 let mut payment_params = route_params.payment_params.clone();
1863 payment_params.previously_failed_channels.push(chan_3_id);
1864 nodes[0].router.expect_find_route(RouteParameters {
1865 payment_params, final_value_msat: amt_msat / 4,
1866 }, Ok(retry_2_route));
1868 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1869 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1870 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1871 assert_eq!(closed_chan_events.len(), 4);
1872 match closed_chan_events[0] {
1873 Event::ChannelClosed { .. } => {},
1874 _ => panic!("Unexpected event"),
1876 match closed_chan_events[1] {
1877 Event::PaymentPathFailed { .. } => {},
1878 _ => panic!("Unexpected event"),
1880 match closed_chan_events[2] {
1881 Event::ChannelClosed { .. } => {},
1882 _ => panic!("Unexpected event"),
1884 match closed_chan_events[3] {
1885 Event::PaymentPathFailed { .. } => {},
1886 _ => panic!("Unexpected event"),
1889 // Pass the first part of the payment along the path.
1890 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1891 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1893 // First message is the first update_add, remaining messages are broadcasting channel updates and
1894 // errors for the permfailed channels
1895 assert_eq!(msg_events.len(), 5);
1896 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1898 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1899 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1900 check_added_monitors!(nodes[1], 1);
1901 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1903 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1904 check_added_monitors!(nodes[0], 1);
1905 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1907 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1908 check_added_monitors!(nodes[0], 1);
1909 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1911 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1912 check_added_monitors!(nodes[1], 1);
1914 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1915 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1916 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1917 check_added_monitors!(nodes[1], 1);
1918 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1920 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1921 check_added_monitors!(nodes[0], 1);
1923 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
1924 check_added_monitors!(nodes[0], 1);
1925 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1927 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1928 check_added_monitors!(nodes[1], 1);
1930 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1931 nodes[1].node.process_pending_htlc_forwards();
1932 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
1933 nodes[1].node.claim_funds(payment_preimage);
1934 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
1935 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1936 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
1938 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
1939 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
1940 check_added_monitors!(nodes[0], 1);
1941 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1943 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1944 check_added_monitors!(nodes[1], 4);
1945 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1947 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1948 check_added_monitors!(nodes[1], 1);
1949 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1951 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1952 check_added_monitors!(nodes[0], 1);
1954 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
1955 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
1956 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
1957 check_added_monitors!(nodes[0], 1);
1958 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1960 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
1961 check_added_monitors!(nodes[1], 1);
1963 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1964 check_added_monitors!(nodes[1], 1);
1965 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1967 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1968 check_added_monitors!(nodes[0], 1);
1969 expect_payment_sent!(nodes[0], payment_preimage);
1973 fn auto_retry_zero_attempts_send_error() {
1974 let chanmon_cfgs = create_chanmon_cfgs(2);
1975 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1976 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1977 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1979 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1980 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1982 // Marshall data to send the payment
1983 let amt_msat = 20_000;
1984 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1985 #[cfg(feature = "std")]
1986 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1987 #[cfg(not(feature = "std"))]
1988 let payment_expiry_secs = 60 * 60;
1989 let mut invoice_features = InvoiceFeatures::empty();
1990 invoice_features.set_variable_length_onion_required();
1991 invoice_features.set_payment_secret_required();
1992 invoice_features.set_basic_mpp_optional();
1993 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1994 .with_expiry_time(payment_expiry_secs as u64)
1995 .with_features(invoice_features);
1996 let route_params = RouteParameters {
1998 final_value_msat: amt_msat,
2001 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2002 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2003 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2004 let events = nodes[0].node.get_and_clear_pending_events();
2005 assert_eq!(events.len(), 3);
2006 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2007 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2008 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2009 check_added_monitors!(nodes[0], 2);
2013 fn fails_paying_after_rejected_by_payee() {
2014 let chanmon_cfgs = create_chanmon_cfgs(2);
2015 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2016 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2017 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2019 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2021 // Marshall data to send the payment
2022 let amt_msat = 20_000;
2023 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2024 #[cfg(feature = "std")]
2025 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2026 #[cfg(not(feature = "std"))]
2027 let payment_expiry_secs = 60 * 60;
2028 let mut invoice_features = InvoiceFeatures::empty();
2029 invoice_features.set_variable_length_onion_required();
2030 invoice_features.set_payment_secret_required();
2031 invoice_features.set_basic_mpp_optional();
2032 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2033 .with_expiry_time(payment_expiry_secs as u64)
2034 .with_features(invoice_features);
2035 let route_params = RouteParameters {
2037 final_value_msat: amt_msat,
2040 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2041 check_added_monitors!(nodes[0], 1);
2042 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2043 assert_eq!(events.len(), 1);
2044 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2045 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2046 check_added_monitors!(nodes[1], 0);
2047 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2048 expect_pending_htlcs_forwardable!(nodes[1]);
2049 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2051 nodes[1].node.fail_htlc_backwards(&payment_hash);
2052 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2053 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash);
2057 fn retry_multi_path_single_failed_payment() {
2058 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2059 let chanmon_cfgs = create_chanmon_cfgs(2);
2060 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2061 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2062 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2064 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2065 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2067 let amt_msat = 100_010_000;
2069 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2070 #[cfg(feature = "std")]
2071 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2072 #[cfg(not(feature = "std"))]
2073 let payment_expiry_secs = 60 * 60;
2074 let mut invoice_features = InvoiceFeatures::empty();
2075 invoice_features.set_variable_length_onion_required();
2076 invoice_features.set_payment_secret_required();
2077 invoice_features.set_basic_mpp_optional();
2078 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2079 .with_expiry_time(payment_expiry_secs as u64)
2080 .with_features(invoice_features);
2081 let route_params = RouteParameters {
2082 payment_params: payment_params.clone(),
2083 final_value_msat: amt_msat,
2086 let chans = nodes[0].node.list_usable_channels();
2087 let mut route = Route {
2090 pubkey: nodes[1].node.get_our_node_id(),
2091 node_features: nodes[1].node.node_features(),
2092 short_channel_id: chans[0].short_channel_id.unwrap(),
2093 channel_features: nodes[1].node.channel_features(),
2095 cltv_expiry_delta: 100,
2098 pubkey: nodes[1].node.get_our_node_id(),
2099 node_features: nodes[1].node.node_features(),
2100 short_channel_id: chans[1].short_channel_id.unwrap(),
2101 channel_features: nodes[1].node.channel_features(),
2102 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2103 cltv_expiry_delta: 100,
2106 payment_params: Some(payment_params),
2108 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2109 // On retry, split the payment across both channels.
2110 route.paths[0][0].fee_msat = 50_000_001;
2111 route.paths[1][0].fee_msat = 50_000_000;
2112 let mut pay_params = route.payment_params.clone().unwrap();
2113 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2114 nodes[0].router.expect_find_route(RouteParameters {
2115 payment_params: pay_params,
2116 // Note that the second request here requests the amount we originally failed to send,
2117 // not the amount remaining on the full payment, which should be changed.
2118 final_value_msat: 100_000_001,
2119 }, Ok(route.clone()));
2122 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2123 // The initial send attempt, 2 paths
2124 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2125 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2126 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2127 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2128 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2131 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2132 let events = nodes[0].node.get_and_clear_pending_events();
2133 assert_eq!(events.len(), 1);
2135 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2136 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2137 short_channel_id: Some(expected_scid), .. } =>
2139 assert_eq!(payment_hash, ev_payment_hash);
2140 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2141 assert!(err_msg.contains("max HTLC"));
2143 _ => panic!("Unexpected event"),
2145 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2146 assert_eq!(htlc_msgs.len(), 2);
2147 check_added_monitors!(nodes[0], 2);
2151 fn immediate_retry_on_failure() {
2152 // Tests that we can/will retry immediately after a failure
2153 let chanmon_cfgs = create_chanmon_cfgs(2);
2154 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2155 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2156 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2158 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2159 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2161 let amt_msat = 100_000_001;
2162 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2163 #[cfg(feature = "std")]
2164 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2165 #[cfg(not(feature = "std"))]
2166 let payment_expiry_secs = 60 * 60;
2167 let mut invoice_features = InvoiceFeatures::empty();
2168 invoice_features.set_variable_length_onion_required();
2169 invoice_features.set_payment_secret_required();
2170 invoice_features.set_basic_mpp_optional();
2171 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2172 .with_expiry_time(payment_expiry_secs as u64)
2173 .with_features(invoice_features);
2174 let route_params = RouteParameters {
2176 final_value_msat: amt_msat,
2179 let chans = nodes[0].node.list_usable_channels();
2180 let mut route = Route {
2183 pubkey: nodes[1].node.get_our_node_id(),
2184 node_features: nodes[1].node.node_features(),
2185 short_channel_id: chans[0].short_channel_id.unwrap(),
2186 channel_features: nodes[1].node.channel_features(),
2187 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2188 cltv_expiry_delta: 100,
2191 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2193 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2194 // On retry, split the payment across both channels.
2195 route.paths.push(route.paths[0].clone());
2196 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2197 route.paths[0][0].fee_msat = 50_000_000;
2198 route.paths[1][0].fee_msat = 50_000_001;
2199 let mut pay_params = route_params.payment_params.clone();
2200 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2201 nodes[0].router.expect_find_route(RouteParameters {
2202 payment_params: pay_params, final_value_msat: amt_msat,
2203 }, Ok(route.clone()));
2205 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2206 let events = nodes[0].node.get_and_clear_pending_events();
2207 assert_eq!(events.len(), 1);
2209 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2210 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2211 short_channel_id: Some(expected_scid), .. } =>
2213 assert_eq!(payment_hash, ev_payment_hash);
2214 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2215 assert!(err_msg.contains("max HTLC"));
2217 _ => panic!("Unexpected event"),
2219 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2220 assert_eq!(htlc_msgs.len(), 2);
2221 check_added_monitors!(nodes[0], 2);
2225 fn no_extra_retries_on_back_to_back_fail() {
2226 // In a previous release, we had a race where we may exceed the payment retry count if we
2227 // get two failures in a row with the second indicating that all paths had failed (this field,
2228 // `all_paths_failed`, has since been removed).
2229 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2230 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2231 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2232 // pending which we will see later. Thus, when we previously removed the retry tracking map
2233 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2234 // retry entry even though more events for the same payment were still pending. This led to
2235 // us retrying a payment again even though we'd already given up on it.
2237 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2238 // is used to remove the payment retry counter entries instead. This tests for the specific
2239 // excess-retry case while also testing `PaymentFailed` generation.
2241 let chanmon_cfgs = create_chanmon_cfgs(3);
2242 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2243 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2244 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2246 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2247 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2249 let amt_msat = 200_000_000;
2250 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2251 #[cfg(feature = "std")]
2252 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2253 #[cfg(not(feature = "std"))]
2254 let payment_expiry_secs = 60 * 60;
2255 let mut invoice_features = InvoiceFeatures::empty();
2256 invoice_features.set_variable_length_onion_required();
2257 invoice_features.set_payment_secret_required();
2258 invoice_features.set_basic_mpp_optional();
2259 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2260 .with_expiry_time(payment_expiry_secs as u64)
2261 .with_features(invoice_features);
2262 let route_params = RouteParameters {
2264 final_value_msat: amt_msat,
2267 let mut route = Route {
2270 pubkey: nodes[1].node.get_our_node_id(),
2271 node_features: nodes[1].node.node_features(),
2272 short_channel_id: chan_1_scid,
2273 channel_features: nodes[1].node.channel_features(),
2274 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2275 cltv_expiry_delta: 100,
2277 pubkey: nodes[2].node.get_our_node_id(),
2278 node_features: nodes[2].node.node_features(),
2279 short_channel_id: chan_2_scid,
2280 channel_features: nodes[2].node.channel_features(),
2281 fee_msat: 100_000_000,
2282 cltv_expiry_delta: 100,
2285 pubkey: nodes[1].node.get_our_node_id(),
2286 node_features: nodes[1].node.node_features(),
2287 short_channel_id: chan_1_scid,
2288 channel_features: nodes[1].node.channel_features(),
2289 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2290 cltv_expiry_delta: 100,
2292 pubkey: nodes[2].node.get_our_node_id(),
2293 node_features: nodes[2].node.node_features(),
2294 short_channel_id: chan_2_scid,
2295 channel_features: nodes[2].node.channel_features(),
2296 fee_msat: 100_000_000,
2297 cltv_expiry_delta: 100,
2300 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2302 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2303 let mut second_payment_params = route_params.payment_params.clone();
2304 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2305 // On retry, we'll only return one path
2306 route.paths.remove(1);
2307 route.paths[0][1].fee_msat = amt_msat;
2308 nodes[0].router.expect_find_route(RouteParameters {
2309 payment_params: second_payment_params,
2310 final_value_msat: amt_msat,
2311 }, Ok(route.clone()));
2313 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2314 let htlc_updates = SendEvent::from_node(&nodes[0]);
2315 check_added_monitors!(nodes[0], 1);
2316 assert_eq!(htlc_updates.msgs.len(), 1);
2318 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2319 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2320 check_added_monitors!(nodes[1], 1);
2321 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2323 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2324 check_added_monitors!(nodes[0], 1);
2325 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2327 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2328 check_added_monitors!(nodes[0], 1);
2329 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2331 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2332 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2333 check_added_monitors!(nodes[1], 1);
2334 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2336 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2337 check_added_monitors!(nodes[1], 1);
2338 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2340 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2341 check_added_monitors!(nodes[0], 1);
2343 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2344 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2345 check_added_monitors!(nodes[0], 1);
2346 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2348 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2349 check_added_monitors!(nodes[1], 1);
2350 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2352 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2353 check_added_monitors!(nodes[1], 1);
2354 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2356 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2357 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2358 check_added_monitors!(nodes[0], 1);
2360 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2361 check_added_monitors!(nodes[0], 1);
2362 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2364 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2365 check_added_monitors!(nodes[1], 1);
2366 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2367 check_added_monitors!(nodes[1], 1);
2368 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2370 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2371 check_added_monitors!(nodes[0], 1);
2373 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2374 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2377 // Previously, we retried payments in an event consumer, which would retry each
2378 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2379 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2380 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2381 // by adding the `PaymentFailed` event.
2383 // Because we now retry payments as a batch, we simply return a single-path route in the
2384 // second, batched, request, have that fail, ensure the payment was abandoned.
2385 let mut events = nodes[0].node.get_and_clear_pending_events();
2386 assert_eq!(events.len(), 3);
2388 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2389 assert_eq!(payment_hash, ev_payment_hash);
2390 assert_eq!(payment_failed_permanently, false);
2392 _ => panic!("Unexpected event"),
2395 Event::PendingHTLCsForwardable { .. } => {},
2396 _ => panic!("Unexpected event"),
2399 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2400 assert_eq!(payment_hash, ev_payment_hash);
2401 assert_eq!(payment_failed_permanently, false);
2403 _ => panic!("Unexpected event"),
2406 nodes[0].node.process_pending_htlc_forwards();
2407 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2408 check_added_monitors!(nodes[0], 1);
2410 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2411 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2412 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2413 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2414 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2416 let mut events = nodes[0].node.get_and_clear_pending_events();
2417 assert_eq!(events.len(), 2);
2419 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2420 assert_eq!(payment_hash, ev_payment_hash);
2421 assert_eq!(payment_failed_permanently, false);
2423 _ => panic!("Unexpected event"),
2426 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
2427 assert_eq!(payment_hash, *ev_payment_hash);
2428 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2430 _ => panic!("Unexpected event"),
2435 fn test_simple_partial_retry() {
2436 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2437 // full amount of the payment, rather than only the missing amount. Here we simply test for
2438 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2439 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2441 let chanmon_cfgs = create_chanmon_cfgs(3);
2442 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2443 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2444 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2446 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2447 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2449 let amt_msat = 200_000_000;
2450 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2451 #[cfg(feature = "std")]
2452 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2453 #[cfg(not(feature = "std"))]
2454 let payment_expiry_secs = 60 * 60;
2455 let mut invoice_features = InvoiceFeatures::empty();
2456 invoice_features.set_variable_length_onion_required();
2457 invoice_features.set_payment_secret_required();
2458 invoice_features.set_basic_mpp_optional();
2459 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2460 .with_expiry_time(payment_expiry_secs as u64)
2461 .with_features(invoice_features);
2462 let route_params = RouteParameters {
2464 final_value_msat: amt_msat,
2467 let mut route = Route {
2470 pubkey: nodes[1].node.get_our_node_id(),
2471 node_features: nodes[1].node.node_features(),
2472 short_channel_id: chan_1_scid,
2473 channel_features: nodes[1].node.channel_features(),
2474 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2475 cltv_expiry_delta: 100,
2477 pubkey: nodes[2].node.get_our_node_id(),
2478 node_features: nodes[2].node.node_features(),
2479 short_channel_id: chan_2_scid,
2480 channel_features: nodes[2].node.channel_features(),
2481 fee_msat: 100_000_000,
2482 cltv_expiry_delta: 100,
2485 pubkey: nodes[1].node.get_our_node_id(),
2486 node_features: nodes[1].node.node_features(),
2487 short_channel_id: chan_1_scid,
2488 channel_features: nodes[1].node.channel_features(),
2490 cltv_expiry_delta: 100,
2492 pubkey: nodes[2].node.get_our_node_id(),
2493 node_features: nodes[2].node.node_features(),
2494 short_channel_id: chan_2_scid,
2495 channel_features: nodes[2].node.channel_features(),
2496 fee_msat: 100_000_000,
2497 cltv_expiry_delta: 100,
2500 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2502 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2503 let mut second_payment_params = route_params.payment_params.clone();
2504 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2505 // On retry, we'll only be asked for one path (or 100k sats)
2506 route.paths.remove(0);
2507 nodes[0].router.expect_find_route(RouteParameters {
2508 payment_params: second_payment_params,
2509 final_value_msat: amt_msat / 2,
2510 }, Ok(route.clone()));
2512 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2513 let htlc_updates = SendEvent::from_node(&nodes[0]);
2514 check_added_monitors!(nodes[0], 1);
2515 assert_eq!(htlc_updates.msgs.len(), 1);
2517 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2518 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2519 check_added_monitors!(nodes[1], 1);
2520 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2522 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2523 check_added_monitors!(nodes[0], 1);
2524 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2526 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2527 check_added_monitors!(nodes[0], 1);
2528 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2530 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2531 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2532 check_added_monitors!(nodes[1], 1);
2533 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2535 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2536 check_added_monitors!(nodes[1], 1);
2537 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2539 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2540 check_added_monitors!(nodes[0], 1);
2542 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2543 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2544 check_added_monitors!(nodes[0], 1);
2545 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2547 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2548 check_added_monitors!(nodes[1], 1);
2550 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2551 check_added_monitors!(nodes[1], 1);
2553 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2555 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2556 check_added_monitors!(nodes[0], 1);
2558 let mut events = nodes[0].node.get_and_clear_pending_events();
2559 assert_eq!(events.len(), 2);
2561 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2562 assert_eq!(payment_hash, ev_payment_hash);
2563 assert_eq!(payment_failed_permanently, false);
2565 _ => panic!("Unexpected event"),
2568 Event::PendingHTLCsForwardable { .. } => {},
2569 _ => panic!("Unexpected event"),
2572 nodes[0].node.process_pending_htlc_forwards();
2573 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2574 check_added_monitors!(nodes[0], 1);
2576 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2577 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2579 expect_pending_htlcs_forwardable!(nodes[1]);
2580 check_added_monitors!(nodes[1], 1);
2582 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2583 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2584 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2585 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2587 expect_pending_htlcs_forwardable!(nodes[2]);
2588 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2592 #[cfg(feature = "std")]
2593 fn test_threaded_payment_retries() {
2594 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2595 // a single thread and would happily let multiple threads run retries at the same time. Because
2596 // retries are done by first calculating the amount we need to retry, then dropping the
2597 // relevant lock, then actually sending, we would happily let multiple threads retry the same
2598 // amount at the same time, overpaying our original HTLC!
2599 let chanmon_cfgs = create_chanmon_cfgs(4);
2600 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2601 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2602 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2604 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2605 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2606 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2607 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2609 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2610 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2611 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2612 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2614 let amt_msat = 100_000_000;
2615 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2616 #[cfg(feature = "std")]
2617 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2618 #[cfg(not(feature = "std"))]
2619 let payment_expiry_secs = 60 * 60;
2620 let mut invoice_features = InvoiceFeatures::empty();
2621 invoice_features.set_variable_length_onion_required();
2622 invoice_features.set_payment_secret_required();
2623 invoice_features.set_basic_mpp_optional();
2624 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2625 .with_expiry_time(payment_expiry_secs as u64)
2626 .with_features(invoice_features);
2627 let mut route_params = RouteParameters {
2629 final_value_msat: amt_msat,
2632 let mut route = Route {
2635 pubkey: nodes[1].node.get_our_node_id(),
2636 node_features: nodes[1].node.node_features(),
2637 short_channel_id: chan_1_scid,
2638 channel_features: nodes[1].node.channel_features(),
2640 cltv_expiry_delta: 100,
2642 pubkey: nodes[3].node.get_our_node_id(),
2643 node_features: nodes[2].node.node_features(),
2644 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2645 channel_features: nodes[2].node.channel_features(),
2646 fee_msat: amt_msat / 1000,
2647 cltv_expiry_delta: 100,
2650 pubkey: nodes[2].node.get_our_node_id(),
2651 node_features: nodes[2].node.node_features(),
2652 short_channel_id: chan_3_scid,
2653 channel_features: nodes[2].node.channel_features(),
2655 cltv_expiry_delta: 100,
2657 pubkey: nodes[3].node.get_our_node_id(),
2658 node_features: nodes[3].node.node_features(),
2659 short_channel_id: chan_4_scid,
2660 channel_features: nodes[3].node.channel_features(),
2661 fee_msat: amt_msat - amt_msat / 1000,
2662 cltv_expiry_delta: 100,
2665 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2667 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2669 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
2670 check_added_monitors!(nodes[0], 2);
2671 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2672 assert_eq!(send_msg_events.len(), 2);
2673 send_msg_events.retain(|msg|
2674 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
2675 // Drop the commitment update for nodes[2], we can just let that one sit pending
2677 *node_id == nodes[1].node.get_our_node_id()
2678 } else { panic!(); }
2681 // from here on out, the retry `RouteParameters` amount will be amt/1000
2682 route_params.final_value_msat /= 1000;
2685 let end_time = Instant::now() + Duration::from_secs(1);
2686 macro_rules! thread_body { () => { {
2687 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
2688 let node_ref = NodePtr::from_node(&nodes[0]);
2690 let node_a = unsafe { &*node_ref.0 };
2691 while Instant::now() < end_time {
2692 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2693 // Ignore if we have any pending events, just always pretend we just got a
2694 // PendingHTLCsForwardable
2695 node_a.node.process_pending_htlc_forwards();
2699 let mut threads = Vec::new();
2700 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
2702 // Back in the main thread, poll pending messages and make sure that we never have more than
2703 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
2704 // there are HTLC messages shoved in while its running. This allows us to test that we never
2705 // generate an additional update_add_htlc until we've fully failed the first.
2706 let mut previously_failed_channels = Vec::new();
2708 assert_eq!(send_msg_events.len(), 1);
2709 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
2710 assert_eq!(send_event.msgs.len(), 1);
2712 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
2713 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
2715 // Note that we only push one route into `expect_find_route` at a time, because that's all
2716 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
2717 // we should still ultimately fail for the same reason - because we're trying to send too
2718 // many HTLCs at once.
2719 let mut new_route_params = route_params.clone();
2720 previously_failed_channels.push(route.paths[0][1].short_channel_id);
2721 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
2722 route.paths[0][1].short_channel_id += 1;
2723 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
2725 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2726 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
2727 // The "normal" commitment_signed_dance delivers the final RAA and then calls
2728 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
2729 // This races with our other threads which may generate an add-HTLCs commitment update via
2730 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
2731 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
2732 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
2733 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
2735 let cur_time = Instant::now();
2736 if cur_time > end_time {
2737 for thread in threads.drain(..) { thread.join().unwrap(); }
2740 // Make sure we have some events to handle when we go around...
2741 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2742 nodes[0].node.process_pending_htlc_forwards();
2743 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2744 check_added_monitors!(nodes[0], 2);
2746 if cur_time > end_time {
2752 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
2753 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
2754 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
2755 // it was last persisted.
2756 let chanmon_cfgs = create_chanmon_cfgs(2);
2757 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2758 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2759 let (persister_a, persister_b, persister_c);
2760 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
2761 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
2762 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2764 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2766 let mut nodes_0_serialized = Vec::new();
2767 if !persist_manager_with_payment {
2768 nodes_0_serialized = nodes[0].node.encode();
2771 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2773 if persist_manager_with_payment {
2774 nodes_0_serialized = nodes[0].node.encode();
2777 nodes[1].node.claim_funds(our_payment_preimage);
2778 check_added_monitors!(nodes[1], 1);
2779 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
2781 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2782 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2783 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
2784 check_added_monitors!(nodes[0], 1);
2786 // The ChannelMonitor should always be the latest version, as we're required to persist it
2787 // during the commitment signed handling.
2788 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2789 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
2791 let events = nodes[0].node.get_and_clear_pending_events();
2792 assert_eq!(events.len(), 2);
2793 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
2794 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
2795 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
2796 // the double-claim that would otherwise appear at the end of this test.
2797 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2798 assert_eq!(as_broadcasted_txn.len(), 1);
2800 // Ensure that, even after some time, if we restart we still include *something* in the current
2801 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
2802 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
2803 // A naive implementation of the fix here would wipe the pending payments set, causing a
2804 // failure event when we restart.
2805 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2807 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2808 reload_node!(nodes[0], test_default_channel_config(), &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister_b, chain_monitor_b, nodes_0_deserialized_b);
2809 let events = nodes[0].node.get_and_clear_pending_events();
2810 assert!(events.is_empty());
2812 // Ensure that we don't generate any further events even after the channel-closing commitment
2813 // transaction is confirmed on-chain.
2814 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
2815 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2817 let events = nodes[0].node.get_and_clear_pending_events();
2818 assert!(events.is_empty());
2820 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2821 reload_node!(nodes[0], test_default_channel_config(), &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister_c, chain_monitor_c, nodes_0_deserialized_c);
2822 let events = nodes[0].node.get_and_clear_pending_events();
2823 assert!(events.is_empty());
2827 fn no_missing_sent_on_midpoint_reload() {
2828 do_no_missing_sent_on_midpoint_reload(false);
2829 do_no_missing_sent_on_midpoint_reload(true);