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(&route, None, payment_id);
1092 Err(PaymentSendFailure::DuplicatePayment) => {},
1093 _ => panic!("Unexpected send result: {:?}", send_result),
1098 check_send_rejected!();
1100 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1101 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1102 // we must remain just as idempotent as we were before.
1103 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1105 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1106 nodes[0].node.timer_tick_occurred();
1109 check_send_rejected!();
1111 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1112 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1113 // the payment complete. However, they could have called `send_payment` while the event was
1114 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1115 // after the event is handled a duplicate payment should sitll be rejected.
1116 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1117 check_send_rejected!();
1119 // If relatively little time has passed, a duplicate payment should still fail.
1120 nodes[0].node.timer_tick_occurred();
1121 check_send_rejected!();
1123 // However, after some time has passed (at least more than the one timer tick above), a
1124 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1125 // references to the old payment data.
1126 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1127 nodes[0].node.timer_tick_occurred();
1130 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1131 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1132 check_added_monitors!(nodes[0], 1);
1133 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1134 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1138 fn abandoned_send_payment_idempotent() {
1139 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1141 let chanmon_cfgs = create_chanmon_cfgs(2);
1142 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1143 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1144 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1146 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1148 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1149 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1151 macro_rules! check_send_rejected {
1153 // If we try to resend a new payment with a different payment_hash but with the same
1154 // payment_id, it should be rejected.
1155 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1156 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1158 Err(PaymentSendFailure::DuplicatePayment) => {},
1159 _ => panic!("Unexpected send result: {:?}", send_result),
1162 // Further, if we try to send a spontaneous payment with the same payment_id it should
1163 // also be rejected.
1164 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1166 Err(PaymentSendFailure::DuplicatePayment) => {},
1167 _ => panic!("Unexpected send result: {:?}", send_result),
1172 check_send_rejected!();
1174 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1175 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1177 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1179 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1180 nodes[0].node.timer_tick_occurred();
1182 check_send_rejected!();
1184 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash);
1186 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1187 // failed payment back.
1188 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1189 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1190 check_added_monitors!(nodes[0], 1);
1191 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1192 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1195 #[derive(PartialEq)]
1196 enum InterceptTest {
1203 fn test_trivial_inflight_htlc_tracking(){
1204 // In this test, we test three scenarios:
1205 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1206 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1207 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1208 let chanmon_cfgs = create_chanmon_cfgs(3);
1209 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1210 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1211 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1213 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1214 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1216 // Send and claim the payment. Inflight HTLCs should be empty.
1217 let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1218 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1220 let mut node_0_per_peer_lock;
1221 let mut node_0_peer_state_lock;
1222 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1224 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1225 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1226 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1227 channel_1.get_short_channel_id().unwrap()
1229 assert_eq!(chan_1_used_liquidity, None);
1232 let mut node_1_per_peer_lock;
1233 let mut node_1_peer_state_lock;
1234 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1236 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1237 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1238 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1239 channel_2.get_short_channel_id().unwrap()
1242 assert_eq!(chan_2_used_liquidity, None);
1244 let pending_payments = nodes[0].node.list_recent_payments();
1245 assert_eq!(pending_payments.len(), 1);
1246 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1248 // Remove fulfilled payment
1249 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1250 nodes[0].node.timer_tick_occurred();
1253 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1254 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1255 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1257 let mut node_0_per_peer_lock;
1258 let mut node_0_peer_state_lock;
1259 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1261 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1262 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1263 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1264 channel_1.get_short_channel_id().unwrap()
1266 // First hop accounts for expected 1000 msat fee
1267 assert_eq!(chan_1_used_liquidity, Some(501000));
1270 let mut node_1_per_peer_lock;
1271 let mut node_1_peer_state_lock;
1272 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1274 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1275 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1276 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1277 channel_2.get_short_channel_id().unwrap()
1280 assert_eq!(chan_2_used_liquidity, Some(500000));
1282 let pending_payments = nodes[0].node.list_recent_payments();
1283 assert_eq!(pending_payments.len(), 1);
1284 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1286 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1287 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1289 // Remove fulfilled payment
1290 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1291 nodes[0].node.timer_tick_occurred();
1294 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1296 let mut node_0_per_peer_lock;
1297 let mut node_0_peer_state_lock;
1298 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1300 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1301 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1302 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1303 channel_1.get_short_channel_id().unwrap()
1305 assert_eq!(chan_1_used_liquidity, None);
1308 let mut node_1_per_peer_lock;
1309 let mut node_1_peer_state_lock;
1310 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1312 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1313 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1314 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1315 channel_2.get_short_channel_id().unwrap()
1317 assert_eq!(chan_2_used_liquidity, None);
1320 let pending_payments = nodes[0].node.list_recent_payments();
1321 assert_eq!(pending_payments.len(), 0);
1325 fn test_holding_cell_inflight_htlcs() {
1326 let chanmon_cfgs = create_chanmon_cfgs(2);
1327 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1328 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1329 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1330 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1332 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1333 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1335 // Queue up two payments - one will be delivered right away, one immediately goes into the
1336 // holding cell as nodes[0] is AwaitingRAA.
1338 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1339 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1340 check_added_monitors!(nodes[0], 1);
1341 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1342 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1343 check_added_monitors!(nodes[0], 0);
1346 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1349 let mut node_0_per_peer_lock;
1350 let mut node_0_peer_state_lock;
1351 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1353 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1354 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1355 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1356 channel.get_short_channel_id().unwrap()
1359 assert_eq!(used_liquidity, Some(2000000));
1362 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1363 nodes[0].node.get_and_clear_pending_msg_events();
1367 fn intercepted_payment() {
1368 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1369 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1370 // payment or (b) fail the payment.
1371 do_test_intercepted_payment(InterceptTest::Forward);
1372 do_test_intercepted_payment(InterceptTest::Fail);
1373 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1374 do_test_intercepted_payment(InterceptTest::Timeout);
1377 fn do_test_intercepted_payment(test: InterceptTest) {
1378 let chanmon_cfgs = create_chanmon_cfgs(3);
1379 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1381 let mut zero_conf_chan_config = test_default_channel_config();
1382 zero_conf_chan_config.manually_accept_inbound_channels = true;
1383 let mut intercept_forwards_config = test_default_channel_config();
1384 intercept_forwards_config.accept_intercept_htlcs = true;
1385 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1387 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1388 let scorer = test_utils::TestScorer::new();
1389 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1391 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1393 let amt_msat = 100_000;
1394 let intercept_scid = nodes[1].node.get_intercept_scid();
1395 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1396 .with_route_hints(vec![
1397 RouteHint(vec![RouteHintHop {
1398 src_node_id: nodes[1].node.get_our_node_id(),
1399 short_channel_id: intercept_scid,
1402 proportional_millionths: 0,
1404 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1405 htlc_minimum_msat: None,
1406 htlc_maximum_msat: None,
1409 .with_features(nodes[2].node.invoice_features());
1410 let route_params = RouteParameters {
1412 final_value_msat: amt_msat,
1414 let route = get_route(
1415 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1416 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1417 route_params.payment_params.final_cltv_expiry_delta, nodes[0].logger, &scorer,
1421 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1422 nodes[0].node.send_payment_with_route(&route, payment_hash,
1423 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1424 let payment_event = {
1426 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1427 assert_eq!(added_monitors.len(), 1);
1428 added_monitors.clear();
1430 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1431 assert_eq!(events.len(), 1);
1432 SendEvent::from_event(events.remove(0))
1434 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1435 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1437 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1438 let events = nodes[1].node.get_and_clear_pending_events();
1439 assert_eq!(events.len(), 1);
1440 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1441 crate::events::Event::HTLCIntercepted {
1442 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1444 assert_eq!(pmt_hash, payment_hash);
1445 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1446 assert_eq!(short_channel_id, intercept_scid);
1447 (intercept_id, expected_outbound_amount_msat)
1452 // Check for unknown channel id error.
1453 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();
1454 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()) });
1456 if test == InterceptTest::Fail {
1457 // Ensure we can fail the intercepted payment back.
1458 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1459 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1460 nodes[1].node.process_pending_htlc_forwards();
1461 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1462 check_added_monitors!(&nodes[1], 1);
1463 assert!(update_fail.update_fail_htlcs.len() == 1);
1464 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1465 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1466 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1468 // Ensure the payment fails with the expected error.
1469 let fail_conditions = PaymentFailedConditions::new()
1470 .blamed_scid(intercept_scid)
1471 .blamed_chan_closed(true)
1472 .expected_htlc_error_data(0x4000 | 10, &[]);
1473 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1474 } else if test == InterceptTest::Forward {
1475 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1476 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1477 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();
1478 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1479 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1481 // Open the just-in-time channel so the payment can then be forwarded.
1482 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1484 // Finally, forward the intercepted payment through and claim it.
1485 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1486 expect_pending_htlcs_forwardable!(nodes[1]);
1488 let payment_event = {
1490 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1491 assert_eq!(added_monitors.len(), 1);
1492 added_monitors.clear();
1494 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1495 assert_eq!(events.len(), 1);
1496 SendEvent::from_event(events.remove(0))
1498 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1499 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1500 expect_pending_htlcs_forwardable!(nodes[2]);
1502 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1503 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1504 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1505 let events = nodes[0].node.get_and_clear_pending_events();
1506 assert_eq!(events.len(), 2);
1508 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1509 assert_eq!(payment_preimage, *ev_preimage);
1510 assert_eq!(payment_hash, *ev_hash);
1511 assert_eq!(fee_paid_msat, &Some(1000));
1513 _ => panic!("Unexpected event")
1516 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1517 assert_eq!(hash, Some(payment_hash));
1519 _ => panic!("Unexpected event")
1521 } else if test == InterceptTest::Timeout {
1522 let mut block = Block {
1523 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1526 connect_block(&nodes[0], &block);
1527 connect_block(&nodes[1], &block);
1528 for _ in 0..TEST_FINAL_CLTV {
1529 block.header.prev_blockhash = block.block_hash();
1530 connect_block(&nodes[0], &block);
1531 connect_block(&nodes[1], &block);
1533 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1534 check_added_monitors!(nodes[1], 1);
1535 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1536 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1537 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1538 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1539 assert!(htlc_timeout_updates.update_fee.is_none());
1541 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1542 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1543 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1545 // Check for unknown intercept id error.
1546 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1547 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();
1548 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1549 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1550 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1554 #[derive(PartialEq)]
1565 fn automatic_retries() {
1566 do_automatic_retries(AutoRetry::Success);
1567 do_automatic_retries(AutoRetry::Spontaneous);
1568 do_automatic_retries(AutoRetry::FailAttempts);
1569 do_automatic_retries(AutoRetry::FailTimeout);
1570 do_automatic_retries(AutoRetry::FailOnRestart);
1571 do_automatic_retries(AutoRetry::FailOnRetry);
1573 fn do_automatic_retries(test: AutoRetry) {
1574 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1576 let chanmon_cfgs = create_chanmon_cfgs(3);
1577 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1578 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1581 let new_chain_monitor;
1582 let node_0_deserialized;
1584 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1585 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1586 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1588 // Marshall data to send the payment
1589 #[cfg(feature = "std")]
1590 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1591 #[cfg(not(feature = "std"))]
1592 let payment_expiry_secs = 60 * 60;
1593 let amt_msat = 1000;
1594 let mut invoice_features = InvoiceFeatures::empty();
1595 invoice_features.set_variable_length_onion_required();
1596 invoice_features.set_payment_secret_required();
1597 invoice_features.set_basic_mpp_optional();
1598 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1599 .with_expiry_time(payment_expiry_secs as u64)
1600 .with_features(invoice_features);
1601 let route_params = RouteParameters {
1603 final_value_msat: amt_msat,
1605 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1607 macro_rules! pass_failed_attempt_with_retry_along_path {
1608 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1609 // Send a payment attempt that fails due to lack of liquidity on the second hop
1610 check_added_monitors!(nodes[0], 1);
1611 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1612 let mut update_add = update_0.update_add_htlcs[0].clone();
1613 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1614 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1615 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1616 nodes[1].node.process_pending_htlc_forwards();
1617 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1618 vec![HTLCDestination::NextHopChannel {
1619 node_id: Some(nodes[2].node.get_our_node_id()),
1620 channel_id: $failing_channel_id,
1622 nodes[1].node.process_pending_htlc_forwards();
1623 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1624 check_added_monitors!(&nodes[1], 1);
1625 assert!(update_1.update_fail_htlcs.len() == 1);
1626 let fail_msg = update_1.update_fail_htlcs[0].clone();
1627 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1628 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1630 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1631 let mut events = nodes[0].node.get_and_clear_pending_events();
1632 assert_eq!(events.len(), 2);
1634 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1635 assert_eq!(payment_hash, ev_payment_hash);
1636 assert_eq!(payment_failed_permanently, false);
1638 _ => panic!("Unexpected event"),
1640 if $expect_pending_htlcs_forwardable {
1642 Event::PendingHTLCsForwardable { .. } => {},
1643 _ => panic!("Unexpected event"),
1647 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1648 assert_eq!(payment_hash, ev_payment_hash);
1650 _ => panic!("Unexpected event"),
1656 if test == AutoRetry::Success {
1657 // Test that we can succeed on the first retry.
1658 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1659 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1660 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1662 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1663 // attempt, since the initial second hop channel will be excluded from pathfinding
1664 create_announced_chan_between_nodes(&nodes, 1, 2);
1666 // We retry payments in `process_pending_htlc_forwards`
1667 nodes[0].node.process_pending_htlc_forwards();
1668 check_added_monitors!(nodes[0], 1);
1669 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1670 assert_eq!(msg_events.len(), 1);
1671 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1672 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1673 } else if test == AutoRetry::Spontaneous {
1674 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1675 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1677 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1678 // attempt, since the initial second hop channel will be excluded from pathfinding
1679 create_announced_chan_between_nodes(&nodes, 1, 2);
1681 // We retry payments in `process_pending_htlc_forwards`
1682 nodes[0].node.process_pending_htlc_forwards();
1683 check_added_monitors!(nodes[0], 1);
1684 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1685 assert_eq!(msg_events.len(), 1);
1686 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1687 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1688 } else if test == AutoRetry::FailAttempts {
1689 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1690 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1691 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1692 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1694 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1695 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1696 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1698 // We retry payments in `process_pending_htlc_forwards`
1699 nodes[0].node.process_pending_htlc_forwards();
1700 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1702 // Ensure we won't retry a second time.
1703 nodes[0].node.process_pending_htlc_forwards();
1704 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1705 assert_eq!(msg_events.len(), 0);
1706 } else if test == AutoRetry::FailTimeout {
1707 #[cfg(not(feature = "no-std"))] {
1708 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1709 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1710 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
1711 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1713 // Advance the time so the second attempt fails due to timeout.
1714 SinceEpoch::advance(Duration::from_secs(61));
1716 // Make sure we don't retry again.
1717 nodes[0].node.process_pending_htlc_forwards();
1718 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1719 assert_eq!(msg_events.len(), 0);
1721 let mut events = nodes[0].node.get_and_clear_pending_events();
1722 assert_eq!(events.len(), 1);
1724 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1725 assert_eq!(payment_hash, *ev_payment_hash);
1726 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1728 _ => panic!("Unexpected event"),
1731 } else if test == AutoRetry::FailOnRestart {
1732 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1733 // attempts remaining prior to restart.
1734 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1735 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1736 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1738 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1739 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1740 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1742 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1743 nodes[0].node.process_pending_htlc_forwards();
1744 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1746 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1747 let node_encoded = nodes[0].node.encode();
1748 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1749 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1751 let mut events = nodes[0].node.get_and_clear_pending_events();
1752 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
1753 // Make sure we don't retry again.
1754 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1755 assert_eq!(msg_events.len(), 0);
1757 let mut events = nodes[0].node.get_and_clear_pending_events();
1758 assert_eq!(events.len(), 1);
1760 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1761 assert_eq!(payment_hash, *ev_payment_hash);
1762 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1764 _ => panic!("Unexpected event"),
1766 } else if test == AutoRetry::FailOnRetry {
1767 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1768 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1769 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1771 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1772 // fail to find a route.
1773 nodes[0].node.process_pending_htlc_forwards();
1774 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1775 assert_eq!(msg_events.len(), 0);
1777 let mut events = nodes[0].node.get_and_clear_pending_events();
1778 assert_eq!(events.len(), 1);
1780 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1781 assert_eq!(payment_hash, *ev_payment_hash);
1782 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1784 _ => panic!("Unexpected event"),
1790 fn auto_retry_partial_failure() {
1791 // Test that we'll retry appropriately on send partial failure and retry partial failure.
1792 let chanmon_cfgs = create_chanmon_cfgs(2);
1793 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1794 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1795 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1797 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1798 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1799 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1801 // Marshall data to send the payment
1802 let amt_msat = 20_000;
1803 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1804 #[cfg(feature = "std")]
1805 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1806 #[cfg(not(feature = "std"))]
1807 let payment_expiry_secs = 60 * 60;
1808 let mut invoice_features = InvoiceFeatures::empty();
1809 invoice_features.set_variable_length_onion_required();
1810 invoice_features.set_payment_secret_required();
1811 invoice_features.set_basic_mpp_optional();
1812 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1813 .with_expiry_time(payment_expiry_secs as u64)
1814 .with_features(invoice_features);
1815 let route_params = RouteParameters {
1817 final_value_msat: amt_msat,
1820 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1821 // second (for the initial send path2 over chan_2) fails.
1822 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1823 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1824 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1825 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1826 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1827 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1828 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1830 // Configure the initial send, retry1 and retry2's paths.
1831 let send_route = Route {
1834 pubkey: nodes[1].node.get_our_node_id(),
1835 node_features: nodes[1].node.node_features(),
1836 short_channel_id: chan_1_id,
1837 channel_features: nodes[1].node.channel_features(),
1838 fee_msat: amt_msat / 2,
1839 cltv_expiry_delta: 100,
1842 pubkey: nodes[1].node.get_our_node_id(),
1843 node_features: nodes[1].node.node_features(),
1844 short_channel_id: chan_2_id,
1845 channel_features: nodes[1].node.channel_features(),
1846 fee_msat: amt_msat / 2,
1847 cltv_expiry_delta: 100,
1850 payment_params: Some(route_params.payment_params.clone()),
1852 let retry_1_route = Route {
1855 pubkey: nodes[1].node.get_our_node_id(),
1856 node_features: nodes[1].node.node_features(),
1857 short_channel_id: chan_1_id,
1858 channel_features: nodes[1].node.channel_features(),
1859 fee_msat: amt_msat / 4,
1860 cltv_expiry_delta: 100,
1863 pubkey: nodes[1].node.get_our_node_id(),
1864 node_features: nodes[1].node.node_features(),
1865 short_channel_id: chan_3_id,
1866 channel_features: nodes[1].node.channel_features(),
1867 fee_msat: amt_msat / 4,
1868 cltv_expiry_delta: 100,
1871 payment_params: Some(route_params.payment_params.clone()),
1873 let retry_2_route = Route {
1876 pubkey: nodes[1].node.get_our_node_id(),
1877 node_features: nodes[1].node.node_features(),
1878 short_channel_id: chan_1_id,
1879 channel_features: nodes[1].node.channel_features(),
1880 fee_msat: amt_msat / 4,
1881 cltv_expiry_delta: 100,
1884 payment_params: Some(route_params.payment_params.clone()),
1886 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1887 let mut payment_params = route_params.payment_params.clone();
1888 payment_params.previously_failed_channels.push(chan_2_id);
1889 nodes[0].router.expect_find_route(RouteParameters {
1890 payment_params, final_value_msat: amt_msat / 2,
1891 }, Ok(retry_1_route));
1892 let mut payment_params = route_params.payment_params.clone();
1893 payment_params.previously_failed_channels.push(chan_3_id);
1894 nodes[0].router.expect_find_route(RouteParameters {
1895 payment_params, final_value_msat: amt_msat / 4,
1896 }, Ok(retry_2_route));
1898 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1899 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1900 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1901 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1902 assert_eq!(closed_chan_events.len(), 4);
1903 match closed_chan_events[0] {
1904 Event::ChannelClosed { .. } => {},
1905 _ => panic!("Unexpected event"),
1907 match closed_chan_events[1] {
1908 Event::PaymentPathFailed { .. } => {},
1909 _ => panic!("Unexpected event"),
1911 match closed_chan_events[2] {
1912 Event::ChannelClosed { .. } => {},
1913 _ => panic!("Unexpected event"),
1915 match closed_chan_events[3] {
1916 Event::PaymentPathFailed { .. } => {},
1917 _ => panic!("Unexpected event"),
1920 // Pass the first part of the payment along the path.
1921 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1922 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1924 // First message is the first update_add, remaining messages are broadcasting channel updates and
1925 // errors for the permfailed channels
1926 assert_eq!(msg_events.len(), 5);
1927 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1929 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1930 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1931 check_added_monitors!(nodes[1], 1);
1932 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1934 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1935 check_added_monitors!(nodes[0], 1);
1936 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1938 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1939 check_added_monitors!(nodes[0], 1);
1940 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1942 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1943 check_added_monitors!(nodes[1], 1);
1945 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1946 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1947 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1948 check_added_monitors!(nodes[1], 1);
1949 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1951 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1952 check_added_monitors!(nodes[0], 1);
1954 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
1955 check_added_monitors!(nodes[0], 1);
1956 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1958 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1959 check_added_monitors!(nodes[1], 1);
1961 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1962 nodes[1].node.process_pending_htlc_forwards();
1963 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
1964 nodes[1].node.claim_funds(payment_preimage);
1965 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
1966 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1967 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
1969 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
1970 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
1971 check_added_monitors!(nodes[0], 1);
1972 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1974 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1975 check_added_monitors!(nodes[1], 4);
1976 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1978 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1979 check_added_monitors!(nodes[1], 1);
1980 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1982 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1983 check_added_monitors!(nodes[0], 1);
1985 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
1986 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
1987 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
1988 check_added_monitors!(nodes[0], 1);
1989 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1991 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
1992 check_added_monitors!(nodes[1], 1);
1994 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1995 check_added_monitors!(nodes[1], 1);
1996 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1998 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1999 check_added_monitors!(nodes[0], 1);
2000 expect_payment_sent!(nodes[0], payment_preimage);
2004 fn auto_retry_zero_attempts_send_error() {
2005 let chanmon_cfgs = create_chanmon_cfgs(2);
2006 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2007 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2008 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2010 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2011 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2013 // Marshall data to send the payment
2014 let amt_msat = 20_000;
2015 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2016 #[cfg(feature = "std")]
2017 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2018 #[cfg(not(feature = "std"))]
2019 let payment_expiry_secs = 60 * 60;
2020 let mut invoice_features = InvoiceFeatures::empty();
2021 invoice_features.set_variable_length_onion_required();
2022 invoice_features.set_payment_secret_required();
2023 invoice_features.set_basic_mpp_optional();
2024 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2025 .with_expiry_time(payment_expiry_secs as u64)
2026 .with_features(invoice_features);
2027 let route_params = RouteParameters {
2029 final_value_msat: amt_msat,
2032 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2033 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2034 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2035 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2036 let events = nodes[0].node.get_and_clear_pending_events();
2037 assert_eq!(events.len(), 3);
2038 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2039 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2040 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2041 check_added_monitors!(nodes[0], 2);
2045 fn fails_paying_after_rejected_by_payee() {
2046 let chanmon_cfgs = create_chanmon_cfgs(2);
2047 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2048 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2049 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2051 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2053 // Marshall data to send the payment
2054 let amt_msat = 20_000;
2055 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2056 #[cfg(feature = "std")]
2057 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2058 #[cfg(not(feature = "std"))]
2059 let payment_expiry_secs = 60 * 60;
2060 let mut invoice_features = InvoiceFeatures::empty();
2061 invoice_features.set_variable_length_onion_required();
2062 invoice_features.set_payment_secret_required();
2063 invoice_features.set_basic_mpp_optional();
2064 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2065 .with_expiry_time(payment_expiry_secs as u64)
2066 .with_features(invoice_features);
2067 let route_params = RouteParameters {
2069 final_value_msat: amt_msat,
2072 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2073 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2074 check_added_monitors!(nodes[0], 1);
2075 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2076 assert_eq!(events.len(), 1);
2077 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2078 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2079 check_added_monitors!(nodes[1], 0);
2080 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2081 expect_pending_htlcs_forwardable!(nodes[1]);
2082 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2084 nodes[1].node.fail_htlc_backwards(&payment_hash);
2085 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2086 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash);
2090 fn retry_multi_path_single_failed_payment() {
2091 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2092 let chanmon_cfgs = create_chanmon_cfgs(2);
2093 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2094 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2095 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2097 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2098 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2100 let amt_msat = 100_010_000;
2102 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2103 #[cfg(feature = "std")]
2104 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2105 #[cfg(not(feature = "std"))]
2106 let payment_expiry_secs = 60 * 60;
2107 let mut invoice_features = InvoiceFeatures::empty();
2108 invoice_features.set_variable_length_onion_required();
2109 invoice_features.set_payment_secret_required();
2110 invoice_features.set_basic_mpp_optional();
2111 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2112 .with_expiry_time(payment_expiry_secs as u64)
2113 .with_features(invoice_features);
2114 let route_params = RouteParameters {
2115 payment_params: payment_params.clone(),
2116 final_value_msat: amt_msat,
2119 let chans = nodes[0].node.list_usable_channels();
2120 let mut route = Route {
2123 pubkey: nodes[1].node.get_our_node_id(),
2124 node_features: nodes[1].node.node_features(),
2125 short_channel_id: chans[0].short_channel_id.unwrap(),
2126 channel_features: nodes[1].node.channel_features(),
2128 cltv_expiry_delta: 100,
2131 pubkey: nodes[1].node.get_our_node_id(),
2132 node_features: nodes[1].node.node_features(),
2133 short_channel_id: chans[1].short_channel_id.unwrap(),
2134 channel_features: nodes[1].node.channel_features(),
2135 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2136 cltv_expiry_delta: 100,
2139 payment_params: Some(payment_params),
2141 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2142 // On retry, split the payment across both channels.
2143 route.paths[0][0].fee_msat = 50_000_001;
2144 route.paths[1][0].fee_msat = 50_000_000;
2145 let mut pay_params = route.payment_params.clone().unwrap();
2146 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2147 nodes[0].router.expect_find_route(RouteParameters {
2148 payment_params: pay_params,
2149 // Note that the second request here requests the amount we originally failed to send,
2150 // not the amount remaining on the full payment, which should be changed.
2151 final_value_msat: 100_000_001,
2152 }, Ok(route.clone()));
2155 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2156 // The initial send attempt, 2 paths
2157 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2158 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2159 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2160 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2161 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2164 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2165 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2166 let events = nodes[0].node.get_and_clear_pending_events();
2167 assert_eq!(events.len(), 1);
2169 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2170 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2171 short_channel_id: Some(expected_scid), .. } =>
2173 assert_eq!(payment_hash, ev_payment_hash);
2174 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2175 assert!(err_msg.contains("max HTLC"));
2177 _ => panic!("Unexpected event"),
2179 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2180 assert_eq!(htlc_msgs.len(), 2);
2181 check_added_monitors!(nodes[0], 2);
2185 fn immediate_retry_on_failure() {
2186 // Tests that we can/will retry immediately after a failure
2187 let chanmon_cfgs = create_chanmon_cfgs(2);
2188 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2189 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2190 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2192 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2193 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2195 let amt_msat = 100_000_001;
2196 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2197 #[cfg(feature = "std")]
2198 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2199 #[cfg(not(feature = "std"))]
2200 let payment_expiry_secs = 60 * 60;
2201 let mut invoice_features = InvoiceFeatures::empty();
2202 invoice_features.set_variable_length_onion_required();
2203 invoice_features.set_payment_secret_required();
2204 invoice_features.set_basic_mpp_optional();
2205 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2206 .with_expiry_time(payment_expiry_secs as u64)
2207 .with_features(invoice_features);
2208 let route_params = RouteParameters {
2210 final_value_msat: amt_msat,
2213 let chans = nodes[0].node.list_usable_channels();
2214 let mut route = Route {
2217 pubkey: nodes[1].node.get_our_node_id(),
2218 node_features: nodes[1].node.node_features(),
2219 short_channel_id: chans[0].short_channel_id.unwrap(),
2220 channel_features: nodes[1].node.channel_features(),
2221 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2222 cltv_expiry_delta: 100,
2225 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2227 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2228 // On retry, split the payment across both channels.
2229 route.paths.push(route.paths[0].clone());
2230 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2231 route.paths[0][0].fee_msat = 50_000_000;
2232 route.paths[1][0].fee_msat = 50_000_001;
2233 let mut pay_params = route_params.payment_params.clone();
2234 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2235 nodes[0].router.expect_find_route(RouteParameters {
2236 payment_params: pay_params, final_value_msat: amt_msat,
2237 }, Ok(route.clone()));
2239 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2240 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2241 let events = nodes[0].node.get_and_clear_pending_events();
2242 assert_eq!(events.len(), 1);
2244 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2245 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2246 short_channel_id: Some(expected_scid), .. } =>
2248 assert_eq!(payment_hash, ev_payment_hash);
2249 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2250 assert!(err_msg.contains("max HTLC"));
2252 _ => panic!("Unexpected event"),
2254 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2255 assert_eq!(htlc_msgs.len(), 2);
2256 check_added_monitors!(nodes[0], 2);
2260 fn no_extra_retries_on_back_to_back_fail() {
2261 // In a previous release, we had a race where we may exceed the payment retry count if we
2262 // get two failures in a row with the second indicating that all paths had failed (this field,
2263 // `all_paths_failed`, has since been removed).
2264 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2265 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2266 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2267 // pending which we will see later. Thus, when we previously removed the retry tracking map
2268 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2269 // retry entry even though more events for the same payment were still pending. This led to
2270 // us retrying a payment again even though we'd already given up on it.
2272 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2273 // is used to remove the payment retry counter entries instead. This tests for the specific
2274 // excess-retry case while also testing `PaymentFailed` generation.
2276 let chanmon_cfgs = create_chanmon_cfgs(3);
2277 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2278 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2279 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2281 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2282 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2284 let amt_msat = 200_000_000;
2285 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2286 #[cfg(feature = "std")]
2287 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2288 #[cfg(not(feature = "std"))]
2289 let payment_expiry_secs = 60 * 60;
2290 let mut invoice_features = InvoiceFeatures::empty();
2291 invoice_features.set_variable_length_onion_required();
2292 invoice_features.set_payment_secret_required();
2293 invoice_features.set_basic_mpp_optional();
2294 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2295 .with_expiry_time(payment_expiry_secs as u64)
2296 .with_features(invoice_features);
2297 let route_params = RouteParameters {
2299 final_value_msat: amt_msat,
2302 let mut route = Route {
2305 pubkey: nodes[1].node.get_our_node_id(),
2306 node_features: nodes[1].node.node_features(),
2307 short_channel_id: chan_1_scid,
2308 channel_features: nodes[1].node.channel_features(),
2309 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2310 cltv_expiry_delta: 100,
2312 pubkey: nodes[2].node.get_our_node_id(),
2313 node_features: nodes[2].node.node_features(),
2314 short_channel_id: chan_2_scid,
2315 channel_features: nodes[2].node.channel_features(),
2316 fee_msat: 100_000_000,
2317 cltv_expiry_delta: 100,
2320 pubkey: nodes[1].node.get_our_node_id(),
2321 node_features: nodes[1].node.node_features(),
2322 short_channel_id: chan_1_scid,
2323 channel_features: nodes[1].node.channel_features(),
2324 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2325 cltv_expiry_delta: 100,
2327 pubkey: nodes[2].node.get_our_node_id(),
2328 node_features: nodes[2].node.node_features(),
2329 short_channel_id: chan_2_scid,
2330 channel_features: nodes[2].node.channel_features(),
2331 fee_msat: 100_000_000,
2332 cltv_expiry_delta: 100,
2335 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2337 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2338 let mut second_payment_params = route_params.payment_params.clone();
2339 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2340 // On retry, we'll only return one path
2341 route.paths.remove(1);
2342 route.paths[0][1].fee_msat = amt_msat;
2343 nodes[0].router.expect_find_route(RouteParameters {
2344 payment_params: second_payment_params,
2345 final_value_msat: amt_msat,
2346 }, Ok(route.clone()));
2348 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2349 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2350 let htlc_updates = SendEvent::from_node(&nodes[0]);
2351 check_added_monitors!(nodes[0], 1);
2352 assert_eq!(htlc_updates.msgs.len(), 1);
2354 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2355 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2356 check_added_monitors!(nodes[1], 1);
2357 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2359 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2360 check_added_monitors!(nodes[0], 1);
2361 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2363 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2364 check_added_monitors!(nodes[0], 1);
2365 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2367 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2368 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2369 check_added_monitors!(nodes[1], 1);
2370 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2372 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2373 check_added_monitors!(nodes[1], 1);
2374 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2376 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2377 check_added_monitors!(nodes[0], 1);
2379 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2380 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2381 check_added_monitors!(nodes[0], 1);
2382 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2384 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2385 check_added_monitors!(nodes[1], 1);
2386 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2388 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2389 check_added_monitors!(nodes[1], 1);
2390 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2392 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2393 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2394 check_added_monitors!(nodes[0], 1);
2396 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2397 check_added_monitors!(nodes[0], 1);
2398 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2400 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2401 check_added_monitors!(nodes[1], 1);
2402 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2403 check_added_monitors!(nodes[1], 1);
2404 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2406 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2407 check_added_monitors!(nodes[0], 1);
2409 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2410 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2413 // Previously, we retried payments in an event consumer, which would retry each
2414 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2415 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2416 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2417 // by adding the `PaymentFailed` event.
2419 // Because we now retry payments as a batch, we simply return a single-path route in the
2420 // second, batched, request, have that fail, ensure the payment was abandoned.
2421 let mut events = nodes[0].node.get_and_clear_pending_events();
2422 assert_eq!(events.len(), 3);
2424 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2425 assert_eq!(payment_hash, ev_payment_hash);
2426 assert_eq!(payment_failed_permanently, false);
2428 _ => panic!("Unexpected event"),
2431 Event::PendingHTLCsForwardable { .. } => {},
2432 _ => panic!("Unexpected event"),
2435 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2436 assert_eq!(payment_hash, ev_payment_hash);
2437 assert_eq!(payment_failed_permanently, false);
2439 _ => panic!("Unexpected event"),
2442 nodes[0].node.process_pending_htlc_forwards();
2443 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2444 check_added_monitors!(nodes[0], 1);
2446 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2447 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2448 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2449 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2450 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2452 let mut events = nodes[0].node.get_and_clear_pending_events();
2453 assert_eq!(events.len(), 2);
2455 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2456 assert_eq!(payment_hash, ev_payment_hash);
2457 assert_eq!(payment_failed_permanently, false);
2459 _ => panic!("Unexpected event"),
2462 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
2463 assert_eq!(payment_hash, *ev_payment_hash);
2464 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2466 _ => panic!("Unexpected event"),
2471 fn test_simple_partial_retry() {
2472 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2473 // full amount of the payment, rather than only the missing amount. Here we simply test for
2474 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2475 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2477 let chanmon_cfgs = create_chanmon_cfgs(3);
2478 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2479 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2480 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2482 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2483 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2485 let amt_msat = 200_000_000;
2486 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2487 #[cfg(feature = "std")]
2488 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2489 #[cfg(not(feature = "std"))]
2490 let payment_expiry_secs = 60 * 60;
2491 let mut invoice_features = InvoiceFeatures::empty();
2492 invoice_features.set_variable_length_onion_required();
2493 invoice_features.set_payment_secret_required();
2494 invoice_features.set_basic_mpp_optional();
2495 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2496 .with_expiry_time(payment_expiry_secs as u64)
2497 .with_features(invoice_features);
2498 let route_params = RouteParameters {
2500 final_value_msat: amt_msat,
2503 let mut route = Route {
2506 pubkey: nodes[1].node.get_our_node_id(),
2507 node_features: nodes[1].node.node_features(),
2508 short_channel_id: chan_1_scid,
2509 channel_features: nodes[1].node.channel_features(),
2510 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2511 cltv_expiry_delta: 100,
2513 pubkey: nodes[2].node.get_our_node_id(),
2514 node_features: nodes[2].node.node_features(),
2515 short_channel_id: chan_2_scid,
2516 channel_features: nodes[2].node.channel_features(),
2517 fee_msat: 100_000_000,
2518 cltv_expiry_delta: 100,
2521 pubkey: nodes[1].node.get_our_node_id(),
2522 node_features: nodes[1].node.node_features(),
2523 short_channel_id: chan_1_scid,
2524 channel_features: nodes[1].node.channel_features(),
2526 cltv_expiry_delta: 100,
2528 pubkey: nodes[2].node.get_our_node_id(),
2529 node_features: nodes[2].node.node_features(),
2530 short_channel_id: chan_2_scid,
2531 channel_features: nodes[2].node.channel_features(),
2532 fee_msat: 100_000_000,
2533 cltv_expiry_delta: 100,
2536 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2538 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2539 let mut second_payment_params = route_params.payment_params.clone();
2540 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2541 // On retry, we'll only be asked for one path (or 100k sats)
2542 route.paths.remove(0);
2543 nodes[0].router.expect_find_route(RouteParameters {
2544 payment_params: second_payment_params,
2545 final_value_msat: amt_msat / 2,
2546 }, Ok(route.clone()));
2548 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2549 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2550 let htlc_updates = SendEvent::from_node(&nodes[0]);
2551 check_added_monitors!(nodes[0], 1);
2552 assert_eq!(htlc_updates.msgs.len(), 1);
2554 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2555 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2556 check_added_monitors!(nodes[1], 1);
2557 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2559 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2560 check_added_monitors!(nodes[0], 1);
2561 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2563 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2564 check_added_monitors!(nodes[0], 1);
2565 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2567 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2568 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2569 check_added_monitors!(nodes[1], 1);
2570 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2572 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2573 check_added_monitors!(nodes[1], 1);
2574 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2576 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2577 check_added_monitors!(nodes[0], 1);
2579 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2580 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2581 check_added_monitors!(nodes[0], 1);
2582 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2584 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2585 check_added_monitors!(nodes[1], 1);
2587 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2588 check_added_monitors!(nodes[1], 1);
2590 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2592 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2593 check_added_monitors!(nodes[0], 1);
2595 let mut events = nodes[0].node.get_and_clear_pending_events();
2596 assert_eq!(events.len(), 2);
2598 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2599 assert_eq!(payment_hash, ev_payment_hash);
2600 assert_eq!(payment_failed_permanently, false);
2602 _ => panic!("Unexpected event"),
2605 Event::PendingHTLCsForwardable { .. } => {},
2606 _ => panic!("Unexpected event"),
2609 nodes[0].node.process_pending_htlc_forwards();
2610 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2611 check_added_monitors!(nodes[0], 1);
2613 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2614 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2616 expect_pending_htlcs_forwardable!(nodes[1]);
2617 check_added_monitors!(nodes[1], 1);
2619 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2620 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2621 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2622 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2624 expect_pending_htlcs_forwardable!(nodes[2]);
2625 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2629 #[cfg(feature = "std")]
2630 fn test_threaded_payment_retries() {
2631 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2632 // a single thread and would happily let multiple threads run retries at the same time. Because
2633 // retries are done by first calculating the amount we need to retry, then dropping the
2634 // relevant lock, then actually sending, we would happily let multiple threads retry the same
2635 // amount at the same time, overpaying our original HTLC!
2636 let chanmon_cfgs = create_chanmon_cfgs(4);
2637 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2638 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2639 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2641 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2642 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2643 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2644 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2646 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2647 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2648 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2649 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2651 let amt_msat = 100_000_000;
2652 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2653 #[cfg(feature = "std")]
2654 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2655 #[cfg(not(feature = "std"))]
2656 let payment_expiry_secs = 60 * 60;
2657 let mut invoice_features = InvoiceFeatures::empty();
2658 invoice_features.set_variable_length_onion_required();
2659 invoice_features.set_payment_secret_required();
2660 invoice_features.set_basic_mpp_optional();
2661 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2662 .with_expiry_time(payment_expiry_secs as u64)
2663 .with_features(invoice_features);
2664 let mut route_params = RouteParameters {
2666 final_value_msat: amt_msat,
2669 let mut route = Route {
2672 pubkey: nodes[1].node.get_our_node_id(),
2673 node_features: nodes[1].node.node_features(),
2674 short_channel_id: chan_1_scid,
2675 channel_features: nodes[1].node.channel_features(),
2677 cltv_expiry_delta: 100,
2679 pubkey: nodes[3].node.get_our_node_id(),
2680 node_features: nodes[2].node.node_features(),
2681 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2682 channel_features: nodes[2].node.channel_features(),
2683 fee_msat: amt_msat / 1000,
2684 cltv_expiry_delta: 100,
2687 pubkey: nodes[2].node.get_our_node_id(),
2688 node_features: nodes[2].node.node_features(),
2689 short_channel_id: chan_3_scid,
2690 channel_features: nodes[2].node.channel_features(),
2692 cltv_expiry_delta: 100,
2694 pubkey: nodes[3].node.get_our_node_id(),
2695 node_features: nodes[3].node.node_features(),
2696 short_channel_id: chan_4_scid,
2697 channel_features: nodes[3].node.channel_features(),
2698 fee_msat: amt_msat - amt_msat / 1000,
2699 cltv_expiry_delta: 100,
2702 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2704 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2706 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2707 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
2708 check_added_monitors!(nodes[0], 2);
2709 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2710 assert_eq!(send_msg_events.len(), 2);
2711 send_msg_events.retain(|msg|
2712 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
2713 // Drop the commitment update for nodes[2], we can just let that one sit pending
2715 *node_id == nodes[1].node.get_our_node_id()
2716 } else { panic!(); }
2719 // from here on out, the retry `RouteParameters` amount will be amt/1000
2720 route_params.final_value_msat /= 1000;
2723 let end_time = Instant::now() + Duration::from_secs(1);
2724 macro_rules! thread_body { () => { {
2725 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
2726 let node_ref = NodePtr::from_node(&nodes[0]);
2728 let node_a = unsafe { &*node_ref.0 };
2729 while Instant::now() < end_time {
2730 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2731 // Ignore if we have any pending events, just always pretend we just got a
2732 // PendingHTLCsForwardable
2733 node_a.node.process_pending_htlc_forwards();
2737 let mut threads = Vec::new();
2738 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
2740 // Back in the main thread, poll pending messages and make sure that we never have more than
2741 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
2742 // there are HTLC messages shoved in while its running. This allows us to test that we never
2743 // generate an additional update_add_htlc until we've fully failed the first.
2744 let mut previously_failed_channels = Vec::new();
2746 assert_eq!(send_msg_events.len(), 1);
2747 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
2748 assert_eq!(send_event.msgs.len(), 1);
2750 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
2751 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
2753 // Note that we only push one route into `expect_find_route` at a time, because that's all
2754 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
2755 // we should still ultimately fail for the same reason - because we're trying to send too
2756 // many HTLCs at once.
2757 let mut new_route_params = route_params.clone();
2758 previously_failed_channels.push(route.paths[0][1].short_channel_id);
2759 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
2760 route.paths[0][1].short_channel_id += 1;
2761 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
2763 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2764 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
2765 // The "normal" commitment_signed_dance delivers the final RAA and then calls
2766 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
2767 // This races with our other threads which may generate an add-HTLCs commitment update via
2768 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
2769 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
2770 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
2771 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
2773 let cur_time = Instant::now();
2774 if cur_time > end_time {
2775 for thread in threads.drain(..) { thread.join().unwrap(); }
2778 // Make sure we have some events to handle when we go around...
2779 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2780 nodes[0].node.process_pending_htlc_forwards();
2781 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2782 check_added_monitors!(nodes[0], 2);
2784 if cur_time > end_time {
2790 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
2791 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
2792 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
2793 // it was last persisted.
2794 let chanmon_cfgs = create_chanmon_cfgs(2);
2795 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2796 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2797 let (persister_a, persister_b, persister_c);
2798 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
2799 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
2800 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2802 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2804 let mut nodes_0_serialized = Vec::new();
2805 if !persist_manager_with_payment {
2806 nodes_0_serialized = nodes[0].node.encode();
2809 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2811 if persist_manager_with_payment {
2812 nodes_0_serialized = nodes[0].node.encode();
2815 nodes[1].node.claim_funds(our_payment_preimage);
2816 check_added_monitors!(nodes[1], 1);
2817 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
2819 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2820 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2821 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
2822 check_added_monitors!(nodes[0], 1);
2824 // The ChannelMonitor should always be the latest version, as we're required to persist it
2825 // during the commitment signed handling.
2826 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2827 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
2829 let events = nodes[0].node.get_and_clear_pending_events();
2830 assert_eq!(events.len(), 2);
2831 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
2832 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
2833 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
2834 // the double-claim that would otherwise appear at the end of this test.
2835 nodes[0].node.timer_tick_occurred();
2836 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2837 assert_eq!(as_broadcasted_txn.len(), 1);
2839 // Ensure that, even after some time, if we restart we still include *something* in the current
2840 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
2841 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
2842 // A naive implementation of the fix here would wipe the pending payments set, causing a
2843 // failure event when we restart.
2844 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2846 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2847 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);
2848 let events = nodes[0].node.get_and_clear_pending_events();
2849 assert!(events.is_empty());
2851 // Ensure that we don't generate any further events even after the channel-closing commitment
2852 // transaction is confirmed on-chain.
2853 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
2854 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2856 let events = nodes[0].node.get_and_clear_pending_events();
2857 assert!(events.is_empty());
2859 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2860 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);
2861 let events = nodes[0].node.get_and_clear_pending_events();
2862 assert!(events.is_empty());
2866 fn no_missing_sent_on_midpoint_reload() {
2867 do_no_missing_sent_on_midpoint_reload(false);
2868 do_no_missing_sent_on_midpoint_reload(true);