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::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure};
19 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
20 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails, RecipientOnionFields};
21 use crate::ln::features::InvoiceFeatures;
23 use crate::ln::msgs::ChannelMessageHandler;
24 use crate::ln::outbound_payment::Retry;
25 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
26 use crate::routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RouteParameters};
27 use crate::routing::scoring::ChannelUsage;
28 use crate::util::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
31 use crate::util::string::UntrustedString;
33 use bitcoin::{Block, BlockHeader, TxMerkleNode};
34 use bitcoin::hashes::Hash;
35 use bitcoin::network::constants::Network;
37 use crate::prelude::*;
39 use crate::ln::functional_test_utils::*;
40 use crate::routing::gossip::NodeId;
41 #[cfg(feature = "std")]
43 crate::util::time::tests::SinceEpoch,
44 std::time::{SystemTime, Instant, Duration}
49 let chanmon_cfgs = create_chanmon_cfgs(4);
50 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
51 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
52 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
54 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
55 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
56 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
57 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
59 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
60 let path = route.paths[0].clone();
61 route.paths.push(path);
62 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
63 route.paths[0][0].short_channel_id = chan_1_id;
64 route.paths[0][1].short_channel_id = chan_3_id;
65 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
66 route.paths[1][0].short_channel_id = chan_2_id;
67 route.paths[1][1].short_channel_id = chan_4_id;
68 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
69 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
74 let chanmon_cfgs = create_chanmon_cfgs(4);
75 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
76 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
77 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
79 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
80 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
81 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
82 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
84 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
86 let amt_msat = 1_000_000;
87 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
88 let path = route.paths[0].clone();
89 route.paths.push(path);
90 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
91 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
92 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
93 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
94 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
95 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
97 // Initiate the MPP payment.
98 let payment_id = PaymentId(payment_hash.0);
99 let mut route_params = RouteParameters {
100 payment_params: route.payment_params.clone().unwrap(),
101 final_value_msat: amt_msat,
104 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
105 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
106 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
107 check_added_monitors!(nodes[0], 2); // one monitor per path
108 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
109 assert_eq!(events.len(), 2);
111 // Pass half of the payment along the success path.
112 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
113 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
115 // Add the HTLC along the first hop.
116 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
117 let (update_add, commitment_signed) = match fail_path_msgs_1 {
118 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 } } => {
119 assert_eq!(update_add_htlcs.len(), 1);
120 assert!(update_fail_htlcs.is_empty());
121 assert!(update_fulfill_htlcs.is_empty());
122 assert!(update_fail_malformed_htlcs.is_empty());
123 assert!(update_fee.is_none());
124 (update_add_htlcs[0].clone(), commitment_signed.clone())
126 _ => panic!("Unexpected event"),
128 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
129 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
131 // Attempt to forward the payment and complete the 2nd path's failure.
132 expect_pending_htlcs_forwardable!(&nodes[2]);
133 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 }]);
134 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
135 assert!(htlc_updates.update_add_htlcs.is_empty());
136 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
137 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
138 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
139 check_added_monitors!(nodes[2], 1);
140 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
141 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
142 let mut events = nodes[0].node.get_and_clear_pending_events();
144 Event::PendingHTLCsForwardable { .. } => {},
145 _ => panic!("Unexpected event")
148 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
150 // Rebalance the channel so the second half of the payment can succeed.
151 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
153 // Retry the second half of the payment and make sure it succeeds.
154 route.paths.remove(0);
155 route_params.final_value_msat = 1_000_000;
156 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
157 nodes[0].router.expect_find_route(route_params, Ok(route));
158 nodes[0].node.process_pending_htlc_forwards();
159 check_added_monitors!(nodes[0], 1);
160 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
161 assert_eq!(events.len(), 1);
162 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
163 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
166 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
167 let chanmon_cfgs = create_chanmon_cfgs(4);
168 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
169 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
170 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
172 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
173 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
174 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
175 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
177 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
178 let path = route.paths[0].clone();
179 route.paths.push(path);
180 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
181 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
182 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
183 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
184 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
185 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
187 // Initiate the MPP payment.
188 nodes[0].node.send_payment_with_route(&route, payment_hash,
189 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
190 check_added_monitors!(nodes[0], 2); // one monitor per path
191 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
192 assert_eq!(events.len(), 2);
194 // Pass half of the payment along the first path.
195 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
196 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
198 if send_partial_mpp {
199 // Time out the partial MPP
200 for _ in 0..MPP_TIMEOUT_TICKS {
201 nodes[3].node.timer_tick_occurred();
204 // Failed HTLC from node 3 -> 1
205 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
206 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
207 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
208 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
209 check_added_monitors!(nodes[3], 1);
210 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
212 // Failed HTLC from node 1 -> 0
213 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 }]);
214 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
215 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
216 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
217 check_added_monitors!(nodes[1], 1);
218 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
220 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
222 // Pass half of the payment along the second path.
223 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
224 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
226 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
227 for _ in 0..MPP_TIMEOUT_TICKS {
228 nodes[3].node.timer_tick_occurred();
231 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
236 fn mpp_receive_timeout() {
237 do_mpp_receive_timeout(true);
238 do_mpp_receive_timeout(false);
242 fn no_pending_leak_on_initial_send_failure() {
243 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
244 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
245 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
246 // pending payment forever and never time it out.
247 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
248 // try, and then check that no pending payment is being tracked.
249 let chanmon_cfgs = create_chanmon_cfgs(2);
250 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
251 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
252 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
254 create_announced_chan_between_nodes(&nodes, 0, 1);
256 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
258 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
259 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
261 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
262 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
263 ), true, APIError::ChannelUnavailable { ref err },
264 assert_eq!(err, "Peer for first hop currently disconnected"));
266 assert!(!nodes[0].node.has_pending_payments());
269 fn do_retry_with_no_persist(confirm_before_reload: bool) {
270 // If we send a pending payment and `send_payment` returns success, we should always either
271 // return a payment failure event or a payment success event, and on failure the payment should
274 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
275 // always persisted asynchronously), the ChannelManager has to reload some payment data from
276 // ChannelMonitor(s) in some cases. This tests that reloading.
278 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
279 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
280 // which has separate codepaths for "commitment transaction already confirmed" and not.
281 let chanmon_cfgs = create_chanmon_cfgs(3);
282 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
283 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
284 let persister: test_utils::TestPersister;
285 let new_chain_monitor: test_utils::TestChainMonitor;
286 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>;
287 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
289 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
290 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
292 // Serialize the ChannelManager prior to sending payments
293 let nodes_0_serialized = nodes[0].node.encode();
295 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
297 let amt_msat = 1_000_000;
298 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
299 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
300 let route_params = RouteParameters {
301 payment_params: route.payment_params.clone().unwrap(),
302 final_value_msat: amt_msat,
304 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
305 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
306 check_added_monitors!(nodes[0], 1);
308 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
309 assert_eq!(events.len(), 1);
310 let payment_event = SendEvent::from_event(events.pop().unwrap());
311 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
313 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
314 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
315 // which would prevent retry.
316 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
317 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
319 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
320 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
321 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
322 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
324 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
326 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
327 if confirm_before_reload {
328 mine_transaction(&nodes[0], &as_commitment_tx);
329 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
332 // The ChannelMonitor should always be the latest version, as we're required to persist it
333 // during the `commitment_signed_dance!()`.
334 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
335 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
337 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
338 // force-close the channel.
339 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
340 assert!(nodes[0].node.list_channels().is_empty());
341 assert!(nodes[0].node.has_pending_payments());
342 nodes[0].node.timer_tick_occurred();
343 if !confirm_before_reload {
344 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
345 assert_eq!(as_broadcasted_txn.len(), 1);
346 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
348 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
350 check_added_monitors!(nodes[0], 1);
352 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
353 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();
354 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
356 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
357 // error, as the channel has hit the chain.
358 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();
359 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
360 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
361 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
362 assert_eq!(as_err.len(), 1);
364 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
365 assert_eq!(node_id, nodes[1].node.get_our_node_id());
366 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
367 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", &nodes[1].node.get_our_node_id())) });
368 check_added_monitors!(nodes[1], 1);
369 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
371 _ => panic!("Unexpected event"),
373 check_closed_broadcast!(nodes[1], false);
375 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
376 // we close in a moment.
377 nodes[2].node.claim_funds(payment_preimage_1);
378 check_added_monitors!(nodes[2], 1);
379 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
381 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
382 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
383 check_added_monitors!(nodes[1], 1);
384 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
385 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
387 if confirm_before_reload {
388 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
389 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
392 // Create a new channel on which to retry the payment before we fail the payment via the
393 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
394 // connecting several blocks while creating the channel (implying time has passed).
395 create_announced_chan_between_nodes(&nodes, 0, 1);
396 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
398 mine_transaction(&nodes[1], &as_commitment_tx);
399 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
400 assert_eq!(bs_htlc_claim_txn.len(), 1);
401 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
403 if !confirm_before_reload {
404 mine_transaction(&nodes[0], &as_commitment_tx);
406 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
407 expect_payment_sent!(nodes[0], payment_preimage_1);
408 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
409 let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
410 assert_eq!(as_htlc_timeout_txn.len(), 2);
411 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1]);
412 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
413 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
414 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
415 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
417 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
419 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
420 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
422 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
423 // reloaded) via a route over the new channel, which work without issue and eventually be
424 // received and claimed at the recipient just like any other payment.
425 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
427 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
428 // and not the original fee. We also update node[1]'s relevant config as
429 // do_claim_payment_along_route expects us to never overpay.
431 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
432 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
433 .unwrap().lock().unwrap();
434 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
435 let mut new_config = channel.config();
436 new_config.forwarding_fee_base_msat += 100_000;
437 channel.update_config(&new_config);
438 new_route.paths[0][0].fee_msat += 100_000;
441 // Force expiration of the channel's previous config.
442 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
443 nodes[1].node.timer_tick_occurred();
446 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
447 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
448 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
449 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
450 check_added_monitors!(nodes[0], 1);
451 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
452 assert_eq!(events.len(), 1);
453 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
454 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
455 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
459 fn retry_with_no_persist() {
460 do_retry_with_no_persist(true);
461 do_retry_with_no_persist(false);
464 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
465 // Test that an off-chain completed payment is not retryable on restart. This was previously
466 // broken for dust payments, but we test for both dust and non-dust payments.
468 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
470 let chanmon_cfgs = create_chanmon_cfgs(3);
471 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
473 let mut manually_accept_config = test_default_channel_config();
474 manually_accept_config.manually_accept_inbound_channels = true;
476 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
478 let first_persister: test_utils::TestPersister;
479 let first_new_chain_monitor: test_utils::TestChainMonitor;
480 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>;
481 let second_persister: test_utils::TestPersister;
482 let second_new_chain_monitor: test_utils::TestChainMonitor;
483 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>;
484 let third_persister: test_utils::TestPersister;
485 let third_new_chain_monitor: test_utils::TestChainMonitor;
486 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>;
488 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
490 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
491 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
492 confirm_transaction(&nodes[0], &funding_tx);
493 confirm_transaction(&nodes[1], &funding_tx);
494 // Ignore the announcement_signatures messages
495 nodes[0].node.get_and_clear_pending_msg_events();
496 nodes[1].node.get_and_clear_pending_msg_events();
497 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
499 // Serialize the ChannelManager prior to sending payments
500 let mut nodes_0_serialized = nodes[0].node.encode();
502 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
503 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 });
505 // The ChannelMonitor should always be the latest version, as we're required to persist it
506 // during the `commitment_signed_dance!()`.
507 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
509 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);
510 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
512 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
513 // force-close the channel.
514 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
515 nodes[0].node.timer_tick_occurred();
516 assert!(nodes[0].node.list_channels().is_empty());
517 assert!(nodes[0].node.has_pending_payments());
518 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
519 check_added_monitors!(nodes[0], 1);
521 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();
522 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
524 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
525 // error, as the channel has hit the chain.
526 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();
527 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
528 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
529 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
530 assert_eq!(as_err.len(), 1);
531 let bs_commitment_tx;
533 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
534 assert_eq!(node_id, nodes[1].node.get_our_node_id());
535 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
536 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", &nodes[1].node.get_our_node_id())) });
537 check_added_monitors!(nodes[1], 1);
538 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
540 _ => panic!("Unexpected event"),
542 check_closed_broadcast!(nodes[1], false);
544 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
545 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
546 // incoming HTLCs with the same payment hash later.
547 nodes[2].node.fail_htlc_backwards(&payment_hash);
548 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
549 check_added_monitors!(nodes[2], 1);
551 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
552 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
553 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
554 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
555 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
557 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
558 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
559 // after the commitment transaction, so always connect the commitment transaction.
560 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
561 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
563 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
564 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
565 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
566 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
567 assert_eq!(as_htlc_timeout.len(), 1);
569 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
570 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
571 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
572 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
575 // Create a new channel on which to retry the payment before we fail the payment via the
576 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
577 // connecting several blocks while creating the channel (implying time has passed).
578 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
579 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
580 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
582 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
583 // confirming, we will fail as it's considered still-pending...
584 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
585 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
586 Err(PaymentSendFailure::DuplicatePayment) => {},
587 _ => panic!("Unexpected error")
589 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
591 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
592 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
593 // (which should also still work).
594 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
595 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
596 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
598 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
599 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
600 nodes_0_serialized = nodes[0].node.encode();
602 // After the payment failed, we're free to send it again.
603 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
604 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
605 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
607 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);
608 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
610 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
612 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
613 // the payment is not (spuriously) listed as still pending.
614 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
615 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
616 check_added_monitors!(nodes[0], 1);
617 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
618 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
620 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(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());
626 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
627 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
628 nodes_0_serialized = nodes[0].node.encode();
630 // Check that after reload we can send the payment again (though we shouldn't, since it was
631 // claimed previously).
632 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);
633 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
635 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
637 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
638 Err(PaymentSendFailure::DuplicatePayment) => {},
639 _ => panic!("Unexpected error")
641 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
645 fn test_completed_payment_not_retryable_on_reload() {
646 do_test_completed_payment_not_retryable_on_reload(true);
647 do_test_completed_payment_not_retryable_on_reload(false);
651 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
652 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
653 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
654 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
655 // the ChannelMonitor tells it to.
657 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
658 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
659 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
660 let chanmon_cfgs = create_chanmon_cfgs(2);
661 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
662 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
663 let persister: test_utils::TestPersister;
664 let new_chain_monitor: test_utils::TestChainMonitor;
665 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>;
666 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
668 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
670 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
672 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
673 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
674 check_closed_broadcast!(nodes[0], true);
675 check_added_monitors!(nodes[0], 1);
676 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
678 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
679 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
681 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
682 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
683 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
684 assert_eq!(node_txn.len(), 3);
685 assert_eq!(node_txn[0], node_txn[1]);
686 check_spends!(node_txn[1], funding_tx);
687 check_spends!(node_txn[2], node_txn[1]);
688 let timeout_txn = vec![node_txn[2].clone()];
690 nodes[1].node.claim_funds(payment_preimage);
691 check_added_monitors!(nodes[1], 1);
692 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
694 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
695 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
696 check_closed_broadcast!(nodes[1], true);
697 check_added_monitors!(nodes[1], 1);
698 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
699 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
700 assert_eq!(claim_txn.len(), 1);
701 check_spends!(claim_txn[0], node_txn[1]);
703 header.prev_blockhash = nodes[0].best_block_hash();
704 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
706 if confirm_commitment_tx {
707 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
710 header.prev_blockhash = nodes[0].best_block_hash();
711 let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
714 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
715 connect_block(&nodes[0], &claim_block);
716 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
719 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
720 // returning InProgress. This should cause the claim event to never make its way to the
722 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
723 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
726 connect_blocks(&nodes[0], 1);
728 connect_block(&nodes[0], &claim_block);
731 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
732 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
733 .get_mut(&funding_txo).unwrap().drain().collect();
734 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
735 // If we're testing connection idempotency we may get substantially more.
736 assert!(mon_updates.len() >= 1);
737 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
738 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
740 // If we persist the ChannelManager here, we should get the PaymentSent event after
742 let mut chan_manager_serialized = Vec::new();
743 if !persist_manager_post_event {
744 chan_manager_serialized = nodes[0].node.encode();
747 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
748 // payment sent event.
749 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
750 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
751 for update in mon_updates {
752 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
755 expect_payment_failed!(nodes[0], payment_hash, false);
757 expect_payment_sent!(nodes[0], payment_preimage);
760 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
762 if persist_manager_post_event {
763 chan_manager_serialized = nodes[0].node.encode();
766 // Now reload nodes[0]...
767 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
769 if persist_manager_post_event {
770 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
771 } else if payment_timeout {
772 expect_payment_failed!(nodes[0], payment_hash, false);
774 expect_payment_sent!(nodes[0], payment_preimage);
777 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
778 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
779 // payment events should kick in, leaving us with no pending events here.
780 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
781 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
782 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
786 fn test_dup_htlc_onchain_fails_on_reload() {
787 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
788 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
789 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
790 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
791 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
792 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
796 fn test_fulfill_restart_failure() {
797 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
798 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
799 // again, or fail it, giving us free money.
801 // Of course probably they won't fail it and give us free money, but because we have code to
802 // handle it, we should test the logic for it anyway. We do that here.
803 let chanmon_cfgs = create_chanmon_cfgs(2);
804 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
805 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
806 let persister: test_utils::TestPersister;
807 let new_chain_monitor: test_utils::TestChainMonitor;
808 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>;
809 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
811 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
812 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
814 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
815 // pre-fulfill, which we do by serializing it here.
816 let chan_manager_serialized = nodes[1].node.encode();
817 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
819 nodes[1].node.claim_funds(payment_preimage);
820 check_added_monitors!(nodes[1], 1);
821 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
823 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
824 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
825 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
827 // Now reload nodes[1]...
828 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
830 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
831 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
833 nodes[1].node.fail_htlc_backwards(&payment_hash);
834 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
835 check_added_monitors!(nodes[1], 1);
836 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
837 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
838 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
839 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
840 // it had already considered the payment fulfilled, and now they just got free money.
841 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
845 fn get_ldk_payment_preimage() {
846 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
847 let chanmon_cfgs = create_chanmon_cfgs(2);
848 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
849 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
850 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
851 create_announced_chan_between_nodes(&nodes, 0, 1);
853 let amt_msat = 60_000;
854 let expiry_secs = 60 * 60;
855 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
857 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
858 .with_features(nodes[1].node.invoice_features());
859 let scorer = test_utils::TestScorer::new();
860 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
861 let random_seed_bytes = keys_manager.get_secure_random_bytes();
862 let route = get_route(
863 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
864 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
865 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
866 nodes[0].node.send_payment_with_route(&route, payment_hash,
867 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
868 check_added_monitors!(nodes[0], 1);
870 // Make sure to use `get_payment_preimage`
871 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
872 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
873 assert_eq!(events.len(), 1);
874 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
875 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
879 fn sent_probe_is_probe_of_sending_node() {
880 let chanmon_cfgs = create_chanmon_cfgs(3);
881 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
882 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
883 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
885 create_announced_chan_between_nodes(&nodes, 0, 1);
886 create_announced_chan_between_nodes(&nodes, 1, 2);
888 // First check we refuse to build a single-hop probe
889 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
890 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
892 // Then build an actual two-hop probing path
893 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
895 match nodes[0].node.send_probe(route.paths[0].clone()) {
896 Ok((payment_hash, payment_id)) => {
897 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
898 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
899 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
904 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
905 check_added_monitors!(nodes[0], 1);
909 fn successful_probe_yields_event() {
910 let chanmon_cfgs = create_chanmon_cfgs(3);
911 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
912 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
913 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
915 create_announced_chan_between_nodes(&nodes, 0, 1);
916 create_announced_chan_between_nodes(&nodes, 1, 2);
918 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
920 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
922 // node[0] -- update_add_htlcs -> node[1]
923 check_added_monitors!(nodes[0], 1);
924 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
925 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
926 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
927 check_added_monitors!(nodes[1], 0);
928 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
929 expect_pending_htlcs_forwardable!(nodes[1]);
931 // node[1] -- update_add_htlcs -> node[2]
932 check_added_monitors!(nodes[1], 1);
933 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
934 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
935 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
936 check_added_monitors!(nodes[2], 0);
937 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
939 // node[1] <- update_fail_htlcs -- node[2]
940 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
941 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
942 check_added_monitors!(nodes[1], 0);
943 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
945 // node[0] <- update_fail_htlcs -- node[1]
946 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
947 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
948 check_added_monitors!(nodes[0], 0);
949 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
951 let mut events = nodes[0].node.get_and_clear_pending_events();
952 assert_eq!(events.len(), 1);
953 match events.drain(..).next().unwrap() {
954 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
955 assert_eq!(payment_id, ev_pid);
956 assert_eq!(payment_hash, ev_ph);
960 assert!(!nodes[0].node.has_pending_payments());
964 fn failed_probe_yields_event() {
965 let chanmon_cfgs = create_chanmon_cfgs(3);
966 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
967 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
968 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
970 create_announced_chan_between_nodes(&nodes, 0, 1);
971 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
973 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
975 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
977 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
979 // node[0] -- update_add_htlcs -> node[1]
980 check_added_monitors!(nodes[0], 1);
981 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
982 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
983 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
984 check_added_monitors!(nodes[1], 0);
985 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
986 expect_pending_htlcs_forwardable!(nodes[1]);
988 // node[0] <- update_fail_htlcs -- node[1]
989 check_added_monitors!(nodes[1], 1);
990 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
991 // Skip the PendingHTLCsForwardable event
992 let _events = nodes[1].node.get_and_clear_pending_events();
993 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
994 check_added_monitors!(nodes[0], 0);
995 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
997 let mut events = nodes[0].node.get_and_clear_pending_events();
998 assert_eq!(events.len(), 1);
999 match events.drain(..).next().unwrap() {
1000 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1001 assert_eq!(payment_id, ev_pid);
1002 assert_eq!(payment_hash, ev_ph);
1006 assert!(!nodes[0].node.has_pending_payments());
1010 fn onchain_failed_probe_yields_event() {
1011 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1013 let chanmon_cfgs = create_chanmon_cfgs(3);
1014 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1015 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1016 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1018 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1019 create_announced_chan_between_nodes(&nodes, 1, 2);
1021 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1023 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1024 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1025 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1027 // node[0] -- update_add_htlcs -> node[1]
1028 check_added_monitors!(nodes[0], 1);
1029 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1030 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1031 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1032 check_added_monitors!(nodes[1], 0);
1033 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1034 expect_pending_htlcs_forwardable!(nodes[1]);
1036 check_added_monitors!(nodes[1], 1);
1037 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1039 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1040 // Node A, which after 6 confirmations should result in a probe failure event.
1041 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1042 confirm_transaction(&nodes[0], &bs_txn[0]);
1043 check_closed_broadcast!(&nodes[0], true);
1044 check_added_monitors!(nodes[0], 1);
1046 let mut events = nodes[0].node.get_and_clear_pending_events();
1047 assert_eq!(events.len(), 2);
1048 let mut found_probe_failed = false;
1049 for event in events.drain(..) {
1051 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1052 assert_eq!(payment_id, ev_pid);
1053 assert_eq!(payment_hash, ev_ph);
1054 found_probe_failed = true;
1056 Event::ChannelClosed { .. } => {},
1060 assert!(found_probe_failed);
1061 assert!(!nodes[0].node.has_pending_payments());
1065 fn claimed_send_payment_idempotent() {
1066 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1067 let chanmon_cfgs = create_chanmon_cfgs(2);
1068 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1069 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1070 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1072 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1074 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1075 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1077 macro_rules! check_send_rejected {
1079 // If we try to resend a new payment with a different payment_hash but with the same
1080 // payment_id, it should be rejected.
1081 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1082 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1084 Err(PaymentSendFailure::DuplicatePayment) => {},
1085 _ => panic!("Unexpected send result: {:?}", send_result),
1088 // Further, if we try to send a spontaneous payment with the same payment_id it should
1089 // also be rejected.
1090 let send_result = nodes[0].node.send_spontaneous_payment(
1091 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1093 Err(PaymentSendFailure::DuplicatePayment) => {},
1094 _ => panic!("Unexpected send result: {:?}", send_result),
1099 check_send_rejected!();
1101 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1102 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1103 // we must remain just as idempotent as we were before.
1104 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1106 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1107 nodes[0].node.timer_tick_occurred();
1110 check_send_rejected!();
1112 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1113 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1114 // the payment complete. However, they could have called `send_payment` while the event was
1115 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1116 // after the event is handled a duplicate payment should sitll be rejected.
1117 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1118 check_send_rejected!();
1120 // If relatively little time has passed, a duplicate payment should still fail.
1121 nodes[0].node.timer_tick_occurred();
1122 check_send_rejected!();
1124 // However, after some time has passed (at least more than the one timer tick above), a
1125 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1126 // references to the old payment data.
1127 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1128 nodes[0].node.timer_tick_occurred();
1131 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1132 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1133 check_added_monitors!(nodes[0], 1);
1134 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1135 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1139 fn abandoned_send_payment_idempotent() {
1140 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1142 let chanmon_cfgs = create_chanmon_cfgs(2);
1143 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1144 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1145 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1147 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1149 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1150 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1152 macro_rules! check_send_rejected {
1154 // If we try to resend a new payment with a different payment_hash but with the same
1155 // payment_id, it should be rejected.
1156 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1157 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1159 Err(PaymentSendFailure::DuplicatePayment) => {},
1160 _ => panic!("Unexpected send result: {:?}", send_result),
1163 // Further, if we try to send a spontaneous payment with the same payment_id it should
1164 // also be rejected.
1165 let send_result = nodes[0].node.send_spontaneous_payment(
1166 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1168 Err(PaymentSendFailure::DuplicatePayment) => {},
1169 _ => panic!("Unexpected send result: {:?}", send_result),
1174 check_send_rejected!();
1176 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1177 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1179 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1181 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1182 nodes[0].node.timer_tick_occurred();
1184 check_send_rejected!();
1186 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash);
1188 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1189 // failed payment back.
1190 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1191 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1192 check_added_monitors!(nodes[0], 1);
1193 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1194 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1197 #[derive(PartialEq)]
1198 enum InterceptTest {
1205 fn test_trivial_inflight_htlc_tracking(){
1206 // In this test, we test three scenarios:
1207 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1208 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1209 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1210 let chanmon_cfgs = create_chanmon_cfgs(3);
1211 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1212 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1213 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1215 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1216 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1218 // Send and claim the payment. Inflight HTLCs should be empty.
1219 let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1220 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1222 let mut node_0_per_peer_lock;
1223 let mut node_0_peer_state_lock;
1224 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1226 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1227 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1228 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1229 channel_1.get_short_channel_id().unwrap()
1231 assert_eq!(chan_1_used_liquidity, None);
1234 let mut node_1_per_peer_lock;
1235 let mut node_1_peer_state_lock;
1236 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1238 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1239 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1240 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1241 channel_2.get_short_channel_id().unwrap()
1244 assert_eq!(chan_2_used_liquidity, None);
1246 let pending_payments = nodes[0].node.list_recent_payments();
1247 assert_eq!(pending_payments.len(), 1);
1248 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1250 // Remove fulfilled payment
1251 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1252 nodes[0].node.timer_tick_occurred();
1255 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1256 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1257 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1259 let mut node_0_per_peer_lock;
1260 let mut node_0_peer_state_lock;
1261 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1263 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1264 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1265 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1266 channel_1.get_short_channel_id().unwrap()
1268 // First hop accounts for expected 1000 msat fee
1269 assert_eq!(chan_1_used_liquidity, Some(501000));
1272 let mut node_1_per_peer_lock;
1273 let mut node_1_peer_state_lock;
1274 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1276 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1277 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1278 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1279 channel_2.get_short_channel_id().unwrap()
1282 assert_eq!(chan_2_used_liquidity, Some(500000));
1284 let pending_payments = nodes[0].node.list_recent_payments();
1285 assert_eq!(pending_payments.len(), 1);
1286 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1288 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1289 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1291 // Remove fulfilled payment
1292 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1293 nodes[0].node.timer_tick_occurred();
1296 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1298 let mut node_0_per_peer_lock;
1299 let mut node_0_peer_state_lock;
1300 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1302 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1303 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1304 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1305 channel_1.get_short_channel_id().unwrap()
1307 assert_eq!(chan_1_used_liquidity, None);
1310 let mut node_1_per_peer_lock;
1311 let mut node_1_peer_state_lock;
1312 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1314 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1315 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1316 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1317 channel_2.get_short_channel_id().unwrap()
1319 assert_eq!(chan_2_used_liquidity, None);
1322 let pending_payments = nodes[0].node.list_recent_payments();
1323 assert_eq!(pending_payments.len(), 0);
1327 fn test_holding_cell_inflight_htlcs() {
1328 let chanmon_cfgs = create_chanmon_cfgs(2);
1329 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1330 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1331 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1332 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1334 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1335 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1337 // Queue up two payments - one will be delivered right away, one immediately goes into the
1338 // holding cell as nodes[0] is AwaitingRAA.
1340 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1341 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1342 check_added_monitors!(nodes[0], 1);
1343 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1344 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1345 check_added_monitors!(nodes[0], 0);
1348 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1351 let mut node_0_per_peer_lock;
1352 let mut node_0_peer_state_lock;
1353 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1355 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1356 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1357 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1358 channel.get_short_channel_id().unwrap()
1361 assert_eq!(used_liquidity, Some(2000000));
1364 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1365 nodes[0].node.get_and_clear_pending_msg_events();
1369 fn intercepted_payment() {
1370 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1371 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1372 // payment or (b) fail the payment.
1373 do_test_intercepted_payment(InterceptTest::Forward);
1374 do_test_intercepted_payment(InterceptTest::Fail);
1375 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1376 do_test_intercepted_payment(InterceptTest::Timeout);
1379 fn do_test_intercepted_payment(test: InterceptTest) {
1380 let chanmon_cfgs = create_chanmon_cfgs(3);
1381 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1383 let mut zero_conf_chan_config = test_default_channel_config();
1384 zero_conf_chan_config.manually_accept_inbound_channels = true;
1385 let mut intercept_forwards_config = test_default_channel_config();
1386 intercept_forwards_config.accept_intercept_htlcs = true;
1387 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1389 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1390 let scorer = test_utils::TestScorer::new();
1391 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1393 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1395 let amt_msat = 100_000;
1396 let intercept_scid = nodes[1].node.get_intercept_scid();
1397 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1398 .with_route_hints(vec![
1399 RouteHint(vec![RouteHintHop {
1400 src_node_id: nodes[1].node.get_our_node_id(),
1401 short_channel_id: intercept_scid,
1404 proportional_millionths: 0,
1406 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1407 htlc_minimum_msat: None,
1408 htlc_maximum_msat: None,
1411 .with_features(nodes[2].node.invoice_features());
1412 let route_params = RouteParameters {
1414 final_value_msat: amt_msat,
1416 let route = get_route(
1417 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1418 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1419 route_params.payment_params.final_cltv_expiry_delta, nodes[0].logger, &scorer,
1423 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1424 nodes[0].node.send_payment_with_route(&route, payment_hash,
1425 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1426 let payment_event = {
1428 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1429 assert_eq!(added_monitors.len(), 1);
1430 added_monitors.clear();
1432 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1433 assert_eq!(events.len(), 1);
1434 SendEvent::from_event(events.remove(0))
1436 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1437 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1439 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1440 let events = nodes[1].node.get_and_clear_pending_events();
1441 assert_eq!(events.len(), 1);
1442 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1443 crate::events::Event::HTLCIntercepted {
1444 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1446 assert_eq!(pmt_hash, payment_hash);
1447 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1448 assert_eq!(short_channel_id, intercept_scid);
1449 (intercept_id, expected_outbound_amount_msat)
1454 // Check for unknown channel id error.
1455 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();
1456 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()) });
1458 if test == InterceptTest::Fail {
1459 // Ensure we can fail the intercepted payment back.
1460 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1461 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1462 nodes[1].node.process_pending_htlc_forwards();
1463 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1464 check_added_monitors!(&nodes[1], 1);
1465 assert!(update_fail.update_fail_htlcs.len() == 1);
1466 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1467 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1468 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1470 // Ensure the payment fails with the expected error.
1471 let fail_conditions = PaymentFailedConditions::new()
1472 .blamed_scid(intercept_scid)
1473 .blamed_chan_closed(true)
1474 .expected_htlc_error_data(0x4000 | 10, &[]);
1475 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1476 } else if test == InterceptTest::Forward {
1477 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1478 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1479 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();
1480 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1481 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1483 // Open the just-in-time channel so the payment can then be forwarded.
1484 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1486 // Finally, forward the intercepted payment through and claim it.
1487 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1488 expect_pending_htlcs_forwardable!(nodes[1]);
1490 let payment_event = {
1492 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1493 assert_eq!(added_monitors.len(), 1);
1494 added_monitors.clear();
1496 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1497 assert_eq!(events.len(), 1);
1498 SendEvent::from_event(events.remove(0))
1500 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1501 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1502 expect_pending_htlcs_forwardable!(nodes[2]);
1504 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1505 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1506 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1507 let events = nodes[0].node.get_and_clear_pending_events();
1508 assert_eq!(events.len(), 2);
1510 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1511 assert_eq!(payment_preimage, *ev_preimage);
1512 assert_eq!(payment_hash, *ev_hash);
1513 assert_eq!(fee_paid_msat, &Some(1000));
1515 _ => panic!("Unexpected event")
1518 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1519 assert_eq!(hash, Some(payment_hash));
1521 _ => panic!("Unexpected event")
1523 } else if test == InterceptTest::Timeout {
1524 let mut block = Block {
1525 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1528 connect_block(&nodes[0], &block);
1529 connect_block(&nodes[1], &block);
1530 for _ in 0..TEST_FINAL_CLTV {
1531 block.header.prev_blockhash = block.block_hash();
1532 connect_block(&nodes[0], &block);
1533 connect_block(&nodes[1], &block);
1535 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1536 check_added_monitors!(nodes[1], 1);
1537 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1538 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1539 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1540 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1541 assert!(htlc_timeout_updates.update_fee.is_none());
1543 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1544 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1545 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1547 // Check for unknown intercept id error.
1548 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1549 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();
1550 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1551 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1552 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1556 #[derive(PartialEq)]
1567 fn automatic_retries() {
1568 do_automatic_retries(AutoRetry::Success);
1569 do_automatic_retries(AutoRetry::Spontaneous);
1570 do_automatic_retries(AutoRetry::FailAttempts);
1571 do_automatic_retries(AutoRetry::FailTimeout);
1572 do_automatic_retries(AutoRetry::FailOnRestart);
1573 do_automatic_retries(AutoRetry::FailOnRetry);
1575 fn do_automatic_retries(test: AutoRetry) {
1576 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1578 let chanmon_cfgs = create_chanmon_cfgs(3);
1579 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1580 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1583 let new_chain_monitor;
1584 let node_0_deserialized;
1586 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1587 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1588 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1590 // Marshall data to send the payment
1591 #[cfg(feature = "std")]
1592 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1593 #[cfg(not(feature = "std"))]
1594 let payment_expiry_secs = 60 * 60;
1595 let amt_msat = 1000;
1596 let mut invoice_features = InvoiceFeatures::empty();
1597 invoice_features.set_variable_length_onion_required();
1598 invoice_features.set_payment_secret_required();
1599 invoice_features.set_basic_mpp_optional();
1600 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1601 .with_expiry_time(payment_expiry_secs as u64)
1602 .with_features(invoice_features);
1603 let route_params = RouteParameters {
1605 final_value_msat: amt_msat,
1607 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1609 macro_rules! pass_failed_attempt_with_retry_along_path {
1610 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1611 // Send a payment attempt that fails due to lack of liquidity on the second hop
1612 check_added_monitors!(nodes[0], 1);
1613 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1614 let mut update_add = update_0.update_add_htlcs[0].clone();
1615 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1616 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1617 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1618 nodes[1].node.process_pending_htlc_forwards();
1619 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1620 vec![HTLCDestination::NextHopChannel {
1621 node_id: Some(nodes[2].node.get_our_node_id()),
1622 channel_id: $failing_channel_id,
1624 nodes[1].node.process_pending_htlc_forwards();
1625 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1626 check_added_monitors!(&nodes[1], 1);
1627 assert!(update_1.update_fail_htlcs.len() == 1);
1628 let fail_msg = update_1.update_fail_htlcs[0].clone();
1629 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1630 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1632 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1633 let mut events = nodes[0].node.get_and_clear_pending_events();
1634 assert_eq!(events.len(), 2);
1636 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1637 assert_eq!(payment_hash, ev_payment_hash);
1638 assert_eq!(payment_failed_permanently, false);
1640 _ => panic!("Unexpected event"),
1642 if $expect_pending_htlcs_forwardable {
1644 Event::PendingHTLCsForwardable { .. } => {},
1645 _ => panic!("Unexpected event"),
1649 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1650 assert_eq!(payment_hash, ev_payment_hash);
1652 _ => panic!("Unexpected event"),
1658 if test == AutoRetry::Success {
1659 // Test that we can succeed on the first retry.
1660 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1661 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1662 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1664 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1665 // attempt, since the initial second hop channel will be excluded from pathfinding
1666 create_announced_chan_between_nodes(&nodes, 1, 2);
1668 // We retry payments in `process_pending_htlc_forwards`
1669 nodes[0].node.process_pending_htlc_forwards();
1670 check_added_monitors!(nodes[0], 1);
1671 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1672 assert_eq!(msg_events.len(), 1);
1673 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1674 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1675 } else if test == AutoRetry::Spontaneous {
1676 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
1677 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
1678 Retry::Attempts(1)).unwrap();
1679 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1681 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1682 // attempt, since the initial second hop channel will be excluded from pathfinding
1683 create_announced_chan_between_nodes(&nodes, 1, 2);
1685 // We retry payments in `process_pending_htlc_forwards`
1686 nodes[0].node.process_pending_htlc_forwards();
1687 check_added_monitors!(nodes[0], 1);
1688 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1689 assert_eq!(msg_events.len(), 1);
1690 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1691 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1692 } else if test == AutoRetry::FailAttempts {
1693 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1694 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1695 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1696 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1698 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1699 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1700 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1702 // We retry payments in `process_pending_htlc_forwards`
1703 nodes[0].node.process_pending_htlc_forwards();
1704 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1706 // Ensure we won't retry a second time.
1707 nodes[0].node.process_pending_htlc_forwards();
1708 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1709 assert_eq!(msg_events.len(), 0);
1710 } else if test == AutoRetry::FailTimeout {
1711 #[cfg(not(feature = "no-std"))] {
1712 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1713 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1714 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
1715 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1717 // Advance the time so the second attempt fails due to timeout.
1718 SinceEpoch::advance(Duration::from_secs(61));
1720 // Make sure we don't retry again.
1721 nodes[0].node.process_pending_htlc_forwards();
1722 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1723 assert_eq!(msg_events.len(), 0);
1725 let mut events = nodes[0].node.get_and_clear_pending_events();
1726 assert_eq!(events.len(), 1);
1728 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1729 assert_eq!(payment_hash, *ev_payment_hash);
1730 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1732 _ => panic!("Unexpected event"),
1735 } else if test == AutoRetry::FailOnRestart {
1736 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1737 // attempts remaining prior to restart.
1738 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1739 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1740 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1742 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1743 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1744 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1746 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1747 nodes[0].node.process_pending_htlc_forwards();
1748 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1750 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1751 let node_encoded = nodes[0].node.encode();
1752 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1753 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1755 let mut events = nodes[0].node.get_and_clear_pending_events();
1756 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
1757 // Make sure we don't retry again.
1758 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1759 assert_eq!(msg_events.len(), 0);
1761 let mut events = nodes[0].node.get_and_clear_pending_events();
1762 assert_eq!(events.len(), 1);
1764 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1765 assert_eq!(payment_hash, *ev_payment_hash);
1766 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1768 _ => panic!("Unexpected event"),
1770 } else if test == AutoRetry::FailOnRetry {
1771 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1772 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1773 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1775 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1776 // fail to find a route.
1777 nodes[0].node.process_pending_htlc_forwards();
1778 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1779 assert_eq!(msg_events.len(), 0);
1781 let mut events = nodes[0].node.get_and_clear_pending_events();
1782 assert_eq!(events.len(), 1);
1784 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1785 assert_eq!(payment_hash, *ev_payment_hash);
1786 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1788 _ => panic!("Unexpected event"),
1794 fn auto_retry_partial_failure() {
1795 // Test that we'll retry appropriately on send partial failure and retry partial failure.
1796 let chanmon_cfgs = create_chanmon_cfgs(2);
1797 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1798 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1799 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1801 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1802 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1803 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1805 // Marshall data to send the payment
1806 let amt_msat = 20_000;
1807 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1808 #[cfg(feature = "std")]
1809 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1810 #[cfg(not(feature = "std"))]
1811 let payment_expiry_secs = 60 * 60;
1812 let mut invoice_features = InvoiceFeatures::empty();
1813 invoice_features.set_variable_length_onion_required();
1814 invoice_features.set_payment_secret_required();
1815 invoice_features.set_basic_mpp_optional();
1816 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1817 .with_expiry_time(payment_expiry_secs as u64)
1818 .with_features(invoice_features);
1819 let route_params = RouteParameters {
1821 final_value_msat: amt_msat,
1824 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1825 // second (for the initial send path2 over chan_2) fails.
1826 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1827 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1828 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1829 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1830 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1831 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1832 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1834 // Configure the initial send, retry1 and retry2's paths.
1835 let send_route = Route {
1838 pubkey: nodes[1].node.get_our_node_id(),
1839 node_features: nodes[1].node.node_features(),
1840 short_channel_id: chan_1_id,
1841 channel_features: nodes[1].node.channel_features(),
1842 fee_msat: amt_msat / 2,
1843 cltv_expiry_delta: 100,
1846 pubkey: nodes[1].node.get_our_node_id(),
1847 node_features: nodes[1].node.node_features(),
1848 short_channel_id: chan_2_id,
1849 channel_features: nodes[1].node.channel_features(),
1850 fee_msat: amt_msat / 2,
1851 cltv_expiry_delta: 100,
1854 payment_params: Some(route_params.payment_params.clone()),
1856 let retry_1_route = Route {
1859 pubkey: nodes[1].node.get_our_node_id(),
1860 node_features: nodes[1].node.node_features(),
1861 short_channel_id: chan_1_id,
1862 channel_features: nodes[1].node.channel_features(),
1863 fee_msat: amt_msat / 4,
1864 cltv_expiry_delta: 100,
1867 pubkey: nodes[1].node.get_our_node_id(),
1868 node_features: nodes[1].node.node_features(),
1869 short_channel_id: chan_3_id,
1870 channel_features: nodes[1].node.channel_features(),
1871 fee_msat: amt_msat / 4,
1872 cltv_expiry_delta: 100,
1875 payment_params: Some(route_params.payment_params.clone()),
1877 let retry_2_route = Route {
1880 pubkey: nodes[1].node.get_our_node_id(),
1881 node_features: nodes[1].node.node_features(),
1882 short_channel_id: chan_1_id,
1883 channel_features: nodes[1].node.channel_features(),
1884 fee_msat: amt_msat / 4,
1885 cltv_expiry_delta: 100,
1888 payment_params: Some(route_params.payment_params.clone()),
1890 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1891 let mut payment_params = route_params.payment_params.clone();
1892 payment_params.previously_failed_channels.push(chan_2_id);
1893 nodes[0].router.expect_find_route(RouteParameters {
1894 payment_params, final_value_msat: amt_msat / 2,
1895 }, Ok(retry_1_route));
1896 let mut payment_params = route_params.payment_params.clone();
1897 payment_params.previously_failed_channels.push(chan_3_id);
1898 nodes[0].router.expect_find_route(RouteParameters {
1899 payment_params, final_value_msat: amt_msat / 4,
1900 }, Ok(retry_2_route));
1902 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1903 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1904 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1905 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1906 assert_eq!(closed_chan_events.len(), 4);
1907 match closed_chan_events[0] {
1908 Event::ChannelClosed { .. } => {},
1909 _ => panic!("Unexpected event"),
1911 match closed_chan_events[1] {
1912 Event::PaymentPathFailed { .. } => {},
1913 _ => panic!("Unexpected event"),
1915 match closed_chan_events[2] {
1916 Event::ChannelClosed { .. } => {},
1917 _ => panic!("Unexpected event"),
1919 match closed_chan_events[3] {
1920 Event::PaymentPathFailed { .. } => {},
1921 _ => panic!("Unexpected event"),
1924 // Pass the first part of the payment along the path.
1925 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1926 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1928 // First message is the first update_add, remaining messages are broadcasting channel updates and
1929 // errors for the permfailed channels
1930 assert_eq!(msg_events.len(), 5);
1931 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1933 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1934 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1935 check_added_monitors!(nodes[1], 1);
1936 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1938 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1939 check_added_monitors!(nodes[0], 1);
1940 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1942 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1943 check_added_monitors!(nodes[0], 1);
1944 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1946 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1947 check_added_monitors!(nodes[1], 1);
1949 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1950 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1951 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1952 check_added_monitors!(nodes[1], 1);
1953 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1955 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1956 check_added_monitors!(nodes[0], 1);
1958 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
1959 check_added_monitors!(nodes[0], 1);
1960 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1962 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1963 check_added_monitors!(nodes[1], 1);
1965 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1966 nodes[1].node.process_pending_htlc_forwards();
1967 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
1968 nodes[1].node.claim_funds(payment_preimage);
1969 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
1970 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1971 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
1973 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
1974 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
1975 check_added_monitors!(nodes[0], 1);
1976 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1978 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1979 check_added_monitors!(nodes[1], 4);
1980 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1982 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1983 check_added_monitors!(nodes[1], 1);
1984 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1986 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1987 check_added_monitors!(nodes[0], 1);
1989 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
1990 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
1991 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
1992 check_added_monitors!(nodes[0], 1);
1993 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1995 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
1996 check_added_monitors!(nodes[1], 1);
1998 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1999 check_added_monitors!(nodes[1], 1);
2000 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2002 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2003 check_added_monitors!(nodes[0], 1);
2004 expect_payment_sent!(nodes[0], payment_preimage);
2008 fn auto_retry_zero_attempts_send_error() {
2009 let chanmon_cfgs = create_chanmon_cfgs(2);
2010 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2011 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2012 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2014 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2015 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2017 // Marshall data to send the payment
2018 let amt_msat = 20_000;
2019 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2020 #[cfg(feature = "std")]
2021 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2022 #[cfg(not(feature = "std"))]
2023 let payment_expiry_secs = 60 * 60;
2024 let mut invoice_features = InvoiceFeatures::empty();
2025 invoice_features.set_variable_length_onion_required();
2026 invoice_features.set_payment_secret_required();
2027 invoice_features.set_basic_mpp_optional();
2028 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2029 .with_expiry_time(payment_expiry_secs as u64)
2030 .with_features(invoice_features);
2031 let route_params = RouteParameters {
2033 final_value_msat: amt_msat,
2036 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2037 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2038 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2039 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2040 let events = nodes[0].node.get_and_clear_pending_events();
2041 assert_eq!(events.len(), 3);
2042 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2043 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2044 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2045 check_added_monitors!(nodes[0], 2);
2049 fn fails_paying_after_rejected_by_payee() {
2050 let chanmon_cfgs = create_chanmon_cfgs(2);
2051 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2052 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2053 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2055 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2057 // Marshall data to send the payment
2058 let amt_msat = 20_000;
2059 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2060 #[cfg(feature = "std")]
2061 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2062 #[cfg(not(feature = "std"))]
2063 let payment_expiry_secs = 60 * 60;
2064 let mut invoice_features = InvoiceFeatures::empty();
2065 invoice_features.set_variable_length_onion_required();
2066 invoice_features.set_payment_secret_required();
2067 invoice_features.set_basic_mpp_optional();
2068 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2069 .with_expiry_time(payment_expiry_secs as u64)
2070 .with_features(invoice_features);
2071 let route_params = RouteParameters {
2073 final_value_msat: amt_msat,
2076 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2077 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2078 check_added_monitors!(nodes[0], 1);
2079 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2080 assert_eq!(events.len(), 1);
2081 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2082 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2083 check_added_monitors!(nodes[1], 0);
2084 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2085 expect_pending_htlcs_forwardable!(nodes[1]);
2086 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2088 nodes[1].node.fail_htlc_backwards(&payment_hash);
2089 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2090 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash);
2094 fn retry_multi_path_single_failed_payment() {
2095 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2096 let chanmon_cfgs = create_chanmon_cfgs(2);
2097 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2098 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2099 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2101 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2102 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2104 let amt_msat = 100_010_000;
2106 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2107 #[cfg(feature = "std")]
2108 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2109 #[cfg(not(feature = "std"))]
2110 let payment_expiry_secs = 60 * 60;
2111 let mut invoice_features = InvoiceFeatures::empty();
2112 invoice_features.set_variable_length_onion_required();
2113 invoice_features.set_payment_secret_required();
2114 invoice_features.set_basic_mpp_optional();
2115 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2116 .with_expiry_time(payment_expiry_secs as u64)
2117 .with_features(invoice_features);
2118 let route_params = RouteParameters {
2119 payment_params: payment_params.clone(),
2120 final_value_msat: amt_msat,
2123 let chans = nodes[0].node.list_usable_channels();
2124 let mut route = Route {
2127 pubkey: nodes[1].node.get_our_node_id(),
2128 node_features: nodes[1].node.node_features(),
2129 short_channel_id: chans[0].short_channel_id.unwrap(),
2130 channel_features: nodes[1].node.channel_features(),
2132 cltv_expiry_delta: 100,
2135 pubkey: nodes[1].node.get_our_node_id(),
2136 node_features: nodes[1].node.node_features(),
2137 short_channel_id: chans[1].short_channel_id.unwrap(),
2138 channel_features: nodes[1].node.channel_features(),
2139 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2140 cltv_expiry_delta: 100,
2143 payment_params: Some(payment_params),
2145 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2146 // On retry, split the payment across both channels.
2147 route.paths[0][0].fee_msat = 50_000_001;
2148 route.paths[1][0].fee_msat = 50_000_000;
2149 let mut pay_params = route.payment_params.clone().unwrap();
2150 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2151 nodes[0].router.expect_find_route(RouteParameters {
2152 payment_params: pay_params,
2153 // Note that the second request here requests the amount we originally failed to send,
2154 // not the amount remaining on the full payment, which should be changed.
2155 final_value_msat: 100_000_001,
2156 }, Ok(route.clone()));
2159 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2160 // The initial send attempt, 2 paths
2161 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2162 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2163 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2164 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2165 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2168 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2169 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2170 let events = nodes[0].node.get_and_clear_pending_events();
2171 assert_eq!(events.len(), 1);
2173 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2174 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2175 short_channel_id: Some(expected_scid), .. } =>
2177 assert_eq!(payment_hash, ev_payment_hash);
2178 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2179 assert!(err_msg.contains("max HTLC"));
2181 _ => panic!("Unexpected event"),
2183 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2184 assert_eq!(htlc_msgs.len(), 2);
2185 check_added_monitors!(nodes[0], 2);
2189 fn immediate_retry_on_failure() {
2190 // Tests that we can/will retry immediately after a failure
2191 let chanmon_cfgs = create_chanmon_cfgs(2);
2192 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2193 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2194 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2196 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2197 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2199 let amt_msat = 100_000_001;
2200 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2201 #[cfg(feature = "std")]
2202 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2203 #[cfg(not(feature = "std"))]
2204 let payment_expiry_secs = 60 * 60;
2205 let mut invoice_features = InvoiceFeatures::empty();
2206 invoice_features.set_variable_length_onion_required();
2207 invoice_features.set_payment_secret_required();
2208 invoice_features.set_basic_mpp_optional();
2209 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2210 .with_expiry_time(payment_expiry_secs as u64)
2211 .with_features(invoice_features);
2212 let route_params = RouteParameters {
2214 final_value_msat: amt_msat,
2217 let chans = nodes[0].node.list_usable_channels();
2218 let mut route = Route {
2221 pubkey: nodes[1].node.get_our_node_id(),
2222 node_features: nodes[1].node.node_features(),
2223 short_channel_id: chans[0].short_channel_id.unwrap(),
2224 channel_features: nodes[1].node.channel_features(),
2225 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2226 cltv_expiry_delta: 100,
2229 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2231 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2232 // On retry, split the payment across both channels.
2233 route.paths.push(route.paths[0].clone());
2234 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2235 route.paths[0][0].fee_msat = 50_000_000;
2236 route.paths[1][0].fee_msat = 50_000_001;
2237 let mut pay_params = route_params.payment_params.clone();
2238 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2239 nodes[0].router.expect_find_route(RouteParameters {
2240 payment_params: pay_params, final_value_msat: amt_msat,
2241 }, Ok(route.clone()));
2243 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2244 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2245 let events = nodes[0].node.get_and_clear_pending_events();
2246 assert_eq!(events.len(), 1);
2248 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2249 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2250 short_channel_id: Some(expected_scid), .. } =>
2252 assert_eq!(payment_hash, ev_payment_hash);
2253 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2254 assert!(err_msg.contains("max HTLC"));
2256 _ => panic!("Unexpected event"),
2258 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2259 assert_eq!(htlc_msgs.len(), 2);
2260 check_added_monitors!(nodes[0], 2);
2264 fn no_extra_retries_on_back_to_back_fail() {
2265 // In a previous release, we had a race where we may exceed the payment retry count if we
2266 // get two failures in a row with the second indicating that all paths had failed (this field,
2267 // `all_paths_failed`, has since been removed).
2268 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2269 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2270 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2271 // pending which we will see later. Thus, when we previously removed the retry tracking map
2272 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2273 // retry entry even though more events for the same payment were still pending. This led to
2274 // us retrying a payment again even though we'd already given up on it.
2276 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2277 // is used to remove the payment retry counter entries instead. This tests for the specific
2278 // excess-retry case while also testing `PaymentFailed` generation.
2280 let chanmon_cfgs = create_chanmon_cfgs(3);
2281 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2282 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2283 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2285 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2286 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2288 let amt_msat = 200_000_000;
2289 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2290 #[cfg(feature = "std")]
2291 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2292 #[cfg(not(feature = "std"))]
2293 let payment_expiry_secs = 60 * 60;
2294 let mut invoice_features = InvoiceFeatures::empty();
2295 invoice_features.set_variable_length_onion_required();
2296 invoice_features.set_payment_secret_required();
2297 invoice_features.set_basic_mpp_optional();
2298 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2299 .with_expiry_time(payment_expiry_secs as u64)
2300 .with_features(invoice_features);
2301 let route_params = RouteParameters {
2303 final_value_msat: amt_msat,
2306 let mut route = Route {
2309 pubkey: nodes[1].node.get_our_node_id(),
2310 node_features: nodes[1].node.node_features(),
2311 short_channel_id: chan_1_scid,
2312 channel_features: nodes[1].node.channel_features(),
2313 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2314 cltv_expiry_delta: 100,
2316 pubkey: nodes[2].node.get_our_node_id(),
2317 node_features: nodes[2].node.node_features(),
2318 short_channel_id: chan_2_scid,
2319 channel_features: nodes[2].node.channel_features(),
2320 fee_msat: 100_000_000,
2321 cltv_expiry_delta: 100,
2324 pubkey: nodes[1].node.get_our_node_id(),
2325 node_features: nodes[1].node.node_features(),
2326 short_channel_id: chan_1_scid,
2327 channel_features: nodes[1].node.channel_features(),
2328 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2329 cltv_expiry_delta: 100,
2331 pubkey: nodes[2].node.get_our_node_id(),
2332 node_features: nodes[2].node.node_features(),
2333 short_channel_id: chan_2_scid,
2334 channel_features: nodes[2].node.channel_features(),
2335 fee_msat: 100_000_000,
2336 cltv_expiry_delta: 100,
2339 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2341 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2342 let mut second_payment_params = route_params.payment_params.clone();
2343 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2344 // On retry, we'll only return one path
2345 route.paths.remove(1);
2346 route.paths[0][1].fee_msat = amt_msat;
2347 nodes[0].router.expect_find_route(RouteParameters {
2348 payment_params: second_payment_params,
2349 final_value_msat: amt_msat,
2350 }, Ok(route.clone()));
2352 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2353 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2354 let htlc_updates = SendEvent::from_node(&nodes[0]);
2355 check_added_monitors!(nodes[0], 1);
2356 assert_eq!(htlc_updates.msgs.len(), 1);
2358 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2359 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2360 check_added_monitors!(nodes[1], 1);
2361 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2363 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2364 check_added_monitors!(nodes[0], 1);
2365 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2367 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2368 check_added_monitors!(nodes[0], 1);
2369 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2371 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2372 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2373 check_added_monitors!(nodes[1], 1);
2374 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2376 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2377 check_added_monitors!(nodes[1], 1);
2378 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2380 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2381 check_added_monitors!(nodes[0], 1);
2383 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2384 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2385 check_added_monitors!(nodes[0], 1);
2386 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2388 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2389 check_added_monitors!(nodes[1], 1);
2390 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2392 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2393 check_added_monitors!(nodes[1], 1);
2394 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2396 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2397 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2398 check_added_monitors!(nodes[0], 1);
2400 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2401 check_added_monitors!(nodes[0], 1);
2402 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2404 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2405 check_added_monitors!(nodes[1], 1);
2406 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2407 check_added_monitors!(nodes[1], 1);
2408 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2410 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2411 check_added_monitors!(nodes[0], 1);
2413 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2414 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2417 // Previously, we retried payments in an event consumer, which would retry each
2418 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2419 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2420 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2421 // by adding the `PaymentFailed` event.
2423 // Because we now retry payments as a batch, we simply return a single-path route in the
2424 // second, batched, request, have that fail, ensure the payment was abandoned.
2425 let mut events = nodes[0].node.get_and_clear_pending_events();
2426 assert_eq!(events.len(), 3);
2428 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2429 assert_eq!(payment_hash, ev_payment_hash);
2430 assert_eq!(payment_failed_permanently, false);
2432 _ => panic!("Unexpected event"),
2435 Event::PendingHTLCsForwardable { .. } => {},
2436 _ => panic!("Unexpected event"),
2439 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2440 assert_eq!(payment_hash, ev_payment_hash);
2441 assert_eq!(payment_failed_permanently, false);
2443 _ => panic!("Unexpected event"),
2446 nodes[0].node.process_pending_htlc_forwards();
2447 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2448 check_added_monitors!(nodes[0], 1);
2450 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2451 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2452 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2453 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2454 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2456 let mut events = nodes[0].node.get_and_clear_pending_events();
2457 assert_eq!(events.len(), 2);
2459 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2460 assert_eq!(payment_hash, ev_payment_hash);
2461 assert_eq!(payment_failed_permanently, false);
2463 _ => panic!("Unexpected event"),
2466 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
2467 assert_eq!(payment_hash, *ev_payment_hash);
2468 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2470 _ => panic!("Unexpected event"),
2475 fn test_simple_partial_retry() {
2476 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2477 // full amount of the payment, rather than only the missing amount. Here we simply test for
2478 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2479 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2481 let chanmon_cfgs = create_chanmon_cfgs(3);
2482 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2483 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2484 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2486 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2487 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2489 let amt_msat = 200_000_000;
2490 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2491 #[cfg(feature = "std")]
2492 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2493 #[cfg(not(feature = "std"))]
2494 let payment_expiry_secs = 60 * 60;
2495 let mut invoice_features = InvoiceFeatures::empty();
2496 invoice_features.set_variable_length_onion_required();
2497 invoice_features.set_payment_secret_required();
2498 invoice_features.set_basic_mpp_optional();
2499 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2500 .with_expiry_time(payment_expiry_secs as u64)
2501 .with_features(invoice_features);
2502 let route_params = RouteParameters {
2504 final_value_msat: amt_msat,
2507 let mut route = Route {
2510 pubkey: nodes[1].node.get_our_node_id(),
2511 node_features: nodes[1].node.node_features(),
2512 short_channel_id: chan_1_scid,
2513 channel_features: nodes[1].node.channel_features(),
2514 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2515 cltv_expiry_delta: 100,
2517 pubkey: nodes[2].node.get_our_node_id(),
2518 node_features: nodes[2].node.node_features(),
2519 short_channel_id: chan_2_scid,
2520 channel_features: nodes[2].node.channel_features(),
2521 fee_msat: 100_000_000,
2522 cltv_expiry_delta: 100,
2525 pubkey: nodes[1].node.get_our_node_id(),
2526 node_features: nodes[1].node.node_features(),
2527 short_channel_id: chan_1_scid,
2528 channel_features: nodes[1].node.channel_features(),
2530 cltv_expiry_delta: 100,
2532 pubkey: nodes[2].node.get_our_node_id(),
2533 node_features: nodes[2].node.node_features(),
2534 short_channel_id: chan_2_scid,
2535 channel_features: nodes[2].node.channel_features(),
2536 fee_msat: 100_000_000,
2537 cltv_expiry_delta: 100,
2540 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2542 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2543 let mut second_payment_params = route_params.payment_params.clone();
2544 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2545 // On retry, we'll only be asked for one path (or 100k sats)
2546 route.paths.remove(0);
2547 nodes[0].router.expect_find_route(RouteParameters {
2548 payment_params: second_payment_params,
2549 final_value_msat: amt_msat / 2,
2550 }, Ok(route.clone()));
2552 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2553 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2554 let htlc_updates = SendEvent::from_node(&nodes[0]);
2555 check_added_monitors!(nodes[0], 1);
2556 assert_eq!(htlc_updates.msgs.len(), 1);
2558 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2559 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2560 check_added_monitors!(nodes[1], 1);
2561 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2563 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2564 check_added_monitors!(nodes[0], 1);
2565 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2567 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2568 check_added_monitors!(nodes[0], 1);
2569 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2571 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2572 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2573 check_added_monitors!(nodes[1], 1);
2574 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2576 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2577 check_added_monitors!(nodes[1], 1);
2578 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2580 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2581 check_added_monitors!(nodes[0], 1);
2583 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2584 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2585 check_added_monitors!(nodes[0], 1);
2586 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2588 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2589 check_added_monitors!(nodes[1], 1);
2591 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2592 check_added_monitors!(nodes[1], 1);
2594 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2596 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2597 check_added_monitors!(nodes[0], 1);
2599 let mut events = nodes[0].node.get_and_clear_pending_events();
2600 assert_eq!(events.len(), 2);
2602 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2603 assert_eq!(payment_hash, ev_payment_hash);
2604 assert_eq!(payment_failed_permanently, false);
2606 _ => panic!("Unexpected event"),
2609 Event::PendingHTLCsForwardable { .. } => {},
2610 _ => panic!("Unexpected event"),
2613 nodes[0].node.process_pending_htlc_forwards();
2614 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2615 check_added_monitors!(nodes[0], 1);
2617 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2618 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2620 expect_pending_htlcs_forwardable!(nodes[1]);
2621 check_added_monitors!(nodes[1], 1);
2623 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2624 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2625 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2626 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2628 expect_pending_htlcs_forwardable!(nodes[2]);
2629 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2633 #[cfg(feature = "std")]
2634 fn test_threaded_payment_retries() {
2635 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2636 // a single thread and would happily let multiple threads run retries at the same time. Because
2637 // retries are done by first calculating the amount we need to retry, then dropping the
2638 // relevant lock, then actually sending, we would happily let multiple threads retry the same
2639 // amount at the same time, overpaying our original HTLC!
2640 let chanmon_cfgs = create_chanmon_cfgs(4);
2641 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2642 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2643 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2645 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2646 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2647 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2648 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2650 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2651 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2652 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2653 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2655 let amt_msat = 100_000_000;
2656 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2657 #[cfg(feature = "std")]
2658 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2659 #[cfg(not(feature = "std"))]
2660 let payment_expiry_secs = 60 * 60;
2661 let mut invoice_features = InvoiceFeatures::empty();
2662 invoice_features.set_variable_length_onion_required();
2663 invoice_features.set_payment_secret_required();
2664 invoice_features.set_basic_mpp_optional();
2665 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2666 .with_expiry_time(payment_expiry_secs as u64)
2667 .with_features(invoice_features);
2668 let mut route_params = RouteParameters {
2670 final_value_msat: amt_msat,
2673 let mut route = Route {
2676 pubkey: nodes[1].node.get_our_node_id(),
2677 node_features: nodes[1].node.node_features(),
2678 short_channel_id: chan_1_scid,
2679 channel_features: nodes[1].node.channel_features(),
2681 cltv_expiry_delta: 100,
2683 pubkey: nodes[3].node.get_our_node_id(),
2684 node_features: nodes[2].node.node_features(),
2685 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2686 channel_features: nodes[2].node.channel_features(),
2687 fee_msat: amt_msat / 1000,
2688 cltv_expiry_delta: 100,
2691 pubkey: nodes[2].node.get_our_node_id(),
2692 node_features: nodes[2].node.node_features(),
2693 short_channel_id: chan_3_scid,
2694 channel_features: nodes[2].node.channel_features(),
2696 cltv_expiry_delta: 100,
2698 pubkey: nodes[3].node.get_our_node_id(),
2699 node_features: nodes[3].node.node_features(),
2700 short_channel_id: chan_4_scid,
2701 channel_features: nodes[3].node.channel_features(),
2702 fee_msat: amt_msat - amt_msat / 1000,
2703 cltv_expiry_delta: 100,
2706 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2708 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2710 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2711 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
2712 check_added_monitors!(nodes[0], 2);
2713 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2714 assert_eq!(send_msg_events.len(), 2);
2715 send_msg_events.retain(|msg|
2716 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
2717 // Drop the commitment update for nodes[2], we can just let that one sit pending
2719 *node_id == nodes[1].node.get_our_node_id()
2720 } else { panic!(); }
2723 // from here on out, the retry `RouteParameters` amount will be amt/1000
2724 route_params.final_value_msat /= 1000;
2727 let end_time = Instant::now() + Duration::from_secs(1);
2728 macro_rules! thread_body { () => { {
2729 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
2730 let node_ref = NodePtr::from_node(&nodes[0]);
2732 let node_a = unsafe { &*node_ref.0 };
2733 while Instant::now() < end_time {
2734 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2735 // Ignore if we have any pending events, just always pretend we just got a
2736 // PendingHTLCsForwardable
2737 node_a.node.process_pending_htlc_forwards();
2741 let mut threads = Vec::new();
2742 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
2744 // Back in the main thread, poll pending messages and make sure that we never have more than
2745 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
2746 // there are HTLC messages shoved in while its running. This allows us to test that we never
2747 // generate an additional update_add_htlc until we've fully failed the first.
2748 let mut previously_failed_channels = Vec::new();
2750 assert_eq!(send_msg_events.len(), 1);
2751 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
2752 assert_eq!(send_event.msgs.len(), 1);
2754 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
2755 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
2757 // Note that we only push one route into `expect_find_route` at a time, because that's all
2758 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
2759 // we should still ultimately fail for the same reason - because we're trying to send too
2760 // many HTLCs at once.
2761 let mut new_route_params = route_params.clone();
2762 previously_failed_channels.push(route.paths[0][1].short_channel_id);
2763 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
2764 route.paths[0][1].short_channel_id += 1;
2765 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
2767 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2768 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
2769 // The "normal" commitment_signed_dance delivers the final RAA and then calls
2770 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
2771 // This races with our other threads which may generate an add-HTLCs commitment update via
2772 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
2773 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
2774 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
2775 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
2777 let cur_time = Instant::now();
2778 if cur_time > end_time {
2779 for thread in threads.drain(..) { thread.join().unwrap(); }
2782 // Make sure we have some events to handle when we go around...
2783 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2784 nodes[0].node.process_pending_htlc_forwards();
2785 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2786 check_added_monitors!(nodes[0], 2);
2788 if cur_time > end_time {
2794 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
2795 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
2796 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
2797 // it was last persisted.
2798 let chanmon_cfgs = create_chanmon_cfgs(2);
2799 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2800 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2801 let (persister_a, persister_b, persister_c);
2802 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
2803 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
2804 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2806 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2808 let mut nodes_0_serialized = Vec::new();
2809 if !persist_manager_with_payment {
2810 nodes_0_serialized = nodes[0].node.encode();
2813 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2815 if persist_manager_with_payment {
2816 nodes_0_serialized = nodes[0].node.encode();
2819 nodes[1].node.claim_funds(our_payment_preimage);
2820 check_added_monitors!(nodes[1], 1);
2821 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
2823 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2824 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2825 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
2826 check_added_monitors!(nodes[0], 1);
2828 // The ChannelMonitor should always be the latest version, as we're required to persist it
2829 // during the commitment signed handling.
2830 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2831 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
2833 let events = nodes[0].node.get_and_clear_pending_events();
2834 assert_eq!(events.len(), 2);
2835 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
2836 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
2837 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
2838 // the double-claim that would otherwise appear at the end of this test.
2839 nodes[0].node.timer_tick_occurred();
2840 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2841 assert_eq!(as_broadcasted_txn.len(), 1);
2843 // Ensure that, even after some time, if we restart we still include *something* in the current
2844 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
2845 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
2846 // A naive implementation of the fix here would wipe the pending payments set, causing a
2847 // failure event when we restart.
2848 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2850 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2851 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);
2852 let events = nodes[0].node.get_and_clear_pending_events();
2853 assert!(events.is_empty());
2855 // Ensure that we don't generate any further events even after the channel-closing commitment
2856 // transaction is confirmed on-chain.
2857 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
2858 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2860 let events = nodes[0].node.get_and_clear_pending_events();
2861 assert!(events.is_empty());
2863 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2864 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);
2865 let events = nodes[0].node.get_and_clear_pending_events();
2866 assert!(events.is_empty());
2870 fn no_missing_sent_on_midpoint_reload() {
2871 do_no_missing_sent_on_midpoint_reload(false);
2872 do_no_missing_sent_on_midpoint_reload(true);