1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test the payment retry logic in ChannelManager, including various edge-cases around
11 //! serialization ordering between ChannelManager/ChannelMonitors and ensuring we can still retry
12 //! payments thereafter.
14 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
15 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::chain::keysinterface::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
19 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails};
20 use crate::ln::features::InvoiceFeatures;
22 use crate::ln::msgs::ChannelMessageHandler;
23 use crate::ln::outbound_payment::Retry;
24 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
25 use crate::routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RouteParameters};
26 use crate::routing::scoring::ChannelUsage;
27 use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
28 use crate::util::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
32 use bitcoin::{Block, BlockHeader, TxMerkleNode};
33 use bitcoin::hashes::Hash;
34 use bitcoin::network::constants::Network;
36 use crate::prelude::*;
38 use crate::ln::functional_test_utils::*;
39 use crate::routing::gossip::NodeId;
40 #[cfg(feature = "std")]
42 crate::util::time::tests::SinceEpoch,
43 std::time::{SystemTime, Duration}
48 let chanmon_cfgs = create_chanmon_cfgs(4);
49 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
50 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
51 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
53 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
54 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
55 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
56 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
58 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
59 let path = route.paths[0].clone();
60 route.paths.push(path);
61 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
62 route.paths[0][0].short_channel_id = chan_1_id;
63 route.paths[0][1].short_channel_id = chan_3_id;
64 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
65 route.paths[1][0].short_channel_id = chan_2_id;
66 route.paths[1][1].short_channel_id = chan_4_id;
67 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
68 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
73 let chanmon_cfgs = create_chanmon_cfgs(4);
74 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
75 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
76 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
78 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
79 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
80 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
81 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
83 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
85 let amt_msat = 1_000_000;
86 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
87 let path = route.paths[0].clone();
88 route.paths.push(path);
89 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
90 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
91 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
92 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
93 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
94 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
96 // Initiate the MPP payment.
97 let payment_id = PaymentId(payment_hash.0);
98 let mut route_params = RouteParameters {
99 payment_params: route.payment_params.clone().unwrap(),
100 final_value_msat: amt_msat,
101 final_cltv_expiry_delta: TEST_FINAL_CLTV,
104 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
105 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
106 check_added_monitors!(nodes[0], 2); // one monitor per path
107 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
108 assert_eq!(events.len(), 2);
110 // Pass half of the payment along the success path.
111 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
112 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
114 // Add the HTLC along the first hop.
115 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
116 let (update_add, commitment_signed) = match fail_path_msgs_1 {
117 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 } } => {
118 assert_eq!(update_add_htlcs.len(), 1);
119 assert!(update_fail_htlcs.is_empty());
120 assert!(update_fulfill_htlcs.is_empty());
121 assert!(update_fail_malformed_htlcs.is_empty());
122 assert!(update_fee.is_none());
123 (update_add_htlcs[0].clone(), commitment_signed.clone())
125 _ => panic!("Unexpected event"),
127 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
128 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
130 // Attempt to forward the payment and complete the 2nd path's failure.
131 expect_pending_htlcs_forwardable!(&nodes[2]);
132 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 }]);
133 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
134 assert!(htlc_updates.update_add_htlcs.is_empty());
135 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
136 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
137 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
138 check_added_monitors!(nodes[2], 1);
139 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
140 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
141 let mut events = nodes[0].node.get_and_clear_pending_events();
143 Event::PendingHTLCsForwardable { .. } => {},
144 _ => panic!("Unexpected event")
147 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
149 // Rebalance the channel so the second half of the payment can succeed.
150 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
152 // Retry the second half of the payment and make sure it succeeds.
153 route.paths.remove(0);
154 route_params.final_value_msat = 1_000_000;
155 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
156 nodes[0].router.expect_find_route(route_params, Ok(route));
157 nodes[0].node.process_pending_htlc_forwards();
158 check_added_monitors!(nodes[0], 1);
159 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
160 assert_eq!(events.len(), 1);
161 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
162 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
165 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
166 let chanmon_cfgs = create_chanmon_cfgs(4);
167 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
168 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
169 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
171 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
172 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
173 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
174 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
176 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
177 let path = route.paths[0].clone();
178 route.paths.push(path);
179 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
180 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
181 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
182 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
183 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
184 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
186 // Initiate the MPP payment.
187 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
188 check_added_monitors!(nodes[0], 2); // one monitor per path
189 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
190 assert_eq!(events.len(), 2);
192 // Pass half of the payment along the first path.
193 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
194 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
196 if send_partial_mpp {
197 // Time out the partial MPP
198 for _ in 0..MPP_TIMEOUT_TICKS {
199 nodes[3].node.timer_tick_occurred();
202 // Failed HTLC from node 3 -> 1
203 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
204 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
205 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
206 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
207 check_added_monitors!(nodes[3], 1);
208 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
210 // Failed HTLC from node 1 -> 0
211 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 }]);
212 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
213 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
214 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
215 check_added_monitors!(nodes[1], 1);
216 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
218 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
220 // Pass half of the payment along the second path.
221 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
222 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
224 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
225 for _ in 0..MPP_TIMEOUT_TICKS {
226 nodes[3].node.timer_tick_occurred();
229 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
234 fn mpp_receive_timeout() {
235 do_mpp_receive_timeout(true);
236 do_mpp_receive_timeout(false);
240 fn retry_expired_payment() {
241 let chanmon_cfgs = create_chanmon_cfgs(3);
242 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
243 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
244 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
246 let _chan_0 = create_announced_chan_between_nodes(&nodes, 0, 1);
247 let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1);
248 // Rebalance to find a route
249 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
251 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
253 // Rebalance so that the first hop fails.
254 send_payment(&nodes[1], &vec!(&nodes[2])[..], 2_000_000);
256 // Make sure the payment fails on the first hop.
257 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
258 check_added_monitors!(nodes[0], 1);
259 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
260 assert_eq!(events.len(), 1);
261 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
262 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
263 check_added_monitors!(nodes[1], 0);
264 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
265 expect_pending_htlcs_forwardable!(nodes[1]);
266 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_1.2 }]);
267 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
268 assert!(htlc_updates.update_add_htlcs.is_empty());
269 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
270 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
271 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
272 check_added_monitors!(nodes[1], 1);
273 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
274 commitment_signed_dance!(nodes[0], nodes[1], htlc_updates.commitment_signed, false);
275 expect_payment_failed!(nodes[0], payment_hash, false);
277 // Mine blocks so the payment will have expired.
278 connect_blocks(&nodes[0], 3);
280 // Retry the payment and make sure it errors as expected.
281 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = nodes[0].node.retry_payment(&route, PaymentId(payment_hash.0)) {
282 assert!(err.contains("not found"));
284 panic!("Unexpected error");
289 fn no_pending_leak_on_initial_send_failure() {
290 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
291 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
292 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
293 // pending payment forever and never time it out.
294 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
295 // try, and then check that no pending payment is being tracked.
296 let chanmon_cfgs = create_chanmon_cfgs(2);
297 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
298 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
299 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
301 create_announced_chan_between_nodes(&nodes, 0, 1);
303 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
305 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
306 nodes[1].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
308 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)),
309 true, APIError::ChannelUnavailable { ref err },
310 assert_eq!(err, "Peer for first hop currently disconnected/pending monitor update!"));
312 assert!(!nodes[0].node.has_pending_payments());
315 fn do_retry_with_no_persist(confirm_before_reload: bool) {
316 // If we send a pending payment and `send_payment` returns success, we should always either
317 // return a payment failure event or a payment success event, and on failure the payment should
320 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
321 // always persisted asynchronously), the ChannelManager has to reload some payment data from
322 // ChannelMonitor(s) in some cases. This tests that reloading.
324 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
325 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
326 // which has separate codepaths for "commitment transaction already confirmed" and not.
327 let chanmon_cfgs = create_chanmon_cfgs(3);
328 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
329 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
330 let persister: test_utils::TestPersister;
331 let new_chain_monitor: test_utils::TestChainMonitor;
332 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>;
333 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
335 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
336 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
338 // Serialize the ChannelManager prior to sending payments
339 let nodes_0_serialized = nodes[0].node.encode();
341 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
343 let amt_msat = 1_000_000;
344 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
345 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
346 let route_params = RouteParameters {
347 payment_params: route.payment_params.clone().unwrap(),
348 final_value_msat: amt_msat,
349 final_cltv_expiry_delta: TEST_FINAL_CLTV,
351 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
352 check_added_monitors!(nodes[0], 1);
354 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
355 assert_eq!(events.len(), 1);
356 let payment_event = SendEvent::from_event(events.pop().unwrap());
357 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
359 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
360 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
361 // which would prevent retry.
362 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
363 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
365 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
366 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
367 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
368 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
370 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
372 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
373 if confirm_before_reload {
374 mine_transaction(&nodes[0], &as_commitment_tx);
375 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
378 // The ChannelMonitor should always be the latest version, as we're required to persist it
379 // during the `commitment_signed_dance!()`.
380 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
381 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
383 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
384 // force-close the channel.
385 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
386 assert!(nodes[0].node.list_channels().is_empty());
387 assert!(nodes[0].node.has_pending_payments());
388 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
389 assert_eq!(as_broadcasted_txn.len(), 1);
390 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
392 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
393 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
394 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
396 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
397 // error, as the channel has hit the chain.
398 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
399 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
400 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
401 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
402 assert_eq!(as_err.len(), 1);
404 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
405 assert_eq!(node_id, nodes[1].node.get_our_node_id());
406 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
407 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", &nodes[1].node.get_our_node_id()) });
408 check_added_monitors!(nodes[1], 1);
409 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
411 _ => panic!("Unexpected event"),
413 check_closed_broadcast!(nodes[1], false);
415 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
416 // we close in a moment.
417 nodes[2].node.claim_funds(payment_preimage_1);
418 check_added_monitors!(nodes[2], 1);
419 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
421 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
422 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
423 check_added_monitors!(nodes[1], 1);
424 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
425 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
427 if confirm_before_reload {
428 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
429 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
432 // Create a new channel on which to retry the payment before we fail the payment via the
433 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
434 // connecting several blocks while creating the channel (implying time has passed).
435 create_announced_chan_between_nodes(&nodes, 0, 1);
436 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
438 mine_transaction(&nodes[1], &as_commitment_tx);
439 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
440 assert_eq!(bs_htlc_claim_txn.len(), 1);
441 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
443 if !confirm_before_reload {
444 mine_transaction(&nodes[0], &as_commitment_tx);
446 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
447 expect_payment_sent!(nodes[0], payment_preimage_1);
448 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
449 let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
450 assert_eq!(as_htlc_timeout_txn.len(), 2);
451 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1]);
452 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
453 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
454 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
455 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
457 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
459 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
460 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
462 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
463 // reloaded) via a route over the new channel, which work without issue and eventually be
464 // received and claimed at the recipient just like any other payment.
465 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
467 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
468 // and not the original fee. We also update node[1]'s relevant config as
469 // do_claim_payment_along_route expects us to never overpay.
471 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
472 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
473 .unwrap().lock().unwrap();
474 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
475 let mut new_config = channel.config();
476 new_config.forwarding_fee_base_msat += 100_000;
477 channel.update_config(&new_config);
478 new_route.paths[0][0].fee_msat += 100_000;
481 // Force expiration of the channel's previous config.
482 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
483 nodes[1].node.timer_tick_occurred();
486 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
487 nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
488 check_added_monitors!(nodes[0], 1);
489 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
490 assert_eq!(events.len(), 1);
491 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
492 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
493 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
497 fn retry_with_no_persist() {
498 do_retry_with_no_persist(true);
499 do_retry_with_no_persist(false);
502 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
503 // Test that an off-chain completed payment is not retryable on restart. This was previously
504 // broken for dust payments, but we test for both dust and non-dust payments.
506 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
508 let chanmon_cfgs = create_chanmon_cfgs(3);
509 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
511 let mut manually_accept_config = test_default_channel_config();
512 manually_accept_config.manually_accept_inbound_channels = true;
514 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
516 let first_persister: test_utils::TestPersister;
517 let first_new_chain_monitor: test_utils::TestChainMonitor;
518 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>;
519 let second_persister: test_utils::TestPersister;
520 let second_new_chain_monitor: test_utils::TestChainMonitor;
521 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>;
522 let third_persister: test_utils::TestPersister;
523 let third_new_chain_monitor: test_utils::TestChainMonitor;
524 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>;
526 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
528 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
529 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
530 confirm_transaction(&nodes[0], &funding_tx);
531 confirm_transaction(&nodes[1], &funding_tx);
532 // Ignore the announcement_signatures messages
533 nodes[0].node.get_and_clear_pending_msg_events();
534 nodes[1].node.get_and_clear_pending_msg_events();
535 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
537 // Serialize the ChannelManager prior to sending payments
538 let mut nodes_0_serialized = nodes[0].node.encode();
540 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
541 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 });
543 // The ChannelMonitor should always be the latest version, as we're required to persist it
544 // during the `commitment_signed_dance!()`.
545 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
547 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);
548 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
550 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
551 // force-close the channel.
552 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
553 assert!(nodes[0].node.list_channels().is_empty());
554 assert!(nodes[0].node.has_pending_payments());
555 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
557 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
558 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
560 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
561 // error, as the channel has hit the chain.
562 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
563 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
564 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
565 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
566 assert_eq!(as_err.len(), 1);
567 let bs_commitment_tx;
569 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
570 assert_eq!(node_id, nodes[1].node.get_our_node_id());
571 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
572 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", &nodes[1].node.get_our_node_id()) });
573 check_added_monitors!(nodes[1], 1);
574 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
576 _ => panic!("Unexpected event"),
578 check_closed_broadcast!(nodes[1], false);
580 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
581 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
582 // incoming HTLCs with the same payment hash later.
583 nodes[2].node.fail_htlc_backwards(&payment_hash);
584 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
585 check_added_monitors!(nodes[2], 1);
587 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
588 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
589 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
590 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
591 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
593 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
594 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
595 // after the commitment transaction, so always connect the commitment transaction.
596 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
597 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
599 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
600 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
601 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
602 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
603 assert_eq!(as_htlc_timeout.len(), 1);
605 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
606 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
607 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
608 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
611 // Create a new channel on which to retry the payment before we fail the payment via the
612 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
613 // connecting several blocks while creating the channel (implying time has passed).
614 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
615 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
616 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
618 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
619 // confirming, we will fail as it's considered still-pending...
620 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
621 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
622 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
624 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
625 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
626 // (which should also still work).
627 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
628 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
629 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
631 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
632 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
633 nodes_0_serialized = nodes[0].node.encode();
635 // After the payment failed, we're free to send it again.
636 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id).is_ok());
637 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
639 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);
640 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
642 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
644 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
645 // the payment is not (spuriously) listed as still pending.
646 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id).is_ok());
647 check_added_monitors!(nodes[0], 1);
648 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
649 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
651 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id).is_err());
652 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
654 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
655 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
656 nodes_0_serialized = nodes[0].node.encode();
658 // Check that after reload we can send the payment again (though we shouldn't, since it was
659 // claimed previously).
660 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);
661 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
663 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
665 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
666 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
670 fn test_completed_payment_not_retryable_on_reload() {
671 do_test_completed_payment_not_retryable_on_reload(true);
672 do_test_completed_payment_not_retryable_on_reload(false);
676 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
677 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
678 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
679 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
680 // the ChannelMonitor tells it to.
682 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
683 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
684 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
685 let chanmon_cfgs = create_chanmon_cfgs(2);
686 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
687 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
688 let persister: test_utils::TestPersister;
689 let new_chain_monitor: test_utils::TestChainMonitor;
690 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>;
691 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
693 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
695 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
697 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
698 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
699 check_closed_broadcast!(nodes[0], true);
700 check_added_monitors!(nodes[0], 1);
701 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
703 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
704 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
706 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
707 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
708 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
709 assert_eq!(node_txn.len(), 3);
710 assert_eq!(node_txn[0], node_txn[1]);
711 check_spends!(node_txn[1], funding_tx);
712 check_spends!(node_txn[2], node_txn[1]);
713 let timeout_txn = vec![node_txn[2].clone()];
715 nodes[1].node.claim_funds(payment_preimage);
716 check_added_monitors!(nodes[1], 1);
717 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
719 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
720 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
721 check_closed_broadcast!(nodes[1], true);
722 check_added_monitors!(nodes[1], 1);
723 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
724 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
725 assert_eq!(claim_txn.len(), 1);
726 check_spends!(claim_txn[0], node_txn[1]);
728 header.prev_blockhash = nodes[0].best_block_hash();
729 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
731 if confirm_commitment_tx {
732 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
735 header.prev_blockhash = nodes[0].best_block_hash();
736 let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
739 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
740 connect_block(&nodes[0], &claim_block);
741 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
744 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
745 // returning InProgress. This should cause the claim event to never make its way to the
747 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
748 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
751 connect_blocks(&nodes[0], 1);
753 connect_block(&nodes[0], &claim_block);
756 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
757 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
758 .get_mut(&funding_txo).unwrap().drain().collect();
759 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
760 // If we're testing connection idempotency we may get substantially more.
761 assert!(mon_updates.len() >= 1);
762 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
763 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
765 // If we persist the ChannelManager here, we should get the PaymentSent event after
767 let mut chan_manager_serialized = Vec::new();
768 if !persist_manager_post_event {
769 chan_manager_serialized = nodes[0].node.encode();
772 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
773 // payment sent event.
774 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
775 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
776 for update in mon_updates {
777 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
780 expect_payment_failed!(nodes[0], payment_hash, false);
782 expect_payment_sent!(nodes[0], payment_preimage);
785 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
787 if persist_manager_post_event {
788 chan_manager_serialized = nodes[0].node.encode();
791 // Now reload nodes[0]...
792 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
794 if persist_manager_post_event {
795 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
796 } else if payment_timeout {
797 expect_payment_failed!(nodes[0], payment_hash, false);
799 expect_payment_sent!(nodes[0], payment_preimage);
802 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
803 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
804 // payment events should kick in, leaving us with no pending events here.
805 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
806 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
807 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
811 fn test_dup_htlc_onchain_fails_on_reload() {
812 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
813 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
814 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
815 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
816 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
817 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
821 fn test_fulfill_restart_failure() {
822 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
823 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
824 // again, or fail it, giving us free money.
826 // Of course probably they won't fail it and give us free money, but because we have code to
827 // handle it, we should test the logic for it anyway. We do that here.
828 let chanmon_cfgs = create_chanmon_cfgs(2);
829 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
830 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
831 let persister: test_utils::TestPersister;
832 let new_chain_monitor: test_utils::TestChainMonitor;
833 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>;
834 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
836 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
837 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
839 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
840 // pre-fulfill, which we do by serializing it here.
841 let chan_manager_serialized = nodes[1].node.encode();
842 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
844 nodes[1].node.claim_funds(payment_preimage);
845 check_added_monitors!(nodes[1], 1);
846 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
848 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
849 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
850 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
852 // Now reload nodes[1]...
853 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
855 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
856 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
858 nodes[1].node.fail_htlc_backwards(&payment_hash);
859 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
860 check_added_monitors!(nodes[1], 1);
861 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
862 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
863 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
864 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
865 // it had already considered the payment fulfilled, and now they just got free money.
866 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
870 fn get_ldk_payment_preimage() {
871 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
872 let chanmon_cfgs = create_chanmon_cfgs(2);
873 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
874 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
875 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
876 create_announced_chan_between_nodes(&nodes, 0, 1);
878 let amt_msat = 60_000;
879 let expiry_secs = 60 * 60;
880 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
882 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
883 .with_features(nodes[1].node.invoice_features());
884 let scorer = test_utils::TestScorer::new();
885 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
886 let random_seed_bytes = keys_manager.get_secure_random_bytes();
887 let route = get_route(
888 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
889 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
890 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
891 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
892 check_added_monitors!(nodes[0], 1);
894 // Make sure to use `get_payment_preimage`
895 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
896 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
897 assert_eq!(events.len(), 1);
898 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
899 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
903 fn sent_probe_is_probe_of_sending_node() {
904 let chanmon_cfgs = create_chanmon_cfgs(3);
905 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
906 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
907 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
909 create_announced_chan_between_nodes(&nodes, 0, 1);
910 create_announced_chan_between_nodes(&nodes, 1, 2);
912 // First check we refuse to build a single-hop probe
913 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
914 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
916 // Then build an actual two-hop probing path
917 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
919 match nodes[0].node.send_probe(route.paths[0].clone()) {
920 Ok((payment_hash, payment_id)) => {
921 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
922 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
923 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
928 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
929 check_added_monitors!(nodes[0], 1);
933 fn successful_probe_yields_event() {
934 let chanmon_cfgs = create_chanmon_cfgs(3);
935 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
936 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
937 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
939 create_announced_chan_between_nodes(&nodes, 0, 1);
940 create_announced_chan_between_nodes(&nodes, 1, 2);
942 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
944 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
946 // node[0] -- update_add_htlcs -> node[1]
947 check_added_monitors!(nodes[0], 1);
948 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
949 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
950 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
951 check_added_monitors!(nodes[1], 0);
952 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
953 expect_pending_htlcs_forwardable!(nodes[1]);
955 // node[1] -- update_add_htlcs -> node[2]
956 check_added_monitors!(nodes[1], 1);
957 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
958 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
959 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
960 check_added_monitors!(nodes[2], 0);
961 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
963 // node[1] <- update_fail_htlcs -- node[2]
964 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
965 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
966 check_added_monitors!(nodes[1], 0);
967 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
969 // node[0] <- update_fail_htlcs -- node[1]
970 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
971 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
972 check_added_monitors!(nodes[0], 0);
973 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
975 let mut events = nodes[0].node.get_and_clear_pending_events();
976 assert_eq!(events.len(), 1);
977 match events.drain(..).next().unwrap() {
978 crate::util::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
979 assert_eq!(payment_id, ev_pid);
980 assert_eq!(payment_hash, ev_ph);
987 fn failed_probe_yields_event() {
988 let chanmon_cfgs = create_chanmon_cfgs(3);
989 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
990 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
991 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
993 create_announced_chan_between_nodes(&nodes, 0, 1);
994 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
996 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
998 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
1000 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1002 // node[0] -- update_add_htlcs -> node[1]
1003 check_added_monitors!(nodes[0], 1);
1004 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1005 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1006 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1007 check_added_monitors!(nodes[1], 0);
1008 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1009 expect_pending_htlcs_forwardable!(nodes[1]);
1011 // node[0] <- update_fail_htlcs -- node[1]
1012 check_added_monitors!(nodes[1], 1);
1013 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1014 // Skip the PendingHTLCsForwardable event
1015 let _events = nodes[1].node.get_and_clear_pending_events();
1016 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1017 check_added_monitors!(nodes[0], 0);
1018 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1020 let mut events = nodes[0].node.get_and_clear_pending_events();
1021 assert_eq!(events.len(), 1);
1022 match events.drain(..).next().unwrap() {
1023 crate::util::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1024 assert_eq!(payment_id, ev_pid);
1025 assert_eq!(payment_hash, ev_ph);
1032 fn onchain_failed_probe_yields_event() {
1033 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1035 let chanmon_cfgs = create_chanmon_cfgs(3);
1036 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1037 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1038 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1040 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1041 create_announced_chan_between_nodes(&nodes, 1, 2);
1043 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1045 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1046 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1047 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1049 // node[0] -- update_add_htlcs -> node[1]
1050 check_added_monitors!(nodes[0], 1);
1051 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1052 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1053 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1054 check_added_monitors!(nodes[1], 0);
1055 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1056 expect_pending_htlcs_forwardable!(nodes[1]);
1058 check_added_monitors!(nodes[1], 1);
1059 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1061 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1062 // Node A, which after 6 confirmations should result in a probe failure event.
1063 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1064 confirm_transaction(&nodes[0], &bs_txn[0]);
1065 check_closed_broadcast!(&nodes[0], true);
1066 check_added_monitors!(nodes[0], 1);
1068 let mut events = nodes[0].node.get_and_clear_pending_events();
1069 assert_eq!(events.len(), 2);
1070 let mut found_probe_failed = false;
1071 for event in events.drain(..) {
1073 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1074 assert_eq!(payment_id, ev_pid);
1075 assert_eq!(payment_hash, ev_ph);
1076 found_probe_failed = true;
1078 Event::ChannelClosed { .. } => {},
1082 assert!(found_probe_failed);
1086 fn claimed_send_payment_idempotent() {
1087 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1088 let chanmon_cfgs = create_chanmon_cfgs(2);
1089 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1090 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1091 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1093 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1095 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1096 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1098 macro_rules! check_send_rejected {
1100 // If we try to resend a new payment with a different payment_hash but with the same
1101 // payment_id, it should be rejected.
1102 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1104 Err(PaymentSendFailure::DuplicatePayment) => {},
1105 _ => panic!("Unexpected send result: {:?}", send_result),
1108 // Further, if we try to send a spontaneous payment with the same payment_id it should
1109 // also be rejected.
1110 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1112 Err(PaymentSendFailure::DuplicatePayment) => {},
1113 _ => panic!("Unexpected send result: {:?}", send_result),
1118 check_send_rejected!();
1120 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1121 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1122 // we must remain just as idempotent as we were before.
1123 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1125 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1126 nodes[0].node.timer_tick_occurred();
1129 check_send_rejected!();
1131 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1132 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1133 // the payment complete. However, they could have called `send_payment` while the event was
1134 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1135 // after the event is handled a duplicate payment should sitll be rejected.
1136 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1137 check_send_rejected!();
1139 // If relatively little time has passed, a duplicate payment should still fail.
1140 nodes[0].node.timer_tick_occurred();
1141 check_send_rejected!();
1143 // However, after some time has passed (at least more than the one timer tick above), a
1144 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1145 // references to the old payment data.
1146 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1147 nodes[0].node.timer_tick_occurred();
1150 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1151 check_added_monitors!(nodes[0], 1);
1152 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1153 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1157 fn abandoned_send_payment_idempotent() {
1158 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1160 let chanmon_cfgs = create_chanmon_cfgs(2);
1161 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1162 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1163 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1165 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1167 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1168 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1170 macro_rules! check_send_rejected {
1172 // If we try to resend a new payment with a different payment_hash but with the same
1173 // payment_id, it should be rejected.
1174 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1176 Err(PaymentSendFailure::DuplicatePayment) => {},
1177 _ => panic!("Unexpected send result: {:?}", send_result),
1180 // Further, if we try to send a spontaneous payment with the same payment_id it should
1181 // also be rejected.
1182 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1184 Err(PaymentSendFailure::DuplicatePayment) => {},
1185 _ => panic!("Unexpected send result: {:?}", send_result),
1190 check_send_rejected!();
1192 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1193 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1195 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1197 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1198 nodes[0].node.timer_tick_occurred();
1200 check_send_rejected!();
1202 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash);
1204 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1205 // failed payment back.
1206 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1207 check_added_monitors!(nodes[0], 1);
1208 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1209 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1212 #[derive(PartialEq)]
1213 enum InterceptTest {
1220 fn test_trivial_inflight_htlc_tracking(){
1221 // In this test, we test three scenarios:
1222 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1223 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1224 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1225 let chanmon_cfgs = create_chanmon_cfgs(3);
1226 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1227 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1228 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1230 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1231 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1233 // Send and claim the payment. Inflight HTLCs should be empty.
1234 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 500000);
1235 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1236 check_added_monitors!(nodes[0], 1);
1237 pass_along_route(&nodes[0], &[&vec!(&nodes[1], &nodes[2])[..]], 500000, payment_hash, payment_secret);
1238 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], payment_preimage);
1240 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1242 let mut node_0_per_peer_lock;
1243 let mut node_0_peer_state_lock;
1244 let mut node_1_per_peer_lock;
1245 let mut node_1_peer_state_lock;
1246 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1247 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1249 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1250 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1251 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1252 channel_1.get_short_channel_id().unwrap()
1254 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1255 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1256 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1257 channel_2.get_short_channel_id().unwrap()
1260 assert_eq!(chan_1_used_liquidity, None);
1261 assert_eq!(chan_2_used_liquidity, None);
1263 let pending_payments = nodes[0].node.list_recent_payments();
1264 assert_eq!(pending_payments.len(), 1);
1265 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1267 // Remove fulfilled payment
1268 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1269 nodes[0].node.timer_tick_occurred();
1272 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1273 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 500000);
1275 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1277 let mut node_0_per_peer_lock;
1278 let mut node_0_peer_state_lock;
1279 let mut node_1_per_peer_lock;
1280 let mut node_1_peer_state_lock;
1281 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1282 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1284 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1285 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1286 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1287 channel_1.get_short_channel_id().unwrap()
1289 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1290 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1291 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1292 channel_2.get_short_channel_id().unwrap()
1295 // First hop accounts for expected 1000 msat fee
1296 assert_eq!(chan_1_used_liquidity, Some(501000));
1297 assert_eq!(chan_2_used_liquidity, Some(500000));
1299 let pending_payments = nodes[0].node.list_recent_payments();
1300 assert_eq!(pending_payments.len(), 1);
1301 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1303 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1304 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1306 // Remove fulfilled payment
1307 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1308 nodes[0].node.timer_tick_occurred();
1312 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1314 let mut node_0_per_peer_lock;
1315 let mut node_0_peer_state_lock;
1316 let mut node_1_per_peer_lock;
1317 let mut node_1_peer_state_lock;
1318 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1319 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1321 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1322 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1323 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1324 channel_1.get_short_channel_id().unwrap()
1326 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1327 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1328 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1329 channel_2.get_short_channel_id().unwrap()
1332 assert_eq!(chan_1_used_liquidity, None);
1333 assert_eq!(chan_2_used_liquidity, None);
1336 let pending_payments = nodes[0].node.list_recent_payments();
1337 assert_eq!(pending_payments.len(), 0);
1341 fn test_holding_cell_inflight_htlcs() {
1342 let chanmon_cfgs = create_chanmon_cfgs(2);
1343 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1344 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1345 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1346 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1348 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1349 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1351 // Queue up two payments - one will be delivered right away, one immediately goes into the
1352 // holding cell as nodes[0] is AwaitingRAA.
1354 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1355 check_added_monitors!(nodes[0], 1);
1356 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1357 check_added_monitors!(nodes[0], 0);
1360 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1363 let mut node_0_per_peer_lock;
1364 let mut node_0_peer_state_lock;
1365 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1367 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1368 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1369 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1370 channel.get_short_channel_id().unwrap()
1373 assert_eq!(used_liquidity, Some(2000000));
1376 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1377 nodes[0].node.get_and_clear_pending_msg_events();
1381 fn intercepted_payment() {
1382 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1383 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1384 // payment or (b) fail the payment.
1385 do_test_intercepted_payment(InterceptTest::Forward);
1386 do_test_intercepted_payment(InterceptTest::Fail);
1387 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1388 do_test_intercepted_payment(InterceptTest::Timeout);
1391 fn do_test_intercepted_payment(test: InterceptTest) {
1392 let chanmon_cfgs = create_chanmon_cfgs(3);
1393 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1395 let mut zero_conf_chan_config = test_default_channel_config();
1396 zero_conf_chan_config.manually_accept_inbound_channels = true;
1397 let mut intercept_forwards_config = test_default_channel_config();
1398 intercept_forwards_config.accept_intercept_htlcs = true;
1399 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1401 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1402 let scorer = test_utils::TestScorer::new();
1403 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1405 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1407 let amt_msat = 100_000;
1408 let intercept_scid = nodes[1].node.get_intercept_scid();
1409 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1410 .with_route_hints(vec![
1411 RouteHint(vec![RouteHintHop {
1412 src_node_id: nodes[1].node.get_our_node_id(),
1413 short_channel_id: intercept_scid,
1416 proportional_millionths: 0,
1418 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1419 htlc_minimum_msat: None,
1420 htlc_maximum_msat: None,
1423 .with_features(nodes[2].node.invoice_features());
1424 let route_params = RouteParameters {
1426 final_value_msat: amt_msat,
1427 final_cltv_expiry_delta: TEST_FINAL_CLTV,
1429 let route = get_route(
1430 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1431 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1432 route_params.final_cltv_expiry_delta, nodes[0].logger, &scorer, &random_seed_bytes
1435 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1436 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1437 let payment_event = {
1439 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1440 assert_eq!(added_monitors.len(), 1);
1441 added_monitors.clear();
1443 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1444 assert_eq!(events.len(), 1);
1445 SendEvent::from_event(events.remove(0))
1447 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1448 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1450 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1451 let events = nodes[1].node.get_and_clear_pending_events();
1452 assert_eq!(events.len(), 1);
1453 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1454 crate::util::events::Event::HTLCIntercepted {
1455 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1457 assert_eq!(pmt_hash, payment_hash);
1458 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1459 assert_eq!(short_channel_id, intercept_scid);
1460 (intercept_id, expected_outbound_amount_msat)
1465 // Check for unknown channel id error.
1466 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();
1467 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()) });
1469 if test == InterceptTest::Fail {
1470 // Ensure we can fail the intercepted payment back.
1471 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1472 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1473 nodes[1].node.process_pending_htlc_forwards();
1474 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1475 check_added_monitors!(&nodes[1], 1);
1476 assert!(update_fail.update_fail_htlcs.len() == 1);
1477 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1478 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1479 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1481 // Ensure the payment fails with the expected error.
1482 let fail_conditions = PaymentFailedConditions::new()
1483 .blamed_scid(intercept_scid)
1484 .blamed_chan_closed(true)
1485 .expected_htlc_error_data(0x4000 | 10, &[]);
1486 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1487 } else if test == InterceptTest::Forward {
1488 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1489 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1490 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();
1491 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1492 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1494 // Open the just-in-time channel so the payment can then be forwarded.
1495 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1497 // Finally, forward the intercepted payment through and claim it.
1498 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1499 expect_pending_htlcs_forwardable!(nodes[1]);
1501 let payment_event = {
1503 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1504 assert_eq!(added_monitors.len(), 1);
1505 added_monitors.clear();
1507 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1508 assert_eq!(events.len(), 1);
1509 SendEvent::from_event(events.remove(0))
1511 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1512 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1513 expect_pending_htlcs_forwardable!(nodes[2]);
1515 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1516 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1517 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1518 let events = nodes[0].node.get_and_clear_pending_events();
1519 assert_eq!(events.len(), 2);
1521 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1522 assert_eq!(payment_preimage, *ev_preimage);
1523 assert_eq!(payment_hash, *ev_hash);
1524 assert_eq!(fee_paid_msat, &Some(1000));
1526 _ => panic!("Unexpected event")
1529 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1530 assert_eq!(hash, Some(payment_hash));
1532 _ => panic!("Unexpected event")
1534 } else if test == InterceptTest::Timeout {
1535 let mut block = Block {
1536 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1539 connect_block(&nodes[0], &block);
1540 connect_block(&nodes[1], &block);
1541 for _ in 0..TEST_FINAL_CLTV {
1542 block.header.prev_blockhash = block.block_hash();
1543 connect_block(&nodes[0], &block);
1544 connect_block(&nodes[1], &block);
1546 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1547 check_added_monitors!(nodes[1], 1);
1548 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1549 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1550 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1551 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1552 assert!(htlc_timeout_updates.update_fee.is_none());
1554 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1555 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1556 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1558 // Check for unknown intercept id error.
1559 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1560 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();
1561 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1562 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1563 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1567 #[derive(PartialEq)]
1578 fn automatic_retries() {
1579 do_automatic_retries(AutoRetry::Success);
1580 do_automatic_retries(AutoRetry::Spontaneous);
1581 do_automatic_retries(AutoRetry::FailAttempts);
1582 do_automatic_retries(AutoRetry::FailTimeout);
1583 do_automatic_retries(AutoRetry::FailOnRestart);
1584 do_automatic_retries(AutoRetry::FailOnRetry);
1586 fn do_automatic_retries(test: AutoRetry) {
1587 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1589 let chanmon_cfgs = create_chanmon_cfgs(3);
1590 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1591 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1594 let new_chain_monitor;
1595 let node_0_deserialized;
1597 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1598 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1599 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1601 // Marshall data to send the payment
1602 #[cfg(feature = "std")]
1603 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1604 #[cfg(not(feature = "std"))]
1605 let payment_expiry_secs = 60 * 60;
1606 let amt_msat = 1000;
1607 let mut invoice_features = InvoiceFeatures::empty();
1608 invoice_features.set_variable_length_onion_required();
1609 invoice_features.set_payment_secret_required();
1610 invoice_features.set_basic_mpp_optional();
1611 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1612 .with_expiry_time(payment_expiry_secs as u64)
1613 .with_features(invoice_features);
1614 let route_params = RouteParameters {
1616 final_value_msat: amt_msat,
1617 final_cltv_expiry_delta: TEST_FINAL_CLTV,
1619 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1621 macro_rules! pass_failed_attempt_with_retry_along_path {
1622 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1623 // Send a payment attempt that fails due to lack of liquidity on the second hop
1624 check_added_monitors!(nodes[0], 1);
1625 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1626 let mut update_add = update_0.update_add_htlcs[0].clone();
1627 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1628 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1629 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1630 nodes[1].node.process_pending_htlc_forwards();
1631 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1632 vec![HTLCDestination::NextHopChannel {
1633 node_id: Some(nodes[2].node.get_our_node_id()),
1634 channel_id: $failing_channel_id,
1636 nodes[1].node.process_pending_htlc_forwards();
1637 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1638 check_added_monitors!(&nodes[1], 1);
1639 assert!(update_1.update_fail_htlcs.len() == 1);
1640 let fail_msg = update_1.update_fail_htlcs[0].clone();
1641 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1642 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1644 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1645 let mut events = nodes[0].node.get_and_clear_pending_events();
1646 assert_eq!(events.len(), 2);
1648 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1649 assert_eq!(payment_hash, ev_payment_hash);
1650 assert_eq!(payment_failed_permanently, false);
1652 _ => panic!("Unexpected event"),
1654 if $expect_pending_htlcs_forwardable {
1656 Event::PendingHTLCsForwardable { .. } => {},
1657 _ => panic!("Unexpected event"),
1661 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1662 assert_eq!(payment_hash, ev_payment_hash);
1664 _ => panic!("Unexpected event"),
1670 if test == AutoRetry::Success {
1671 // Test that we can succeed on the first retry.
1672 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1673 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1675 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1676 // attempt, since the initial second hop channel will be excluded from pathfinding
1677 create_announced_chan_between_nodes(&nodes, 1, 2);
1679 // We retry payments in `process_pending_htlc_forwards`
1680 nodes[0].node.process_pending_htlc_forwards();
1681 check_added_monitors!(nodes[0], 1);
1682 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1683 assert_eq!(msg_events.len(), 1);
1684 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1685 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1686 } else if test == AutoRetry::Spontaneous {
1687 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1688 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1690 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1691 // attempt, since the initial second hop channel will be excluded from pathfinding
1692 create_announced_chan_between_nodes(&nodes, 1, 2);
1694 // We retry payments in `process_pending_htlc_forwards`
1695 nodes[0].node.process_pending_htlc_forwards();
1696 check_added_monitors!(nodes[0], 1);
1697 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1698 assert_eq!(msg_events.len(), 1);
1699 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1700 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1701 } else if test == AutoRetry::FailAttempts {
1702 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1703 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1704 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1706 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1707 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1708 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1710 // We retry payments in `process_pending_htlc_forwards`
1711 nodes[0].node.process_pending_htlc_forwards();
1712 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1714 // Ensure we won't retry a second time.
1715 nodes[0].node.process_pending_htlc_forwards();
1716 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1717 assert_eq!(msg_events.len(), 0);
1718 } else if test == AutoRetry::FailTimeout {
1719 #[cfg(not(feature = "no-std"))] {
1720 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1721 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
1722 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1724 // Advance the time so the second attempt fails due to timeout.
1725 SinceEpoch::advance(Duration::from_secs(61));
1727 // Make sure we don't retry again.
1728 nodes[0].node.process_pending_htlc_forwards();
1729 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1730 assert_eq!(msg_events.len(), 0);
1732 nodes[0].node.abandon_payment(PaymentId(payment_hash.0));
1733 let mut events = nodes[0].node.get_and_clear_pending_events();
1734 assert_eq!(events.len(), 1);
1736 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1737 assert_eq!(payment_hash, *ev_payment_hash);
1738 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1740 _ => panic!("Unexpected event"),
1743 } else if test == AutoRetry::FailOnRestart {
1744 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1745 // attempts remaining prior to restart.
1746 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1747 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1749 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1750 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1751 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1753 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1754 nodes[0].node.process_pending_htlc_forwards();
1755 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1757 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1758 let node_encoded = nodes[0].node.encode();
1759 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1760 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1762 // Make sure we don't retry again.
1763 nodes[0].node.process_pending_htlc_forwards();
1764 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1765 assert_eq!(msg_events.len(), 0);
1767 nodes[0].node.abandon_payment(PaymentId(payment_hash.0));
1768 let mut events = nodes[0].node.get_and_clear_pending_events();
1769 assert_eq!(events.len(), 1);
1771 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1772 assert_eq!(payment_hash, *ev_payment_hash);
1773 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1775 _ => panic!("Unexpected event"),
1777 } else if test == AutoRetry::FailOnRetry {
1778 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1779 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1781 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1782 // fail to find a route.
1783 nodes[0].node.process_pending_htlc_forwards();
1784 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1785 assert_eq!(msg_events.len(), 0);
1787 let mut events = nodes[0].node.get_and_clear_pending_events();
1788 assert_eq!(events.len(), 1);
1790 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1791 assert_eq!(payment_hash, *ev_payment_hash);
1792 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1794 _ => panic!("Unexpected event"),
1800 fn auto_retry_partial_failure() {
1801 // Test that we'll retry appropriately on send partial failure and retry partial failure.
1802 let chanmon_cfgs = create_chanmon_cfgs(2);
1803 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1804 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1805 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1807 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1808 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1809 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1811 // Marshall data to send the payment
1812 let amt_msat = 20_000;
1813 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1814 #[cfg(feature = "std")]
1815 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1816 #[cfg(not(feature = "std"))]
1817 let payment_expiry_secs = 60 * 60;
1818 let mut invoice_features = InvoiceFeatures::empty();
1819 invoice_features.set_variable_length_onion_required();
1820 invoice_features.set_payment_secret_required();
1821 invoice_features.set_basic_mpp_optional();
1822 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1823 .with_expiry_time(payment_expiry_secs as u64)
1824 .with_features(invoice_features);
1825 let route_params = RouteParameters {
1827 final_value_msat: amt_msat,
1828 final_cltv_expiry_delta: TEST_FINAL_CLTV,
1831 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1832 // second (for the initial send path2 over chan_2) fails.
1833 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1834 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1835 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1836 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1837 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1838 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1839 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1841 // Configure the initial send, retry1 and retry2's paths.
1842 let send_route = Route {
1845 pubkey: nodes[1].node.get_our_node_id(),
1846 node_features: nodes[1].node.node_features(),
1847 short_channel_id: chan_1_id,
1848 channel_features: nodes[1].node.channel_features(),
1849 fee_msat: amt_msat / 2,
1850 cltv_expiry_delta: 100,
1853 pubkey: nodes[1].node.get_our_node_id(),
1854 node_features: nodes[1].node.node_features(),
1855 short_channel_id: chan_2_id,
1856 channel_features: nodes[1].node.channel_features(),
1857 fee_msat: amt_msat / 2,
1858 cltv_expiry_delta: 100,
1861 payment_params: Some(route_params.payment_params.clone()),
1863 let retry_1_route = Route {
1866 pubkey: nodes[1].node.get_our_node_id(),
1867 node_features: nodes[1].node.node_features(),
1868 short_channel_id: chan_1_id,
1869 channel_features: nodes[1].node.channel_features(),
1870 fee_msat: amt_msat / 4,
1871 cltv_expiry_delta: 100,
1874 pubkey: nodes[1].node.get_our_node_id(),
1875 node_features: nodes[1].node.node_features(),
1876 short_channel_id: chan_3_id,
1877 channel_features: nodes[1].node.channel_features(),
1878 fee_msat: amt_msat / 4,
1879 cltv_expiry_delta: 100,
1882 payment_params: Some(route_params.payment_params.clone()),
1884 let retry_2_route = Route {
1887 pubkey: nodes[1].node.get_our_node_id(),
1888 node_features: nodes[1].node.node_features(),
1889 short_channel_id: chan_1_id,
1890 channel_features: nodes[1].node.channel_features(),
1891 fee_msat: amt_msat / 4,
1892 cltv_expiry_delta: 100,
1895 payment_params: Some(route_params.payment_params.clone()),
1897 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1898 nodes[0].router.expect_find_route(RouteParameters {
1899 payment_params: route_params.payment_params.clone(),
1900 final_value_msat: amt_msat / 2, final_cltv_expiry_delta: TEST_FINAL_CLTV
1901 }, Ok(retry_1_route));
1902 nodes[0].router.expect_find_route(RouteParameters {
1903 payment_params: route_params.payment_params.clone(),
1904 final_value_msat: amt_msat / 4, final_cltv_expiry_delta: TEST_FINAL_CLTV
1905 }, Ok(retry_2_route));
1907 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1908 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1909 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1910 assert_eq!(closed_chan_events.len(), 2);
1911 match closed_chan_events[0] {
1912 Event::ChannelClosed { .. } => {},
1913 _ => panic!("Unexpected event"),
1915 match closed_chan_events[1] {
1916 Event::ChannelClosed { .. } => {},
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,
2030 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2033 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2034 let err = nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap_err();
2035 if let PaymentSendFailure::AllFailedResendSafe(_) = err {
2036 } else { panic!("Unexpected error"); }
2037 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2038 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 1); // channel close event
2039 check_added_monitors!(nodes[0], 2);
2043 fn fails_paying_after_rejected_by_payee() {
2044 let chanmon_cfgs = create_chanmon_cfgs(2);
2045 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2046 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2047 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2049 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2051 // Marshall data to send the payment
2052 let amt_msat = 20_000;
2053 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2054 #[cfg(feature = "std")]
2055 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2056 #[cfg(not(feature = "std"))]
2057 let payment_expiry_secs = 60 * 60;
2058 let mut invoice_features = InvoiceFeatures::empty();
2059 invoice_features.set_variable_length_onion_required();
2060 invoice_features.set_payment_secret_required();
2061 invoice_features.set_basic_mpp_optional();
2062 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2063 .with_expiry_time(payment_expiry_secs as u64)
2064 .with_features(invoice_features);
2065 let route_params = RouteParameters {
2067 final_value_msat: amt_msat,
2068 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2071 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2072 check_added_monitors!(nodes[0], 1);
2073 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2074 assert_eq!(events.len(), 1);
2075 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2076 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2077 check_added_monitors!(nodes[1], 0);
2078 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2079 expect_pending_htlcs_forwardable!(nodes[1]);
2080 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2082 nodes[1].node.fail_htlc_backwards(&payment_hash);
2083 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2084 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash);
2088 fn retry_multi_path_single_failed_payment() {
2089 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2090 let chanmon_cfgs = create_chanmon_cfgs(2);
2091 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2092 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2093 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2095 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2096 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2098 let amt_msat = 100_010_000;
2100 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2101 #[cfg(feature = "std")]
2102 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2103 #[cfg(not(feature = "std"))]
2104 let payment_expiry_secs = 60 * 60;
2105 let mut invoice_features = InvoiceFeatures::empty();
2106 invoice_features.set_variable_length_onion_required();
2107 invoice_features.set_payment_secret_required();
2108 invoice_features.set_basic_mpp_optional();
2109 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2110 .with_expiry_time(payment_expiry_secs as u64)
2111 .with_features(invoice_features);
2112 let route_params = RouteParameters {
2113 payment_params: payment_params.clone(),
2114 final_value_msat: amt_msat,
2115 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2118 let chans = nodes[0].node.list_usable_channels();
2119 let mut route = Route {
2122 pubkey: nodes[1].node.get_our_node_id(),
2123 node_features: nodes[1].node.node_features(),
2124 short_channel_id: chans[0].short_channel_id.unwrap(),
2125 channel_features: nodes[1].node.channel_features(),
2127 cltv_expiry_delta: 100,
2130 pubkey: nodes[1].node.get_our_node_id(),
2131 node_features: nodes[1].node.node_features(),
2132 short_channel_id: chans[1].short_channel_id.unwrap(),
2133 channel_features: nodes[1].node.channel_features(),
2134 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2135 cltv_expiry_delta: 100,
2138 payment_params: Some(payment_params),
2140 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2141 // On retry, split the payment across both channels.
2142 route.paths[0][0].fee_msat = 50_000_001;
2143 route.paths[1][0].fee_msat = 50_000_000;
2144 nodes[0].router.expect_find_route(RouteParameters {
2145 payment_params: route.payment_params.clone().unwrap(),
2146 // Note that the second request here requests the amount we originally failed to send,
2147 // not the amount remaining on the full payment, which should be changed.
2148 final_value_msat: 100_000_001, final_cltv_expiry_delta: TEST_FINAL_CLTV
2149 }, Ok(route.clone()));
2152 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2153 // The initial send attempt, 2 paths
2154 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2155 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2156 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2157 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2158 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2161 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2162 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2163 assert_eq!(htlc_msgs.len(), 2);
2164 check_added_monitors!(nodes[0], 2);
2168 fn immediate_retry_on_failure() {
2169 // Tests that we can/will retry immediately after a failure
2170 let chanmon_cfgs = create_chanmon_cfgs(2);
2171 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2172 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2173 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2175 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2176 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2178 let amt_msat = 100_000_001;
2179 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2180 #[cfg(feature = "std")]
2181 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2182 #[cfg(not(feature = "std"))]
2183 let payment_expiry_secs = 60 * 60;
2184 let mut invoice_features = InvoiceFeatures::empty();
2185 invoice_features.set_variable_length_onion_required();
2186 invoice_features.set_payment_secret_required();
2187 invoice_features.set_basic_mpp_optional();
2188 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2189 .with_expiry_time(payment_expiry_secs as u64)
2190 .with_features(invoice_features);
2191 let route_params = RouteParameters {
2193 final_value_msat: amt_msat,
2194 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2197 let chans = nodes[0].node.list_usable_channels();
2198 let mut route = Route {
2201 pubkey: nodes[1].node.get_our_node_id(),
2202 node_features: nodes[1].node.node_features(),
2203 short_channel_id: chans[0].short_channel_id.unwrap(),
2204 channel_features: nodes[1].node.channel_features(),
2205 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2206 cltv_expiry_delta: 100,
2209 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2211 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2212 // On retry, split the payment across both channels.
2213 route.paths.push(route.paths[0].clone());
2214 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2215 route.paths[0][0].fee_msat = 50_000_000;
2216 route.paths[1][0].fee_msat = 50_000_001;
2217 nodes[0].router.expect_find_route(RouteParameters {
2218 payment_params: route_params.payment_params.clone(),
2219 final_value_msat: amt_msat, final_cltv_expiry_delta: TEST_FINAL_CLTV
2220 }, Ok(route.clone()));
2222 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2223 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2224 assert_eq!(htlc_msgs.len(), 2);
2225 check_added_monitors!(nodes[0], 2);
2229 fn no_extra_retries_on_back_to_back_fail() {
2230 // In a previous release, we had a race where we may exceed the payment retry count if we
2231 // get two failures in a row with the second having `all_paths_failed` set.
2232 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2233 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2234 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2235 // pending which we will see later. Thus, when we previously removed the retry tracking map
2236 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2237 // retry entry even though more events for the same payment were still pending. This led to
2238 // us retrying a payment again even though we'd already given up on it.
2240 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2241 // is used to remove the payment retry counter entries instead. This tests for the specific
2242 // excess-retry case while also testing `PaymentFailed` generation.
2244 let chanmon_cfgs = create_chanmon_cfgs(3);
2245 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2246 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2247 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2249 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2250 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2252 let amt_msat = 200_000_000;
2253 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2254 #[cfg(feature = "std")]
2255 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2256 #[cfg(not(feature = "std"))]
2257 let payment_expiry_secs = 60 * 60;
2258 let mut invoice_features = InvoiceFeatures::empty();
2259 invoice_features.set_variable_length_onion_required();
2260 invoice_features.set_payment_secret_required();
2261 invoice_features.set_basic_mpp_optional();
2262 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2263 .with_expiry_time(payment_expiry_secs as u64)
2264 .with_features(invoice_features);
2265 let route_params = RouteParameters {
2267 final_value_msat: amt_msat,
2268 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2271 let mut route = Route {
2274 pubkey: nodes[1].node.get_our_node_id(),
2275 node_features: nodes[1].node.node_features(),
2276 short_channel_id: chan_1_scid,
2277 channel_features: nodes[1].node.channel_features(),
2278 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2279 cltv_expiry_delta: 100,
2281 pubkey: nodes[2].node.get_our_node_id(),
2282 node_features: nodes[2].node.node_features(),
2283 short_channel_id: chan_2_scid,
2284 channel_features: nodes[2].node.channel_features(),
2285 fee_msat: 100_000_000,
2286 cltv_expiry_delta: 100,
2289 pubkey: nodes[1].node.get_our_node_id(),
2290 node_features: nodes[1].node.node_features(),
2291 short_channel_id: chan_1_scid,
2292 channel_features: nodes[1].node.channel_features(),
2293 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2294 cltv_expiry_delta: 100,
2296 pubkey: nodes[2].node.get_our_node_id(),
2297 node_features: nodes[2].node.node_features(),
2298 short_channel_id: chan_2_scid,
2299 channel_features: nodes[2].node.channel_features(),
2300 fee_msat: 100_000_000,
2301 cltv_expiry_delta: 100,
2304 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2306 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2307 let mut second_payment_params = route_params.payment_params.clone();
2308 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2309 // On retry, we'll only return one path
2310 route.paths.remove(1);
2311 route.paths[0][1].fee_msat = amt_msat;
2312 nodes[0].router.expect_find_route(RouteParameters {
2313 payment_params: second_payment_params,
2314 final_value_msat: amt_msat, final_cltv_expiry_delta: TEST_FINAL_CLTV,
2315 }, Ok(route.clone()));
2317 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2318 let htlc_updates = SendEvent::from_node(&nodes[0]);
2319 check_added_monitors!(nodes[0], 1);
2320 assert_eq!(htlc_updates.msgs.len(), 1);
2322 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2323 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2324 check_added_monitors!(nodes[1], 1);
2325 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2327 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2328 check_added_monitors!(nodes[0], 1);
2329 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2331 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2332 check_added_monitors!(nodes[0], 1);
2333 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2335 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2336 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2337 check_added_monitors!(nodes[1], 1);
2338 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2340 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2341 check_added_monitors!(nodes[1], 1);
2342 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2344 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2345 check_added_monitors!(nodes[0], 1);
2347 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2348 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2349 check_added_monitors!(nodes[0], 1);
2350 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2352 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2353 check_added_monitors!(nodes[1], 1);
2354 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2356 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2357 check_added_monitors!(nodes[1], 1);
2358 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2360 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2361 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2362 check_added_monitors!(nodes[0], 1);
2364 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2365 check_added_monitors!(nodes[0], 1);
2366 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2368 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2369 check_added_monitors!(nodes[1], 1);
2370 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2371 check_added_monitors!(nodes[1], 1);
2372 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2374 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2375 check_added_monitors!(nodes[0], 1);
2377 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2378 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2381 // Previously, we retried payments in an event consumer, which would retry each
2382 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2383 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2384 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2385 // by adding the `PaymentFailed` event.
2387 // Because we now retry payments as a batch, we simply return a single-path route in the
2388 // second, batched, request, have that fail, ensure the payment was abandoned.
2389 let mut events = nodes[0].node.get_and_clear_pending_events();
2390 assert_eq!(events.len(), 4);
2392 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2393 assert_eq!(payment_hash, ev_payment_hash);
2394 assert_eq!(payment_failed_permanently, false);
2396 _ => panic!("Unexpected event"),
2399 Event::PendingHTLCsForwardable { .. } => {},
2400 _ => panic!("Unexpected event"),
2403 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2404 assert_eq!(payment_hash, ev_payment_hash);
2405 assert_eq!(payment_failed_permanently, false);
2407 _ => panic!("Unexpected event"),
2410 Event::PendingHTLCsForwardable { .. } => {},
2411 _ => panic!("Unexpected event"),
2414 nodes[0].node.process_pending_htlc_forwards();
2415 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2416 check_added_monitors!(nodes[0], 1);
2418 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2419 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2420 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2421 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2422 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2424 let mut events = nodes[0].node.get_and_clear_pending_events();
2425 assert_eq!(events.len(), 2);
2427 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2428 assert_eq!(payment_hash, ev_payment_hash);
2429 assert_eq!(payment_failed_permanently, false);
2431 _ => panic!("Unexpected event"),
2434 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
2435 assert_eq!(payment_hash, *ev_payment_hash);
2436 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2438 _ => panic!("Unexpected event"),
2443 fn test_simple_partial_retry() {
2444 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2445 // full amount of the payment, rather than only the missing amount. Here we simply test for
2446 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2447 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2449 let chanmon_cfgs = create_chanmon_cfgs(3);
2450 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2451 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2452 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2454 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2455 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2457 let amt_msat = 200_000_000;
2458 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2459 #[cfg(feature = "std")]
2460 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2461 #[cfg(not(feature = "std"))]
2462 let payment_expiry_secs = 60 * 60;
2463 let mut invoice_features = InvoiceFeatures::empty();
2464 invoice_features.set_variable_length_onion_required();
2465 invoice_features.set_payment_secret_required();
2466 invoice_features.set_basic_mpp_optional();
2467 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2468 .with_expiry_time(payment_expiry_secs as u64)
2469 .with_features(invoice_features);
2470 let route_params = RouteParameters {
2472 final_value_msat: amt_msat,
2473 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2476 let mut route = Route {
2479 pubkey: nodes[1].node.get_our_node_id(),
2480 node_features: nodes[1].node.node_features(),
2481 short_channel_id: chan_1_scid,
2482 channel_features: nodes[1].node.channel_features(),
2483 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2484 cltv_expiry_delta: 100,
2486 pubkey: nodes[2].node.get_our_node_id(),
2487 node_features: nodes[2].node.node_features(),
2488 short_channel_id: chan_2_scid,
2489 channel_features: nodes[2].node.channel_features(),
2490 fee_msat: 100_000_000,
2491 cltv_expiry_delta: 100,
2494 pubkey: nodes[1].node.get_our_node_id(),
2495 node_features: nodes[1].node.node_features(),
2496 short_channel_id: chan_1_scid,
2497 channel_features: nodes[1].node.channel_features(),
2499 cltv_expiry_delta: 100,
2501 pubkey: nodes[2].node.get_our_node_id(),
2502 node_features: nodes[2].node.node_features(),
2503 short_channel_id: chan_2_scid,
2504 channel_features: nodes[2].node.channel_features(),
2505 fee_msat: 100_000_000,
2506 cltv_expiry_delta: 100,
2509 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2511 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2512 let mut second_payment_params = route_params.payment_params.clone();
2513 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2514 // On retry, we'll only be asked for one path (or 100k sats)
2515 route.paths.remove(0);
2516 nodes[0].router.expect_find_route(RouteParameters {
2517 payment_params: second_payment_params,
2518 final_value_msat: amt_msat / 2, final_cltv_expiry_delta: TEST_FINAL_CLTV,
2519 }, Ok(route.clone()));
2521 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2522 let htlc_updates = SendEvent::from_node(&nodes[0]);
2523 check_added_monitors!(nodes[0], 1);
2524 assert_eq!(htlc_updates.msgs.len(), 1);
2526 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2527 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2528 check_added_monitors!(nodes[1], 1);
2529 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2531 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2532 check_added_monitors!(nodes[0], 1);
2533 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2535 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2536 check_added_monitors!(nodes[0], 1);
2537 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2539 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2540 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2541 check_added_monitors!(nodes[1], 1);
2542 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2544 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2545 check_added_monitors!(nodes[1], 1);
2546 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2548 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2549 check_added_monitors!(nodes[0], 1);
2551 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2552 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2553 check_added_monitors!(nodes[0], 1);
2554 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2556 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2557 check_added_monitors!(nodes[1], 1);
2559 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2560 check_added_monitors!(nodes[1], 1);
2562 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2564 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2565 check_added_monitors!(nodes[0], 1);
2567 let mut events = nodes[0].node.get_and_clear_pending_events();
2568 assert_eq!(events.len(), 2);
2570 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2571 assert_eq!(payment_hash, ev_payment_hash);
2572 assert_eq!(payment_failed_permanently, false);
2574 _ => panic!("Unexpected event"),
2577 Event::PendingHTLCsForwardable { .. } => {},
2578 _ => panic!("Unexpected event"),
2581 nodes[0].node.process_pending_htlc_forwards();
2582 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2583 check_added_monitors!(nodes[0], 1);
2585 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2586 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2588 expect_pending_htlcs_forwardable!(nodes[1]);
2589 check_added_monitors!(nodes[1], 1);
2591 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2592 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2593 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2594 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2596 expect_pending_htlcs_forwardable!(nodes[2]);
2597 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);