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}
47 fn retry_single_path_payment() {
48 let chanmon_cfgs = create_chanmon_cfgs(3);
49 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
50 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
51 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
53 let _chan_0 = create_announced_chan_between_nodes(&nodes, 0, 1);
54 let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1);
55 // Rebalance to find a route
56 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
58 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
60 // Rebalance so that the first hop fails.
61 send_payment(&nodes[1], &vec!(&nodes[2])[..], 2_000_000);
63 // Make sure the payment fails on the first hop.
64 let payment_id = PaymentId(payment_hash.0);
65 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), payment_id).unwrap();
66 check_added_monitors!(nodes[0], 1);
67 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
68 assert_eq!(events.len(), 1);
69 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
70 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
71 check_added_monitors!(nodes[1], 0);
72 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
73 expect_pending_htlcs_forwardable!(nodes[1]);
74 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 }]);
75 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
76 assert!(htlc_updates.update_add_htlcs.is_empty());
77 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
78 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
79 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
80 check_added_monitors!(nodes[1], 1);
81 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
82 commitment_signed_dance!(nodes[0], nodes[1], htlc_updates.commitment_signed, false);
83 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
85 // Rebalance the channel so the retry succeeds.
86 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
88 // Mine two blocks (we expire retries after 3, so this will check that we don't expire early)
89 connect_blocks(&nodes[0], 2);
91 // Retry the payment and make sure it succeeds.
92 nodes[0].node.retry_payment(&route, payment_id).unwrap();
93 check_added_monitors!(nodes[0], 1);
94 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
95 assert_eq!(events.len(), 1);
96 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 100_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
97 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
102 let chanmon_cfgs = create_chanmon_cfgs(4);
103 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
104 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
105 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
107 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
108 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
109 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
110 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
112 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
113 let path = route.paths[0].clone();
114 route.paths.push(path);
115 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
116 route.paths[0][0].short_channel_id = chan_1_id;
117 route.paths[0][1].short_channel_id = chan_3_id;
118 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
119 route.paths[1][0].short_channel_id = chan_2_id;
120 route.paths[1][1].short_channel_id = chan_4_id;
121 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
122 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
127 let chanmon_cfgs = create_chanmon_cfgs(4);
128 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
129 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
130 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
132 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
133 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
134 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
135 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
137 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
139 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 1_000_000);
140 let path = route.paths[0].clone();
141 route.paths.push(path);
142 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
143 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
144 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
145 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
146 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
147 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
149 // Initiate the MPP payment.
150 let payment_id = PaymentId(payment_hash.0);
151 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), payment_id).unwrap();
152 check_added_monitors!(nodes[0], 2); // one monitor per path
153 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
154 assert_eq!(events.len(), 2);
156 // Pass half of the payment along the success path.
157 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
158 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
160 // Add the HTLC along the first hop.
161 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
162 let (update_add, commitment_signed) = match fail_path_msgs_1 {
163 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 } } => {
164 assert_eq!(update_add_htlcs.len(), 1);
165 assert!(update_fail_htlcs.is_empty());
166 assert!(update_fulfill_htlcs.is_empty());
167 assert!(update_fail_malformed_htlcs.is_empty());
168 assert!(update_fee.is_none());
169 (update_add_htlcs[0].clone(), commitment_signed.clone())
171 _ => panic!("Unexpected event"),
173 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
174 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
176 // Attempt to forward the payment and complete the 2nd path's failure.
177 expect_pending_htlcs_forwardable!(&nodes[2]);
178 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 }]);
179 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
180 assert!(htlc_updates.update_add_htlcs.is_empty());
181 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
182 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
183 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
184 check_added_monitors!(nodes[2], 1);
185 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
186 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
187 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
189 // Rebalance the channel so the second half of the payment can succeed.
190 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
192 // Make sure it errors as expected given a too-large amount.
193 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = nodes[0].node.retry_payment(&route, payment_id) {
194 assert!(err.contains("over total_payment_amt_msat"));
195 } else { panic!("Unexpected error"); }
197 // Make sure it errors as expected given the wrong payment_id.
198 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = nodes[0].node.retry_payment(&route, PaymentId([0; 32])) {
199 assert!(err.contains("not found"));
200 } else { panic!("Unexpected error"); }
202 // Retry the second half of the payment and make sure it succeeds.
203 let mut path = route.clone();
204 path.paths.remove(0);
205 nodes[0].node.retry_payment(&path, payment_id).unwrap();
206 check_added_monitors!(nodes[0], 1);
207 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
208 assert_eq!(events.len(), 1);
209 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
210 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
213 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
214 let chanmon_cfgs = create_chanmon_cfgs(4);
215 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
216 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
217 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
219 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
220 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
221 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
222 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
224 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
225 let path = route.paths[0].clone();
226 route.paths.push(path);
227 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
228 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
229 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
230 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
231 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
232 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
234 // Initiate the MPP payment.
235 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
236 check_added_monitors!(nodes[0], 2); // one monitor per path
237 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
238 assert_eq!(events.len(), 2);
240 // Pass half of the payment along the first path.
241 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
242 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
244 if send_partial_mpp {
245 // Time out the partial MPP
246 for _ in 0..MPP_TIMEOUT_TICKS {
247 nodes[3].node.timer_tick_occurred();
250 // Failed HTLC from node 3 -> 1
251 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
252 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
253 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
254 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
255 check_added_monitors!(nodes[3], 1);
256 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
258 // Failed HTLC from node 1 -> 0
259 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 }]);
260 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
261 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
262 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
263 check_added_monitors!(nodes[1], 1);
264 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
266 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
268 // Pass half of the payment along the second path.
269 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
270 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
272 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
273 for _ in 0..MPP_TIMEOUT_TICKS {
274 nodes[3].node.timer_tick_occurred();
277 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
282 fn mpp_receive_timeout() {
283 do_mpp_receive_timeout(true);
284 do_mpp_receive_timeout(false);
288 fn retry_expired_payment() {
289 let chanmon_cfgs = create_chanmon_cfgs(3);
290 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
291 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
292 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
294 let _chan_0 = create_announced_chan_between_nodes(&nodes, 0, 1);
295 let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1);
296 // Rebalance to find a route
297 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
299 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
301 // Rebalance so that the first hop fails.
302 send_payment(&nodes[1], &vec!(&nodes[2])[..], 2_000_000);
304 // Make sure the payment fails on the first hop.
305 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
306 check_added_monitors!(nodes[0], 1);
307 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
308 assert_eq!(events.len(), 1);
309 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
310 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
311 check_added_monitors!(nodes[1], 0);
312 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
313 expect_pending_htlcs_forwardable!(nodes[1]);
314 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 }]);
315 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
316 assert!(htlc_updates.update_add_htlcs.is_empty());
317 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
318 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
319 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
320 check_added_monitors!(nodes[1], 1);
321 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
322 commitment_signed_dance!(nodes[0], nodes[1], htlc_updates.commitment_signed, false);
323 expect_payment_failed!(nodes[0], payment_hash, false);
325 // Mine blocks so the payment will have expired.
326 connect_blocks(&nodes[0], 3);
328 // Retry the payment and make sure it errors as expected.
329 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = nodes[0].node.retry_payment(&route, PaymentId(payment_hash.0)) {
330 assert!(err.contains("not found"));
332 panic!("Unexpected error");
337 fn no_pending_leak_on_initial_send_failure() {
338 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
339 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
340 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
341 // pending payment forever and never time it out.
342 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
343 // try, and then check that no pending payment is being tracked.
344 let chanmon_cfgs = create_chanmon_cfgs(2);
345 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
346 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
347 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
349 create_announced_chan_between_nodes(&nodes, 0, 1);
351 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
353 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
354 nodes[1].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
356 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)),
357 true, APIError::ChannelUnavailable { ref err },
358 assert_eq!(err, "Peer for first hop currently disconnected/pending monitor update!"));
360 assert!(!nodes[0].node.has_pending_payments());
363 fn do_retry_with_no_persist(confirm_before_reload: bool) {
364 // If we send a pending payment and `send_payment` returns success, we should always either
365 // return a payment failure event or a payment success event, and on failure the payment should
368 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
369 // always persisted asynchronously), the ChannelManager has to reload some payment data from
370 // ChannelMonitor(s) in some cases. This tests that reloading.
372 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
373 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
374 // which has separate codepaths for "commitment transaction already confirmed" and not.
375 let chanmon_cfgs = create_chanmon_cfgs(3);
376 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
377 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
378 let persister: test_utils::TestPersister;
379 let new_chain_monitor: test_utils::TestChainMonitor;
380 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>;
381 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
383 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
384 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
386 // Serialize the ChannelManager prior to sending payments
387 let nodes_0_serialized = nodes[0].node.encode();
389 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
391 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
392 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
393 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
394 check_added_monitors!(nodes[0], 1);
396 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
397 assert_eq!(events.len(), 1);
398 let payment_event = SendEvent::from_event(events.pop().unwrap());
399 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
401 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
402 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
403 // which would prevent retry.
404 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
405 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
407 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
408 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
409 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
410 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
412 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
414 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
415 if confirm_before_reload {
416 mine_transaction(&nodes[0], &as_commitment_tx);
417 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
420 // The ChannelMonitor should always be the latest version, as we're required to persist it
421 // during the `commitment_signed_dance!()`.
422 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
423 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
425 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
426 // force-close the channel.
427 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
428 assert!(nodes[0].node.list_channels().is_empty());
429 assert!(nodes[0].node.has_pending_payments());
430 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
431 assert_eq!(as_broadcasted_txn.len(), 1);
432 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
434 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
435 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();
436 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
438 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
439 // error, as the channel has hit the chain.
440 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();
441 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
442 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
443 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
444 assert_eq!(as_err.len(), 1);
446 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
447 assert_eq!(node_id, nodes[1].node.get_our_node_id());
448 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
449 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()) });
450 check_added_monitors!(nodes[1], 1);
451 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
453 _ => panic!("Unexpected event"),
455 check_closed_broadcast!(nodes[1], false);
457 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
458 // we close in a moment.
459 nodes[2].node.claim_funds(payment_preimage_1);
460 check_added_monitors!(nodes[2], 1);
461 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
463 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
464 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
465 check_added_monitors!(nodes[1], 1);
466 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
467 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
469 if confirm_before_reload {
470 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
471 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
474 // Create a new channel on which to retry the payment before we fail the payment via the
475 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
476 // connecting several blocks while creating the channel (implying time has passed).
477 create_announced_chan_between_nodes(&nodes, 0, 1);
478 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
480 mine_transaction(&nodes[1], &as_commitment_tx);
481 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
482 assert_eq!(bs_htlc_claim_txn.len(), 1);
483 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
485 if !confirm_before_reload {
486 mine_transaction(&nodes[0], &as_commitment_tx);
488 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
489 expect_payment_sent!(nodes[0], payment_preimage_1);
490 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
491 let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
492 assert_eq!(as_htlc_timeout_txn.len(), 2);
493 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1]);
494 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
495 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
496 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
497 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
499 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
501 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
502 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
504 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
505 // reloaded) via a route over the new channel, which work without issue and eventually be
506 // received and claimed at the recipient just like any other payment.
507 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
509 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
510 // and not the original fee. We also update node[1]'s relevant config as
511 // do_claim_payment_along_route expects us to never overpay.
513 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
514 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
515 .unwrap().lock().unwrap();
516 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
517 let mut new_config = channel.config();
518 new_config.forwarding_fee_base_msat += 100_000;
519 channel.update_config(&new_config);
520 new_route.paths[0][0].fee_msat += 100_000;
523 // Force expiration of the channel's previous config.
524 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
525 nodes[1].node.timer_tick_occurred();
528 assert!(nodes[0].node.retry_payment(&new_route, payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
529 nodes[0].node.retry_payment(&new_route, PaymentId(payment_hash.0)).unwrap();
530 check_added_monitors!(nodes[0], 1);
531 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
532 assert_eq!(events.len(), 1);
533 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
534 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
535 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
539 fn retry_with_no_persist() {
540 do_retry_with_no_persist(true);
541 do_retry_with_no_persist(false);
544 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
545 // Test that an off-chain completed payment is not retryable on restart. This was previously
546 // broken for dust payments, but we test for both dust and non-dust payments.
548 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
550 let chanmon_cfgs = create_chanmon_cfgs(3);
551 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
553 let mut manually_accept_config = test_default_channel_config();
554 manually_accept_config.manually_accept_inbound_channels = true;
556 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
558 let first_persister: test_utils::TestPersister;
559 let first_new_chain_monitor: test_utils::TestChainMonitor;
560 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>;
561 let second_persister: test_utils::TestPersister;
562 let second_new_chain_monitor: test_utils::TestChainMonitor;
563 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>;
564 let third_persister: test_utils::TestPersister;
565 let third_new_chain_monitor: test_utils::TestChainMonitor;
566 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>;
568 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
570 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
571 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
572 confirm_transaction(&nodes[0], &funding_tx);
573 confirm_transaction(&nodes[1], &funding_tx);
574 // Ignore the announcement_signatures messages
575 nodes[0].node.get_and_clear_pending_msg_events();
576 nodes[1].node.get_and_clear_pending_msg_events();
577 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
579 // Serialize the ChannelManager prior to sending payments
580 let mut nodes_0_serialized = nodes[0].node.encode();
582 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
583 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 });
585 // The ChannelMonitor should always be the latest version, as we're required to persist it
586 // during the `commitment_signed_dance!()`.
587 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
589 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);
590 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
592 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
593 // force-close the channel.
594 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
595 assert!(nodes[0].node.list_channels().is_empty());
596 assert!(nodes[0].node.has_pending_payments());
597 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
599 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();
600 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
602 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
603 // error, as the channel has hit the chain.
604 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();
605 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
606 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
607 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
608 assert_eq!(as_err.len(), 1);
609 let bs_commitment_tx;
611 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
612 assert_eq!(node_id, nodes[1].node.get_our_node_id());
613 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
614 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()) });
615 check_added_monitors!(nodes[1], 1);
616 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
618 _ => panic!("Unexpected event"),
620 check_closed_broadcast!(nodes[1], false);
622 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
623 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
624 // incoming HTLCs with the same payment hash later.
625 nodes[2].node.fail_htlc_backwards(&payment_hash);
626 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
627 check_added_monitors!(nodes[2], 1);
629 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
630 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
631 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
632 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
633 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
635 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
636 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
637 // after the commitment transaction, so always connect the commitment transaction.
638 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
639 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
641 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
642 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
643 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
644 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
645 assert_eq!(as_htlc_timeout.len(), 1);
647 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
648 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
649 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
650 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
653 // Create a new channel on which to retry the payment before we fail the payment via the
654 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
655 // connecting several blocks while creating the channel (implying time has passed).
656 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
657 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
658 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
660 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
661 // confirming, we will fail as it's considered still-pending...
662 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
663 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
664 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
666 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
667 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
668 // (which should also still work).
669 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
670 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
671 // We set mpp_parts_remain to avoid having abandon_payment called
672 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
674 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
675 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
676 nodes_0_serialized = nodes[0].node.encode();
678 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
679 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
681 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);
682 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
684 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
686 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
687 // the payment is not (spuriously) listed as still pending.
688 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
689 check_added_monitors!(nodes[0], 1);
690 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
691 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
693 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
694 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
696 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
697 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
698 nodes_0_serialized = nodes[0].node.encode();
700 // Ensure that after reload we cannot retry the payment.
701 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);
702 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
704 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
706 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
707 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
711 fn test_completed_payment_not_retryable_on_reload() {
712 do_test_completed_payment_not_retryable_on_reload(true);
713 do_test_completed_payment_not_retryable_on_reload(false);
717 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
718 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
719 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
720 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
721 // the ChannelMonitor tells it to.
723 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
724 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
725 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
726 let chanmon_cfgs = create_chanmon_cfgs(2);
727 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
728 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
729 let persister: test_utils::TestPersister;
730 let new_chain_monitor: test_utils::TestChainMonitor;
731 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>;
732 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
734 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
736 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
738 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
739 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
740 check_closed_broadcast!(nodes[0], true);
741 check_added_monitors!(nodes[0], 1);
742 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
744 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
745 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
747 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
748 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
749 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
750 assert_eq!(node_txn.len(), 3);
751 assert_eq!(node_txn[0], node_txn[1]);
752 check_spends!(node_txn[1], funding_tx);
753 check_spends!(node_txn[2], node_txn[1]);
754 let timeout_txn = vec![node_txn[2].clone()];
756 nodes[1].node.claim_funds(payment_preimage);
757 check_added_monitors!(nodes[1], 1);
758 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
760 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
761 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
762 check_closed_broadcast!(nodes[1], true);
763 check_added_monitors!(nodes[1], 1);
764 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
765 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
766 assert_eq!(claim_txn.len(), 1);
767 check_spends!(claim_txn[0], node_txn[1]);
769 header.prev_blockhash = nodes[0].best_block_hash();
770 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
772 if confirm_commitment_tx {
773 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
776 header.prev_blockhash = nodes[0].best_block_hash();
777 let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
780 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
781 connect_block(&nodes[0], &claim_block);
782 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
785 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
786 // returning InProgress. This should cause the claim event to never make its way to the
788 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
789 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
792 connect_blocks(&nodes[0], 1);
794 connect_block(&nodes[0], &claim_block);
797 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
798 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
799 .get_mut(&funding_txo).unwrap().drain().collect();
800 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
801 // If we're testing connection idempotency we may get substantially more.
802 assert!(mon_updates.len() >= 1);
803 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
804 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
806 // If we persist the ChannelManager here, we should get the PaymentSent event after
808 let mut chan_manager_serialized = Vec::new();
809 if !persist_manager_post_event {
810 chan_manager_serialized = nodes[0].node.encode();
813 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
814 // payment sent event.
815 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
816 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
817 for update in mon_updates {
818 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
821 expect_payment_failed!(nodes[0], payment_hash, false);
823 expect_payment_sent!(nodes[0], payment_preimage);
826 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
828 if persist_manager_post_event {
829 chan_manager_serialized = nodes[0].node.encode();
832 // Now reload nodes[0]...
833 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
835 if persist_manager_post_event {
836 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
837 } else if payment_timeout {
838 expect_payment_failed!(nodes[0], payment_hash, false);
840 expect_payment_sent!(nodes[0], payment_preimage);
843 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
844 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
845 // payment events should kick in, leaving us with no pending events here.
846 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
847 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
848 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
852 fn test_dup_htlc_onchain_fails_on_reload() {
853 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
854 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
855 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
856 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
857 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
858 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
862 fn test_fulfill_restart_failure() {
863 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
864 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
865 // again, or fail it, giving us free money.
867 // Of course probably they won't fail it and give us free money, but because we have code to
868 // handle it, we should test the logic for it anyway. We do that here.
869 let chanmon_cfgs = create_chanmon_cfgs(2);
870 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
871 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
872 let persister: test_utils::TestPersister;
873 let new_chain_monitor: test_utils::TestChainMonitor;
874 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>;
875 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
877 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
878 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
880 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
881 // pre-fulfill, which we do by serializing it here.
882 let chan_manager_serialized = nodes[1].node.encode();
883 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
885 nodes[1].node.claim_funds(payment_preimage);
886 check_added_monitors!(nodes[1], 1);
887 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
889 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
890 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
891 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
893 // Now reload nodes[1]...
894 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
896 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
897 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
899 nodes[1].node.fail_htlc_backwards(&payment_hash);
900 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
901 check_added_monitors!(nodes[1], 1);
902 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
903 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
904 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
905 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
906 // it had already considered the payment fulfilled, and now they just got free money.
907 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
911 fn get_ldk_payment_preimage() {
912 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
913 let chanmon_cfgs = create_chanmon_cfgs(2);
914 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
915 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
916 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
917 create_announced_chan_between_nodes(&nodes, 0, 1);
919 let amt_msat = 60_000;
920 let expiry_secs = 60 * 60;
921 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
923 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
924 .with_features(nodes[1].node.invoice_features());
925 let scorer = test_utils::TestScorer::new();
926 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
927 let random_seed_bytes = keys_manager.get_secure_random_bytes();
928 let route = get_route(
929 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
930 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
931 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
932 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
933 check_added_monitors!(nodes[0], 1);
935 // Make sure to use `get_payment_preimage`
936 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
937 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
938 assert_eq!(events.len(), 1);
939 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
940 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
944 fn sent_probe_is_probe_of_sending_node() {
945 let chanmon_cfgs = create_chanmon_cfgs(3);
946 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
947 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
948 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
950 create_announced_chan_between_nodes(&nodes, 0, 1);
951 create_announced_chan_between_nodes(&nodes, 1, 2);
953 // First check we refuse to build a single-hop probe
954 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
955 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
957 // Then build an actual two-hop probing path
958 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
960 match nodes[0].node.send_probe(route.paths[0].clone()) {
961 Ok((payment_hash, payment_id)) => {
962 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
963 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
964 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
969 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
970 check_added_monitors!(nodes[0], 1);
974 fn successful_probe_yields_event() {
975 let chanmon_cfgs = create_chanmon_cfgs(3);
976 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
977 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
978 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
980 create_announced_chan_between_nodes(&nodes, 0, 1);
981 create_announced_chan_between_nodes(&nodes, 1, 2);
983 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
985 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
987 // node[0] -- update_add_htlcs -> node[1]
988 check_added_monitors!(nodes[0], 1);
989 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
990 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
991 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
992 check_added_monitors!(nodes[1], 0);
993 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
994 expect_pending_htlcs_forwardable!(nodes[1]);
996 // node[1] -- update_add_htlcs -> node[2]
997 check_added_monitors!(nodes[1], 1);
998 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
999 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1000 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1001 check_added_monitors!(nodes[2], 0);
1002 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
1004 // node[1] <- update_fail_htlcs -- node[2]
1005 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1006 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1007 check_added_monitors!(nodes[1], 0);
1008 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1010 // node[0] <- update_fail_htlcs -- node[1]
1011 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1012 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1013 check_added_monitors!(nodes[0], 0);
1014 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1016 let mut events = nodes[0].node.get_and_clear_pending_events();
1017 assert_eq!(events.len(), 1);
1018 match events.drain(..).next().unwrap() {
1019 crate::util::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1020 assert_eq!(payment_id, ev_pid);
1021 assert_eq!(payment_hash, ev_ph);
1028 fn failed_probe_yields_event() {
1029 let chanmon_cfgs = create_chanmon_cfgs(3);
1030 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1031 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1032 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1034 create_announced_chan_between_nodes(&nodes, 0, 1);
1035 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1037 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1039 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
1041 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1043 // node[0] -- update_add_htlcs -> node[1]
1044 check_added_monitors!(nodes[0], 1);
1045 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1046 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1047 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1048 check_added_monitors!(nodes[1], 0);
1049 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1050 expect_pending_htlcs_forwardable!(nodes[1]);
1052 // node[0] <- update_fail_htlcs -- node[1]
1053 check_added_monitors!(nodes[1], 1);
1054 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1055 // Skip the PendingHTLCsForwardable event
1056 let _events = nodes[1].node.get_and_clear_pending_events();
1057 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1058 check_added_monitors!(nodes[0], 0);
1059 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1061 let mut events = nodes[0].node.get_and_clear_pending_events();
1062 assert_eq!(events.len(), 1);
1063 match events.drain(..).next().unwrap() {
1064 crate::util::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1065 assert_eq!(payment_id, ev_pid);
1066 assert_eq!(payment_hash, ev_ph);
1073 fn onchain_failed_probe_yields_event() {
1074 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1076 let chanmon_cfgs = create_chanmon_cfgs(3);
1077 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1078 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1079 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1081 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1082 create_announced_chan_between_nodes(&nodes, 1, 2);
1084 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1086 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1087 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1088 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1090 // node[0] -- update_add_htlcs -> node[1]
1091 check_added_monitors!(nodes[0], 1);
1092 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1093 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1094 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1095 check_added_monitors!(nodes[1], 0);
1096 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1097 expect_pending_htlcs_forwardable!(nodes[1]);
1099 check_added_monitors!(nodes[1], 1);
1100 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1102 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1103 // Node A, which after 6 confirmations should result in a probe failure event.
1104 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1105 confirm_transaction(&nodes[0], &bs_txn[0]);
1106 check_closed_broadcast!(&nodes[0], true);
1107 check_added_monitors!(nodes[0], 1);
1109 let mut events = nodes[0].node.get_and_clear_pending_events();
1110 assert_eq!(events.len(), 2);
1111 let mut found_probe_failed = false;
1112 for event in events.drain(..) {
1114 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1115 assert_eq!(payment_id, ev_pid);
1116 assert_eq!(payment_hash, ev_ph);
1117 found_probe_failed = true;
1119 Event::ChannelClosed { .. } => {},
1123 assert!(found_probe_failed);
1127 fn claimed_send_payment_idempotent() {
1128 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1129 let chanmon_cfgs = create_chanmon_cfgs(2);
1130 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1131 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1132 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1134 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1136 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1137 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1139 macro_rules! check_send_rejected {
1141 // If we try to resend a new payment with a different payment_hash but with the same
1142 // payment_id, it should be rejected.
1143 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1145 Err(PaymentSendFailure::DuplicatePayment) => {},
1146 _ => panic!("Unexpected send result: {:?}", send_result),
1149 // Further, if we try to send a spontaneous payment with the same payment_id it should
1150 // also be rejected.
1151 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1153 Err(PaymentSendFailure::DuplicatePayment) => {},
1154 _ => panic!("Unexpected send result: {:?}", send_result),
1159 check_send_rejected!();
1161 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1162 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1163 // we must remain just as idempotent as we were before.
1164 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1166 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1167 nodes[0].node.timer_tick_occurred();
1170 check_send_rejected!();
1172 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1173 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1174 // the payment complete. However, they could have called `send_payment` while the event was
1175 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1176 // after the event is handled a duplicate payment should sitll be rejected.
1177 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1178 check_send_rejected!();
1180 // If relatively little time has passed, a duplicate payment should still fail.
1181 nodes[0].node.timer_tick_occurred();
1182 check_send_rejected!();
1184 // However, after some time has passed (at least more than the one timer tick above), a
1185 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1186 // references to the old payment data.
1187 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1188 nodes[0].node.timer_tick_occurred();
1191 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1192 check_added_monitors!(nodes[0], 1);
1193 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1194 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1198 fn abandoned_send_payment_idempotent() {
1199 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1201 let chanmon_cfgs = create_chanmon_cfgs(2);
1202 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1203 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1204 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1206 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1208 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1209 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1211 macro_rules! check_send_rejected {
1213 // If we try to resend a new payment with a different payment_hash but with the same
1214 // payment_id, it should be rejected.
1215 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1217 Err(PaymentSendFailure::DuplicatePayment) => {},
1218 _ => panic!("Unexpected send result: {:?}", send_result),
1221 // Further, if we try to send a spontaneous payment with the same payment_id it should
1222 // also be rejected.
1223 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1225 Err(PaymentSendFailure::DuplicatePayment) => {},
1226 _ => panic!("Unexpected send result: {:?}", send_result),
1231 check_send_rejected!();
1233 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1234 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1236 pass_failed_payment_back_no_abandon(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash);
1237 check_send_rejected!();
1239 // Until we abandon the payment, no matter how many timer ticks pass, we still cannot reuse the
1241 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1242 nodes[0].node.timer_tick_occurred();
1244 check_send_rejected!();
1246 nodes[0].node.abandon_payment(payment_id);
1247 get_event!(nodes[0], Event::PaymentFailed);
1249 // However, we can reuse the PaymentId immediately after we `abandon_payment`.
1250 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1251 check_added_monitors!(nodes[0], 1);
1252 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1253 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1256 #[derive(PartialEq)]
1257 enum InterceptTest {
1264 fn test_trivial_inflight_htlc_tracking(){
1265 // In this test, we test three scenarios:
1266 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1267 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1268 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1269 let chanmon_cfgs = create_chanmon_cfgs(3);
1270 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1271 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1272 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1274 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1275 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1277 // Send and claim the payment. Inflight HTLCs should be empty.
1278 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 500000);
1279 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1280 check_added_monitors!(nodes[0], 1);
1281 pass_along_route(&nodes[0], &[&vec!(&nodes[1], &nodes[2])[..]], 500000, payment_hash, payment_secret);
1282 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], payment_preimage);
1284 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1286 let mut node_0_per_peer_lock;
1287 let mut node_0_peer_state_lock;
1288 let mut node_1_per_peer_lock;
1289 let mut node_1_peer_state_lock;
1290 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1291 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1293 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1294 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1295 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1296 channel_1.get_short_channel_id().unwrap()
1298 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1299 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1300 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1301 channel_2.get_short_channel_id().unwrap()
1304 assert_eq!(chan_1_used_liquidity, None);
1305 assert_eq!(chan_2_used_liquidity, None);
1307 let pending_payments = nodes[0].node.list_recent_payments();
1308 assert_eq!(pending_payments.len(), 1);
1309 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1311 // Remove fulfilled payment
1312 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1313 nodes[0].node.timer_tick_occurred();
1316 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1317 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 500000);
1319 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1321 let mut node_0_per_peer_lock;
1322 let mut node_0_peer_state_lock;
1323 let mut node_1_per_peer_lock;
1324 let mut node_1_peer_state_lock;
1325 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1326 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1328 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1329 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1330 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1331 channel_1.get_short_channel_id().unwrap()
1333 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1334 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1335 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1336 channel_2.get_short_channel_id().unwrap()
1339 // First hop accounts for expected 1000 msat fee
1340 assert_eq!(chan_1_used_liquidity, Some(501000));
1341 assert_eq!(chan_2_used_liquidity, Some(500000));
1343 let pending_payments = nodes[0].node.list_recent_payments();
1344 assert_eq!(pending_payments.len(), 1);
1345 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1347 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1348 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1350 // Remove fulfilled payment
1351 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1352 nodes[0].node.timer_tick_occurred();
1356 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1358 let mut node_0_per_peer_lock;
1359 let mut node_0_peer_state_lock;
1360 let mut node_1_per_peer_lock;
1361 let mut node_1_peer_state_lock;
1362 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1363 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1365 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1366 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1367 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1368 channel_1.get_short_channel_id().unwrap()
1370 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1371 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1372 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1373 channel_2.get_short_channel_id().unwrap()
1376 assert_eq!(chan_1_used_liquidity, None);
1377 assert_eq!(chan_2_used_liquidity, None);
1380 let pending_payments = nodes[0].node.list_recent_payments();
1381 assert_eq!(pending_payments.len(), 0);
1385 fn test_holding_cell_inflight_htlcs() {
1386 let chanmon_cfgs = create_chanmon_cfgs(2);
1387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1389 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1390 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1392 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1393 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1395 // Queue up two payments - one will be delivered right away, one immediately goes into the
1396 // holding cell as nodes[0] is AwaitingRAA.
1398 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1399 check_added_monitors!(nodes[0], 1);
1400 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1401 check_added_monitors!(nodes[0], 0);
1404 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1407 let mut node_0_per_peer_lock;
1408 let mut node_0_peer_state_lock;
1409 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1411 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1412 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1413 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1414 channel.get_short_channel_id().unwrap()
1417 assert_eq!(used_liquidity, Some(2000000));
1420 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1421 nodes[0].node.get_and_clear_pending_msg_events();
1425 fn intercepted_payment() {
1426 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1427 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1428 // payment or (b) fail the payment.
1429 do_test_intercepted_payment(InterceptTest::Forward);
1430 do_test_intercepted_payment(InterceptTest::Fail);
1431 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1432 do_test_intercepted_payment(InterceptTest::Timeout);
1435 fn do_test_intercepted_payment(test: InterceptTest) {
1436 let chanmon_cfgs = create_chanmon_cfgs(3);
1437 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1439 let mut zero_conf_chan_config = test_default_channel_config();
1440 zero_conf_chan_config.manually_accept_inbound_channels = true;
1441 let mut intercept_forwards_config = test_default_channel_config();
1442 intercept_forwards_config.accept_intercept_htlcs = true;
1443 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1445 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1446 let scorer = test_utils::TestScorer::new();
1447 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1449 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1451 let amt_msat = 100_000;
1452 let intercept_scid = nodes[1].node.get_intercept_scid();
1453 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1454 .with_route_hints(vec![
1455 RouteHint(vec![RouteHintHop {
1456 src_node_id: nodes[1].node.get_our_node_id(),
1457 short_channel_id: intercept_scid,
1460 proportional_millionths: 0,
1462 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1463 htlc_minimum_msat: None,
1464 htlc_maximum_msat: None,
1467 .with_features(nodes[2].node.invoice_features());
1468 let route_params = RouteParameters {
1470 final_value_msat: amt_msat,
1471 final_cltv_expiry_delta: TEST_FINAL_CLTV,
1473 let route = get_route(
1474 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1475 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1476 route_params.final_cltv_expiry_delta, nodes[0].logger, &scorer, &random_seed_bytes
1479 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1480 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1481 let payment_event = {
1483 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1484 assert_eq!(added_monitors.len(), 1);
1485 added_monitors.clear();
1487 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1488 assert_eq!(events.len(), 1);
1489 SendEvent::from_event(events.remove(0))
1491 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1492 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1494 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1495 let events = nodes[1].node.get_and_clear_pending_events();
1496 assert_eq!(events.len(), 1);
1497 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1498 crate::util::events::Event::HTLCIntercepted {
1499 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1501 assert_eq!(pmt_hash, payment_hash);
1502 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1503 assert_eq!(short_channel_id, intercept_scid);
1504 (intercept_id, expected_outbound_amount_msat)
1509 // Check for unknown channel id error.
1510 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();
1511 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()) });
1513 if test == InterceptTest::Fail {
1514 // Ensure we can fail the intercepted payment back.
1515 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1516 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1517 nodes[1].node.process_pending_htlc_forwards();
1518 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1519 check_added_monitors!(&nodes[1], 1);
1520 assert!(update_fail.update_fail_htlcs.len() == 1);
1521 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1522 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1523 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1525 // Ensure the payment fails with the expected error.
1526 let fail_conditions = PaymentFailedConditions::new()
1527 .blamed_scid(intercept_scid)
1528 .blamed_chan_closed(true)
1529 .expected_htlc_error_data(0x4000 | 10, &[]);
1530 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1531 } else if test == InterceptTest::Forward {
1532 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1533 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1534 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();
1535 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1536 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1538 // Open the just-in-time channel so the payment can then be forwarded.
1539 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1541 // Finally, forward the intercepted payment through and claim it.
1542 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1543 expect_pending_htlcs_forwardable!(nodes[1]);
1545 let payment_event = {
1547 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1548 assert_eq!(added_monitors.len(), 1);
1549 added_monitors.clear();
1551 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1552 assert_eq!(events.len(), 1);
1553 SendEvent::from_event(events.remove(0))
1555 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1556 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1557 expect_pending_htlcs_forwardable!(nodes[2]);
1559 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1560 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1561 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1562 let events = nodes[0].node.get_and_clear_pending_events();
1563 assert_eq!(events.len(), 2);
1565 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1566 assert_eq!(payment_preimage, *ev_preimage);
1567 assert_eq!(payment_hash, *ev_hash);
1568 assert_eq!(fee_paid_msat, &Some(1000));
1570 _ => panic!("Unexpected event")
1573 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1574 assert_eq!(hash, Some(payment_hash));
1576 _ => panic!("Unexpected event")
1578 } else if test == InterceptTest::Timeout {
1579 let mut block = Block {
1580 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1583 connect_block(&nodes[0], &block);
1584 connect_block(&nodes[1], &block);
1585 for _ in 0..TEST_FINAL_CLTV {
1586 block.header.prev_blockhash = block.block_hash();
1587 connect_block(&nodes[0], &block);
1588 connect_block(&nodes[1], &block);
1590 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1591 check_added_monitors!(nodes[1], 1);
1592 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1593 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1594 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1595 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1596 assert!(htlc_timeout_updates.update_fee.is_none());
1598 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1599 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1600 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1602 // Check for unknown intercept id error.
1603 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1604 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();
1605 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1606 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1607 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1611 #[derive(PartialEq)]
1622 fn automatic_retries() {
1623 do_automatic_retries(AutoRetry::Success);
1624 do_automatic_retries(AutoRetry::Spontaneous);
1625 do_automatic_retries(AutoRetry::FailAttempts);
1626 do_automatic_retries(AutoRetry::FailTimeout);
1627 do_automatic_retries(AutoRetry::FailOnRestart);
1628 do_automatic_retries(AutoRetry::FailOnRetry);
1630 fn do_automatic_retries(test: AutoRetry) {
1631 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1633 let chanmon_cfgs = create_chanmon_cfgs(3);
1634 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1635 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1638 let new_chain_monitor;
1639 let node_0_deserialized;
1641 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1642 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1643 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1645 // Marshall data to send the payment
1646 #[cfg(feature = "std")]
1647 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1648 #[cfg(not(feature = "std"))]
1649 let payment_expiry_secs = 60 * 60;
1650 let amt_msat = 1000;
1651 let mut invoice_features = InvoiceFeatures::empty();
1652 invoice_features.set_variable_length_onion_required();
1653 invoice_features.set_payment_secret_required();
1654 invoice_features.set_basic_mpp_optional();
1655 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1656 .with_expiry_time(payment_expiry_secs as u64)
1657 .with_features(invoice_features);
1658 let route_params = RouteParameters {
1660 final_value_msat: amt_msat,
1661 final_cltv_expiry_delta: TEST_FINAL_CLTV,
1663 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1665 macro_rules! pass_failed_attempt_with_retry_along_path {
1666 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1667 // Send a payment attempt that fails due to lack of liquidity on the second hop
1668 check_added_monitors!(nodes[0], 1);
1669 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1670 let mut update_add = update_0.update_add_htlcs[0].clone();
1671 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1672 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1673 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1674 nodes[1].node.process_pending_htlc_forwards();
1675 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1676 vec![HTLCDestination::NextHopChannel {
1677 node_id: Some(nodes[2].node.get_our_node_id()),
1678 channel_id: $failing_channel_id,
1680 nodes[1].node.process_pending_htlc_forwards();
1681 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1682 check_added_monitors!(&nodes[1], 1);
1683 assert!(update_1.update_fail_htlcs.len() == 1);
1684 let fail_msg = update_1.update_fail_htlcs[0].clone();
1686 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1687 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1689 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1690 let mut events = nodes[0].node.get_and_clear_pending_events();
1692 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1693 assert_eq!(payment_hash, ev_payment_hash);
1694 assert_eq!(payment_failed_permanently, false);
1696 _ => panic!("Unexpected event"),
1698 if $expect_pending_htlcs_forwardable {
1699 assert_eq!(events.len(), 2);
1701 Event::PendingHTLCsForwardable { .. } => {},
1702 _ => panic!("Unexpected event"),
1704 } else { assert_eq!(events.len(), 1) }
1708 if test == AutoRetry::Success {
1709 // Test that we can succeed on the first retry.
1710 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1711 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1713 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1714 // attempt, since the initial second hop channel will be excluded from pathfinding
1715 create_announced_chan_between_nodes(&nodes, 1, 2);
1717 // We retry payments in `process_pending_htlc_forwards`
1718 nodes[0].node.process_pending_htlc_forwards();
1719 check_added_monitors!(nodes[0], 1);
1720 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1721 assert_eq!(msg_events.len(), 1);
1722 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1723 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1724 } else if test == AutoRetry::Spontaneous {
1725 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1726 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1728 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1729 // attempt, since the initial second hop channel will be excluded from pathfinding
1730 create_announced_chan_between_nodes(&nodes, 1, 2);
1732 // We retry payments in `process_pending_htlc_forwards`
1733 nodes[0].node.process_pending_htlc_forwards();
1734 check_added_monitors!(nodes[0], 1);
1735 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1736 assert_eq!(msg_events.len(), 1);
1737 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1738 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1739 } else if test == AutoRetry::FailAttempts {
1740 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1741 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1742 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1744 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1745 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1746 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1748 // We retry payments in `process_pending_htlc_forwards`
1749 nodes[0].node.process_pending_htlc_forwards();
1750 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1752 // Ensure we won't retry a second time.
1753 nodes[0].node.process_pending_htlc_forwards();
1754 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1755 assert_eq!(msg_events.len(), 0);
1757 nodes[0].node.abandon_payment(PaymentId(payment_hash.0));
1758 let events = nodes[0].node.get_and_clear_pending_events();
1759 assert_eq!(events.len(), 1);
1761 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1762 assert_eq!(payment_hash, *ev_payment_hash);
1763 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1765 _ => panic!("Unexpected event"),
1767 } else if test == AutoRetry::FailTimeout {
1768 #[cfg(not(feature = "no-std"))] {
1769 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1770 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();
1771 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1773 // Advance the time so the second attempt fails due to timeout.
1774 SinceEpoch::advance(Duration::from_secs(61));
1776 // Make sure we don't retry again.
1777 nodes[0].node.process_pending_htlc_forwards();
1778 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1779 assert_eq!(msg_events.len(), 0);
1781 nodes[0].node.abandon_payment(PaymentId(payment_hash.0));
1782 let mut events = nodes[0].node.get_and_clear_pending_events();
1783 assert_eq!(events.len(), 1);
1785 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1786 assert_eq!(payment_hash, *ev_payment_hash);
1787 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1789 _ => panic!("Unexpected event"),
1792 } else if test == AutoRetry::FailOnRestart {
1793 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1794 // attempts remaining prior to restart.
1795 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1796 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1798 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1799 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1800 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1802 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1803 nodes[0].node.process_pending_htlc_forwards();
1804 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1806 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1807 let node_encoded = nodes[0].node.encode();
1808 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1809 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1811 // Make sure we don't retry again.
1812 nodes[0].node.process_pending_htlc_forwards();
1813 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1814 assert_eq!(msg_events.len(), 0);
1816 nodes[0].node.abandon_payment(PaymentId(payment_hash.0));
1817 let mut events = nodes[0].node.get_and_clear_pending_events();
1818 assert_eq!(events.len(), 1);
1820 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1821 assert_eq!(payment_hash, *ev_payment_hash);
1822 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1824 _ => panic!("Unexpected event"),
1826 } else if test == AutoRetry::FailOnRetry {
1827 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1828 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1830 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1831 // fail to find a route.
1832 nodes[0].node.process_pending_htlc_forwards();
1833 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1834 assert_eq!(msg_events.len(), 0);
1836 let mut events = nodes[0].node.get_and_clear_pending_events();
1837 assert_eq!(events.len(), 1);
1839 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1840 assert_eq!(payment_hash, *ev_payment_hash);
1841 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1843 _ => panic!("Unexpected event"),
1849 fn auto_retry_partial_failure() {
1850 // Test that we'll retry appropriately on send partial failure and retry partial failure.
1851 let chanmon_cfgs = create_chanmon_cfgs(2);
1852 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1853 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1854 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1856 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1857 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1858 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1860 // Marshall data to send the payment
1861 let amt_msat = 20_000;
1862 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1863 #[cfg(feature = "std")]
1864 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1865 #[cfg(not(feature = "std"))]
1866 let payment_expiry_secs = 60 * 60;
1867 let mut invoice_features = InvoiceFeatures::empty();
1868 invoice_features.set_variable_length_onion_required();
1869 invoice_features.set_payment_secret_required();
1870 invoice_features.set_basic_mpp_optional();
1871 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1872 .with_expiry_time(payment_expiry_secs as u64)
1873 .with_features(invoice_features);
1874 let route_params = RouteParameters {
1876 final_value_msat: amt_msat,
1877 final_cltv_expiry_delta: TEST_FINAL_CLTV,
1880 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1881 // second (for the initial send path2 over chan_2) fails.
1882 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1883 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1884 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1885 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1886 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1887 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1888 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1890 // Configure the initial send, retry1 and retry2's paths.
1891 let send_route = Route {
1894 pubkey: nodes[1].node.get_our_node_id(),
1895 node_features: nodes[1].node.node_features(),
1896 short_channel_id: chan_1_id,
1897 channel_features: nodes[1].node.channel_features(),
1898 fee_msat: amt_msat / 2,
1899 cltv_expiry_delta: 100,
1902 pubkey: nodes[1].node.get_our_node_id(),
1903 node_features: nodes[1].node.node_features(),
1904 short_channel_id: chan_2_id,
1905 channel_features: nodes[1].node.channel_features(),
1906 fee_msat: amt_msat / 2,
1907 cltv_expiry_delta: 100,
1910 payment_params: Some(route_params.payment_params.clone()),
1912 let retry_1_route = Route {
1915 pubkey: nodes[1].node.get_our_node_id(),
1916 node_features: nodes[1].node.node_features(),
1917 short_channel_id: chan_1_id,
1918 channel_features: nodes[1].node.channel_features(),
1919 fee_msat: amt_msat / 4,
1920 cltv_expiry_delta: 100,
1923 pubkey: nodes[1].node.get_our_node_id(),
1924 node_features: nodes[1].node.node_features(),
1925 short_channel_id: chan_3_id,
1926 channel_features: nodes[1].node.channel_features(),
1927 fee_msat: amt_msat / 4,
1928 cltv_expiry_delta: 100,
1931 payment_params: Some(route_params.payment_params.clone()),
1933 let retry_2_route = Route {
1936 pubkey: nodes[1].node.get_our_node_id(),
1937 node_features: nodes[1].node.node_features(),
1938 short_channel_id: chan_1_id,
1939 channel_features: nodes[1].node.channel_features(),
1940 fee_msat: amt_msat / 4,
1941 cltv_expiry_delta: 100,
1944 payment_params: Some(route_params.payment_params.clone()),
1946 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1947 nodes[0].router.expect_find_route(RouteParameters {
1948 payment_params: route_params.payment_params.clone(),
1949 final_value_msat: amt_msat / 2, final_cltv_expiry_delta: TEST_FINAL_CLTV
1950 }, Ok(retry_1_route));
1951 nodes[0].router.expect_find_route(RouteParameters {
1952 payment_params: route_params.payment_params.clone(),
1953 final_value_msat: amt_msat / 4, final_cltv_expiry_delta: TEST_FINAL_CLTV
1954 }, Ok(retry_2_route));
1956 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1957 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1958 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1959 assert_eq!(closed_chan_events.len(), 2);
1960 match closed_chan_events[0] {
1961 Event::ChannelClosed { .. } => {},
1962 _ => panic!("Unexpected event"),
1964 match closed_chan_events[1] {
1965 Event::ChannelClosed { .. } => {},
1966 _ => panic!("Unexpected event"),
1969 // Pass the first part of the payment along the path.
1970 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1971 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1973 // First message is the first update_add, remaining messages are broadcasting channel updates and
1974 // errors for the permfailed channels
1975 assert_eq!(msg_events.len(), 5);
1976 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1978 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1979 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1980 check_added_monitors!(nodes[1], 1);
1981 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1983 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1984 check_added_monitors!(nodes[0], 1);
1985 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1987 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1988 check_added_monitors!(nodes[0], 1);
1989 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1991 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1992 check_added_monitors!(nodes[1], 1);
1994 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1995 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1996 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1997 check_added_monitors!(nodes[1], 1);
1998 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2000 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2001 check_added_monitors!(nodes[0], 1);
2003 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
2004 check_added_monitors!(nodes[0], 1);
2005 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2007 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2008 check_added_monitors!(nodes[1], 1);
2010 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
2011 nodes[1].node.process_pending_htlc_forwards();
2012 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
2013 nodes[1].node.claim_funds(payment_preimage);
2014 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
2015 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2016 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
2018 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
2019 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
2020 check_added_monitors!(nodes[0], 1);
2021 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2023 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2024 check_added_monitors!(nodes[1], 4);
2025 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2027 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2028 check_added_monitors!(nodes[1], 1);
2029 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2031 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2032 check_added_monitors!(nodes[0], 1);
2034 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2035 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2036 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2037 check_added_monitors!(nodes[0], 1);
2038 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2040 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2041 check_added_monitors!(nodes[1], 1);
2043 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2044 check_added_monitors!(nodes[1], 1);
2045 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2047 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2048 check_added_monitors!(nodes[0], 1);
2049 expect_payment_sent!(nodes[0], payment_preimage);
2053 fn auto_retry_zero_attempts_send_error() {
2054 let chanmon_cfgs = create_chanmon_cfgs(2);
2055 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2056 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2057 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2059 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2060 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2062 // Marshall data to send the payment
2063 let amt_msat = 20_000;
2064 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2065 #[cfg(feature = "std")]
2066 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2067 #[cfg(not(feature = "std"))]
2068 let payment_expiry_secs = 60 * 60;
2069 let mut invoice_features = InvoiceFeatures::empty();
2070 invoice_features.set_variable_length_onion_required();
2071 invoice_features.set_payment_secret_required();
2072 invoice_features.set_basic_mpp_optional();
2073 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2074 .with_expiry_time(payment_expiry_secs as u64)
2075 .with_features(invoice_features);
2076 let route_params = RouteParameters {
2078 final_value_msat: amt_msat,
2079 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2082 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2083 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();
2084 if let PaymentSendFailure::AllFailedResendSafe(_) = err {
2085 } else { panic!("Unexpected error"); }
2086 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2087 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 1); // channel close event
2088 check_added_monitors!(nodes[0], 2);
2092 fn fails_paying_after_rejected_by_payee() {
2093 let chanmon_cfgs = create_chanmon_cfgs(2);
2094 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2095 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2096 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2098 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2100 // Marshall data to send the payment
2101 let amt_msat = 20_000;
2102 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2103 #[cfg(feature = "std")]
2104 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2105 #[cfg(not(feature = "std"))]
2106 let payment_expiry_secs = 60 * 60;
2107 let mut invoice_features = InvoiceFeatures::empty();
2108 invoice_features.set_variable_length_onion_required();
2109 invoice_features.set_payment_secret_required();
2110 invoice_features.set_basic_mpp_optional();
2111 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2112 .with_expiry_time(payment_expiry_secs as u64)
2113 .with_features(invoice_features);
2114 let route_params = RouteParameters {
2116 final_value_msat: amt_msat,
2117 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2120 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2121 check_added_monitors!(nodes[0], 1);
2122 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2123 assert_eq!(events.len(), 1);
2124 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2125 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2126 check_added_monitors!(nodes[1], 0);
2127 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2128 expect_pending_htlcs_forwardable!(nodes[1]);
2129 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2131 nodes[1].node.fail_htlc_backwards(&payment_hash);
2132 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2133 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash);
2137 fn retry_multi_path_single_failed_payment() {
2138 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2139 let chanmon_cfgs = create_chanmon_cfgs(2);
2140 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2141 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2142 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2144 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2145 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2147 let amt_msat = 100_010_000;
2149 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2150 #[cfg(feature = "std")]
2151 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2152 #[cfg(not(feature = "std"))]
2153 let payment_expiry_secs = 60 * 60;
2154 let mut invoice_features = InvoiceFeatures::empty();
2155 invoice_features.set_variable_length_onion_required();
2156 invoice_features.set_payment_secret_required();
2157 invoice_features.set_basic_mpp_optional();
2158 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2159 .with_expiry_time(payment_expiry_secs as u64)
2160 .with_features(invoice_features);
2161 let route_params = RouteParameters {
2162 payment_params: payment_params.clone(),
2163 final_value_msat: amt_msat,
2164 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2167 let chans = nodes[0].node.list_usable_channels();
2168 let mut route = Route {
2171 pubkey: nodes[1].node.get_our_node_id(),
2172 node_features: nodes[1].node.node_features(),
2173 short_channel_id: chans[0].short_channel_id.unwrap(),
2174 channel_features: nodes[1].node.channel_features(),
2176 cltv_expiry_delta: 100,
2179 pubkey: nodes[1].node.get_our_node_id(),
2180 node_features: nodes[1].node.node_features(),
2181 short_channel_id: chans[1].short_channel_id.unwrap(),
2182 channel_features: nodes[1].node.channel_features(),
2183 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2184 cltv_expiry_delta: 100,
2187 payment_params: Some(payment_params),
2189 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2190 // On retry, split the payment across both channels.
2191 route.paths[0][0].fee_msat = 50_000_001;
2192 route.paths[1][0].fee_msat = 50_000_000;
2193 nodes[0].router.expect_find_route(RouteParameters {
2194 payment_params: route.payment_params.clone().unwrap(),
2195 // Note that the second request here requests the amount we originally failed to send,
2196 // not the amount remaining on the full payment, which should be changed.
2197 final_value_msat: 100_000_001, final_cltv_expiry_delta: TEST_FINAL_CLTV
2198 }, Ok(route.clone()));
2201 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2202 // The initial send attempt, 2 paths
2203 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2204 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2205 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2206 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2207 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2210 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2211 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2212 assert_eq!(htlc_msgs.len(), 2);
2213 check_added_monitors!(nodes[0], 2);
2217 fn immediate_retry_on_failure() {
2218 // Tests that we can/will retry immediately after a failure
2219 let chanmon_cfgs = create_chanmon_cfgs(2);
2220 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2221 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2222 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2224 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2225 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2227 let amt_msat = 100_000_001;
2228 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2229 #[cfg(feature = "std")]
2230 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2231 #[cfg(not(feature = "std"))]
2232 let payment_expiry_secs = 60 * 60;
2233 let mut invoice_features = InvoiceFeatures::empty();
2234 invoice_features.set_variable_length_onion_required();
2235 invoice_features.set_payment_secret_required();
2236 invoice_features.set_basic_mpp_optional();
2237 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2238 .with_expiry_time(payment_expiry_secs as u64)
2239 .with_features(invoice_features);
2240 let route_params = RouteParameters {
2242 final_value_msat: amt_msat,
2243 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2246 let chans = nodes[0].node.list_usable_channels();
2247 let mut route = Route {
2250 pubkey: nodes[1].node.get_our_node_id(),
2251 node_features: nodes[1].node.node_features(),
2252 short_channel_id: chans[0].short_channel_id.unwrap(),
2253 channel_features: nodes[1].node.channel_features(),
2254 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2255 cltv_expiry_delta: 100,
2258 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2260 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2261 // On retry, split the payment across both channels.
2262 route.paths.push(route.paths[0].clone());
2263 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2264 route.paths[0][0].fee_msat = 50_000_000;
2265 route.paths[1][0].fee_msat = 50_000_001;
2266 nodes[0].router.expect_find_route(RouteParameters {
2267 payment_params: route_params.payment_params.clone(),
2268 final_value_msat: amt_msat, final_cltv_expiry_delta: TEST_FINAL_CLTV
2269 }, Ok(route.clone()));
2271 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2272 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2273 assert_eq!(htlc_msgs.len(), 2);
2274 check_added_monitors!(nodes[0], 2);
2278 fn no_extra_retries_on_back_to_back_fail() {
2279 // In a previous release, we had a race where we may exceed the payment retry count if we
2280 // get two failures in a row with the second having `all_paths_failed` set.
2281 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2282 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2283 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2284 // pending which we will see later. Thus, when we previously removed the retry tracking map
2285 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2286 // retry entry even though more events for the same payment were still pending. This led to
2287 // us retrying a payment again even though we'd already given up on it.
2289 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2290 // is used to remove the payment retry counter entries instead. This tests for the specific
2291 // excess-retry case while also testing `PaymentFailed` generation.
2293 let chanmon_cfgs = create_chanmon_cfgs(3);
2294 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2295 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2296 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2298 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2299 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2301 let amt_msat = 200_000_000;
2302 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2303 #[cfg(feature = "std")]
2304 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2305 #[cfg(not(feature = "std"))]
2306 let payment_expiry_secs = 60 * 60;
2307 let mut invoice_features = InvoiceFeatures::empty();
2308 invoice_features.set_variable_length_onion_required();
2309 invoice_features.set_payment_secret_required();
2310 invoice_features.set_basic_mpp_optional();
2311 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2312 .with_expiry_time(payment_expiry_secs as u64)
2313 .with_features(invoice_features);
2314 let route_params = RouteParameters {
2316 final_value_msat: amt_msat,
2317 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2320 let mut route = Route {
2323 pubkey: nodes[1].node.get_our_node_id(),
2324 node_features: nodes[1].node.node_features(),
2325 short_channel_id: chan_1_scid,
2326 channel_features: nodes[1].node.channel_features(),
2327 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2328 cltv_expiry_delta: 100,
2330 pubkey: nodes[2].node.get_our_node_id(),
2331 node_features: nodes[2].node.node_features(),
2332 short_channel_id: chan_2_scid,
2333 channel_features: nodes[2].node.channel_features(),
2334 fee_msat: 100_000_000,
2335 cltv_expiry_delta: 100,
2338 pubkey: nodes[1].node.get_our_node_id(),
2339 node_features: nodes[1].node.node_features(),
2340 short_channel_id: chan_1_scid,
2341 channel_features: nodes[1].node.channel_features(),
2342 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2343 cltv_expiry_delta: 100,
2345 pubkey: nodes[2].node.get_our_node_id(),
2346 node_features: nodes[2].node.node_features(),
2347 short_channel_id: chan_2_scid,
2348 channel_features: nodes[2].node.channel_features(),
2349 fee_msat: 100_000_000,
2350 cltv_expiry_delta: 100,
2353 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2355 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2356 let mut second_payment_params = route_params.payment_params.clone();
2357 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2358 // On retry, we'll only return one path
2359 route.paths.remove(1);
2360 route.paths[0][1].fee_msat = amt_msat;
2361 nodes[0].router.expect_find_route(RouteParameters {
2362 payment_params: second_payment_params,
2363 final_value_msat: amt_msat, final_cltv_expiry_delta: TEST_FINAL_CLTV,
2364 }, Ok(route.clone()));
2366 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2367 let htlc_updates = SendEvent::from_node(&nodes[0]);
2368 check_added_monitors!(nodes[0], 1);
2369 assert_eq!(htlc_updates.msgs.len(), 1);
2371 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2372 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2373 check_added_monitors!(nodes[1], 1);
2374 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2376 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2377 check_added_monitors!(nodes[0], 1);
2378 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2380 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2381 check_added_monitors!(nodes[0], 1);
2382 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2384 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2385 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2386 check_added_monitors!(nodes[1], 1);
2387 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2389 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2390 check_added_monitors!(nodes[1], 1);
2391 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2393 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2394 check_added_monitors!(nodes[0], 1);
2396 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2397 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2398 check_added_monitors!(nodes[0], 1);
2399 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2401 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2402 check_added_monitors!(nodes[1], 1);
2403 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2405 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2406 check_added_monitors!(nodes[1], 1);
2407 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2409 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2410 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2411 check_added_monitors!(nodes[0], 1);
2413 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2414 check_added_monitors!(nodes[0], 1);
2415 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2417 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2418 check_added_monitors!(nodes[1], 1);
2419 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2420 check_added_monitors!(nodes[1], 1);
2421 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2423 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2424 check_added_monitors!(nodes[0], 1);
2426 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2427 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2430 // Previously, we retried payments in an event consumer, which would retry each
2431 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2432 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2433 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2434 // by adding the `PaymentFailed` event.
2436 // Because we now retry payments as a batch, we simply return a single-path route in the
2437 // second, batched, request, have that fail, then complete the payment via `abandon_payment`.
2438 let mut events = nodes[0].node.get_and_clear_pending_events();
2439 assert_eq!(events.len(), 4);
2441 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2442 assert_eq!(payment_hash, ev_payment_hash);
2443 assert_eq!(payment_failed_permanently, false);
2445 _ => panic!("Unexpected event"),
2448 Event::PendingHTLCsForwardable { .. } => {},
2449 _ => panic!("Unexpected event"),
2452 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2453 assert_eq!(payment_hash, ev_payment_hash);
2454 assert_eq!(payment_failed_permanently, false);
2456 _ => panic!("Unexpected event"),
2459 Event::PendingHTLCsForwardable { .. } => {},
2460 _ => panic!("Unexpected event"),
2463 nodes[0].node.process_pending_htlc_forwards();
2464 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2465 check_added_monitors!(nodes[0], 1);
2467 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2468 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2469 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2470 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2471 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2473 let mut events = nodes[0].node.get_and_clear_pending_events();
2474 assert_eq!(events.len(), 1);
2476 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2477 assert_eq!(payment_hash, ev_payment_hash);
2478 assert_eq!(payment_failed_permanently, false);
2480 _ => panic!("Unexpected event"),
2482 nodes[0].node.abandon_payment(PaymentId(payment_hash.0));
2483 events = nodes[0].node.get_and_clear_pending_events();
2484 assert_eq!(events.len(), 1);
2486 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
2487 assert_eq!(payment_hash, *ev_payment_hash);
2488 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2490 _ => panic!("Unexpected event"),
2495 fn test_simple_partial_retry() {
2496 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2497 // full amount of the payment, rather than only the missing amount. Here we simply test for
2498 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2499 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2501 let chanmon_cfgs = create_chanmon_cfgs(3);
2502 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2503 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2504 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2506 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2507 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2509 let amt_msat = 200_000_000;
2510 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2511 #[cfg(feature = "std")]
2512 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2513 #[cfg(not(feature = "std"))]
2514 let payment_expiry_secs = 60 * 60;
2515 let mut invoice_features = InvoiceFeatures::empty();
2516 invoice_features.set_variable_length_onion_required();
2517 invoice_features.set_payment_secret_required();
2518 invoice_features.set_basic_mpp_optional();
2519 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2520 .with_expiry_time(payment_expiry_secs as u64)
2521 .with_features(invoice_features);
2522 let route_params = RouteParameters {
2524 final_value_msat: amt_msat,
2525 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2528 let mut route = Route {
2531 pubkey: nodes[1].node.get_our_node_id(),
2532 node_features: nodes[1].node.node_features(),
2533 short_channel_id: chan_1_scid,
2534 channel_features: nodes[1].node.channel_features(),
2535 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2536 cltv_expiry_delta: 100,
2538 pubkey: nodes[2].node.get_our_node_id(),
2539 node_features: nodes[2].node.node_features(),
2540 short_channel_id: chan_2_scid,
2541 channel_features: nodes[2].node.channel_features(),
2542 fee_msat: 100_000_000,
2543 cltv_expiry_delta: 100,
2546 pubkey: nodes[1].node.get_our_node_id(),
2547 node_features: nodes[1].node.node_features(),
2548 short_channel_id: chan_1_scid,
2549 channel_features: nodes[1].node.channel_features(),
2551 cltv_expiry_delta: 100,
2553 pubkey: nodes[2].node.get_our_node_id(),
2554 node_features: nodes[2].node.node_features(),
2555 short_channel_id: chan_2_scid,
2556 channel_features: nodes[2].node.channel_features(),
2557 fee_msat: 100_000_000,
2558 cltv_expiry_delta: 100,
2561 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2563 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2564 let mut second_payment_params = route_params.payment_params.clone();
2565 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2566 // On retry, we'll only be asked for one path (or 100k sats)
2567 route.paths.remove(0);
2568 nodes[0].router.expect_find_route(RouteParameters {
2569 payment_params: second_payment_params,
2570 final_value_msat: amt_msat / 2, final_cltv_expiry_delta: TEST_FINAL_CLTV,
2571 }, Ok(route.clone()));
2573 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2574 let htlc_updates = SendEvent::from_node(&nodes[0]);
2575 check_added_monitors!(nodes[0], 1);
2576 assert_eq!(htlc_updates.msgs.len(), 1);
2578 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2579 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2580 check_added_monitors!(nodes[1], 1);
2581 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2583 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2584 check_added_monitors!(nodes[0], 1);
2585 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2587 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2588 check_added_monitors!(nodes[0], 1);
2589 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2591 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2592 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2593 check_added_monitors!(nodes[1], 1);
2594 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2596 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2597 check_added_monitors!(nodes[1], 1);
2598 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2600 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2601 check_added_monitors!(nodes[0], 1);
2603 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2604 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2605 check_added_monitors!(nodes[0], 1);
2606 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2608 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2609 check_added_monitors!(nodes[1], 1);
2611 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2612 check_added_monitors!(nodes[1], 1);
2614 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2616 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2617 check_added_monitors!(nodes[0], 1);
2619 let mut events = nodes[0].node.get_and_clear_pending_events();
2620 assert_eq!(events.len(), 2);
2622 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2623 assert_eq!(payment_hash, ev_payment_hash);
2624 assert_eq!(payment_failed_permanently, false);
2626 _ => panic!("Unexpected event"),
2629 Event::PendingHTLCsForwardable { .. } => {},
2630 _ => panic!("Unexpected event"),
2633 nodes[0].node.process_pending_htlc_forwards();
2634 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2635 check_added_monitors!(nodes[0], 1);
2637 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2638 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2640 expect_pending_htlcs_forwardable!(nodes[1]);
2641 check_added_monitors!(nodes[1], 1);
2643 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2644 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2645 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2646 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2648 expect_pending_htlcs_forwardable!(nodes[2]);
2649 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);