1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test the payment retry logic in ChannelManager, including various edge-cases around
11 //! serialization ordering between ChannelManager/ChannelMonitors and ensuring we can still retry
12 //! payments thereafter.
14 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
15 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::chain::keysinterface::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
19 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails};
20 use crate::ln::features::InvoiceFeatures;
22 use crate::ln::msgs::ChannelMessageHandler;
23 use crate::ln::outbound_payment::Retry;
24 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
25 use crate::routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RouteParameters};
26 use crate::routing::scoring::ChannelUsage;
27 use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure};
28 use crate::util::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
31 use crate::util::string::UntrustedString;
33 use bitcoin::{Block, BlockHeader, TxMerkleNode};
34 use bitcoin::hashes::Hash;
35 use bitcoin::network::constants::Network;
37 use crate::prelude::*;
39 use crate::ln::functional_test_utils::*;
40 use crate::routing::gossip::NodeId;
41 #[cfg(feature = "std")]
43 crate::util::time::tests::SinceEpoch,
44 std::time::{SystemTime, Instant, Duration}
49 let chanmon_cfgs = create_chanmon_cfgs(4);
50 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
51 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
52 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
54 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
55 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
56 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
57 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
59 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
60 let path = route.paths[0].clone();
61 route.paths.push(path);
62 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
63 route.paths[0][0].short_channel_id = chan_1_id;
64 route.paths[0][1].short_channel_id = chan_3_id;
65 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
66 route.paths[1][0].short_channel_id = chan_2_id;
67 route.paths[1][1].short_channel_id = chan_4_id;
68 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
69 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
74 let chanmon_cfgs = create_chanmon_cfgs(4);
75 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
76 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
77 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
79 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
80 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
81 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
82 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
84 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
86 let amt_msat = 1_000_000;
87 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
88 let path = route.paths[0].clone();
89 route.paths.push(path);
90 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
91 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
92 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
93 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
94 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
95 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
97 // Initiate the MPP payment.
98 let payment_id = PaymentId(payment_hash.0);
99 let mut route_params = RouteParameters {
100 payment_params: route.payment_params.clone().unwrap(),
101 final_value_msat: amt_msat,
104 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
105 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
106 check_added_monitors!(nodes[0], 2); // one monitor per path
107 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
108 assert_eq!(events.len(), 2);
110 // Pass half of the payment along the success path.
111 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
112 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
114 // Add the HTLC along the first hop.
115 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
116 let (update_add, commitment_signed) = match fail_path_msgs_1 {
117 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
118 assert_eq!(update_add_htlcs.len(), 1);
119 assert!(update_fail_htlcs.is_empty());
120 assert!(update_fulfill_htlcs.is_empty());
121 assert!(update_fail_malformed_htlcs.is_empty());
122 assert!(update_fee.is_none());
123 (update_add_htlcs[0].clone(), commitment_signed.clone())
125 _ => panic!("Unexpected event"),
127 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
128 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
130 // Attempt to forward the payment and complete the 2nd path's failure.
131 expect_pending_htlcs_forwardable!(&nodes[2]);
132 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_4_id }]);
133 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
134 assert!(htlc_updates.update_add_htlcs.is_empty());
135 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
136 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
137 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
138 check_added_monitors!(nodes[2], 1);
139 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
140 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
141 let mut events = nodes[0].node.get_and_clear_pending_events();
143 Event::PendingHTLCsForwardable { .. } => {},
144 _ => panic!("Unexpected event")
147 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
149 // Rebalance the channel so the second half of the payment can succeed.
150 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
152 // Retry the second half of the payment and make sure it succeeds.
153 route.paths.remove(0);
154 route_params.final_value_msat = 1_000_000;
155 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
156 nodes[0].router.expect_find_route(route_params, Ok(route));
157 nodes[0].node.process_pending_htlc_forwards();
158 check_added_monitors!(nodes[0], 1);
159 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
160 assert_eq!(events.len(), 1);
161 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
162 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
165 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
166 let chanmon_cfgs = create_chanmon_cfgs(4);
167 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
168 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
169 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
171 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
172 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
173 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
174 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
176 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
177 let path = route.paths[0].clone();
178 route.paths.push(path);
179 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
180 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
181 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
182 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
183 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
184 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
186 // Initiate the MPP payment.
187 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
188 check_added_monitors!(nodes[0], 2); // one monitor per path
189 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
190 assert_eq!(events.len(), 2);
192 // Pass half of the payment along the first path.
193 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
194 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
196 if send_partial_mpp {
197 // Time out the partial MPP
198 for _ in 0..MPP_TIMEOUT_TICKS {
199 nodes[3].node.timer_tick_occurred();
202 // Failed HTLC from node 3 -> 1
203 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
204 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
205 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
206 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
207 check_added_monitors!(nodes[3], 1);
208 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
210 // Failed HTLC from node 1 -> 0
211 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_3_id }]);
212 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
213 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
214 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
215 check_added_monitors!(nodes[1], 1);
216 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
218 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
220 // Pass half of the payment along the second path.
221 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
222 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
224 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
225 for _ in 0..MPP_TIMEOUT_TICKS {
226 nodes[3].node.timer_tick_occurred();
229 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
234 fn mpp_receive_timeout() {
235 do_mpp_receive_timeout(true);
236 do_mpp_receive_timeout(false);
240 fn no_pending_leak_on_initial_send_failure() {
241 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
242 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
243 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
244 // pending payment forever and never time it out.
245 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
246 // try, and then check that no pending payment is being tracked.
247 let chanmon_cfgs = create_chanmon_cfgs(2);
248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
250 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
252 create_announced_chan_between_nodes(&nodes, 0, 1);
254 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
256 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
257 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
259 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)),
260 true, APIError::ChannelUnavailable { ref err },
261 assert_eq!(err, "Peer for first hop currently disconnected"));
263 assert!(!nodes[0].node.has_pending_payments());
266 fn do_retry_with_no_persist(confirm_before_reload: bool) {
267 // If we send a pending payment and `send_payment` returns success, we should always either
268 // return a payment failure event or a payment success event, and on failure the payment should
271 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
272 // always persisted asynchronously), the ChannelManager has to reload some payment data from
273 // ChannelMonitor(s) in some cases. This tests that reloading.
275 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
276 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
277 // which has separate codepaths for "commitment transaction already confirmed" and not.
278 let chanmon_cfgs = create_chanmon_cfgs(3);
279 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
280 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
281 let persister: test_utils::TestPersister;
282 let new_chain_monitor: test_utils::TestChainMonitor;
283 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>;
284 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
286 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
287 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
289 // Serialize the ChannelManager prior to sending payments
290 let nodes_0_serialized = nodes[0].node.encode();
292 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
294 let amt_msat = 1_000_000;
295 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
296 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
297 let route_params = RouteParameters {
298 payment_params: route.payment_params.clone().unwrap(),
299 final_value_msat: amt_msat,
301 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
302 check_added_monitors!(nodes[0], 1);
304 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
305 assert_eq!(events.len(), 1);
306 let payment_event = SendEvent::from_event(events.pop().unwrap());
307 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
309 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
310 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
311 // which would prevent retry.
312 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
313 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
315 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
316 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
317 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
318 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
320 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
322 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
323 if confirm_before_reload {
324 mine_transaction(&nodes[0], &as_commitment_tx);
325 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
328 // The ChannelMonitor should always be the latest version, as we're required to persist it
329 // during the `commitment_signed_dance!()`.
330 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
331 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
333 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
334 // force-close the channel.
335 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
336 assert!(nodes[0].node.list_channels().is_empty());
337 assert!(nodes[0].node.has_pending_payments());
338 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
339 assert_eq!(as_broadcasted_txn.len(), 1);
340 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
342 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
343 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
344 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
346 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
347 // error, as the channel has hit the chain.
348 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
349 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
350 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
351 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
352 assert_eq!(as_err.len(), 1);
354 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
355 assert_eq!(node_id, nodes[1].node.get_our_node_id());
356 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
357 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", &nodes[1].node.get_our_node_id())) });
358 check_added_monitors!(nodes[1], 1);
359 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
361 _ => panic!("Unexpected event"),
363 check_closed_broadcast!(nodes[1], false);
365 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
366 // we close in a moment.
367 nodes[2].node.claim_funds(payment_preimage_1);
368 check_added_monitors!(nodes[2], 1);
369 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
371 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
372 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
373 check_added_monitors!(nodes[1], 1);
374 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
375 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
377 if confirm_before_reload {
378 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
379 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
382 // Create a new channel on which to retry the payment before we fail the payment via the
383 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
384 // connecting several blocks while creating the channel (implying time has passed).
385 create_announced_chan_between_nodes(&nodes, 0, 1);
386 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
388 mine_transaction(&nodes[1], &as_commitment_tx);
389 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
390 assert_eq!(bs_htlc_claim_txn.len(), 1);
391 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
393 if !confirm_before_reload {
394 mine_transaction(&nodes[0], &as_commitment_tx);
396 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
397 expect_payment_sent!(nodes[0], payment_preimage_1);
398 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
399 let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
400 assert_eq!(as_htlc_timeout_txn.len(), 2);
401 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1]);
402 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
403 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
404 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
405 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
407 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
409 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
410 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
412 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
413 // reloaded) via a route over the new channel, which work without issue and eventually be
414 // received and claimed at the recipient just like any other payment.
415 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
417 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
418 // and not the original fee. We also update node[1]'s relevant config as
419 // do_claim_payment_along_route expects us to never overpay.
421 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
422 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
423 .unwrap().lock().unwrap();
424 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
425 let mut new_config = channel.config();
426 new_config.forwarding_fee_base_msat += 100_000;
427 channel.update_config(&new_config);
428 new_route.paths[0][0].fee_msat += 100_000;
431 // Force expiration of the channel's previous config.
432 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
433 nodes[1].node.timer_tick_occurred();
436 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
437 nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
438 check_added_monitors!(nodes[0], 1);
439 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
440 assert_eq!(events.len(), 1);
441 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
442 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
443 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
447 fn retry_with_no_persist() {
448 do_retry_with_no_persist(true);
449 do_retry_with_no_persist(false);
452 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
453 // Test that an off-chain completed payment is not retryable on restart. This was previously
454 // broken for dust payments, but we test for both dust and non-dust payments.
456 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
458 let chanmon_cfgs = create_chanmon_cfgs(3);
459 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
461 let mut manually_accept_config = test_default_channel_config();
462 manually_accept_config.manually_accept_inbound_channels = true;
464 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
466 let first_persister: test_utils::TestPersister;
467 let first_new_chain_monitor: test_utils::TestChainMonitor;
468 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>;
469 let second_persister: test_utils::TestPersister;
470 let second_new_chain_monitor: test_utils::TestChainMonitor;
471 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>;
472 let third_persister: test_utils::TestPersister;
473 let third_new_chain_monitor: test_utils::TestChainMonitor;
474 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>;
476 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
478 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
479 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
480 confirm_transaction(&nodes[0], &funding_tx);
481 confirm_transaction(&nodes[1], &funding_tx);
482 // Ignore the announcement_signatures messages
483 nodes[0].node.get_and_clear_pending_msg_events();
484 nodes[1].node.get_and_clear_pending_msg_events();
485 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
487 // Serialize the ChannelManager prior to sending payments
488 let mut nodes_0_serialized = nodes[0].node.encode();
490 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
491 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 });
493 // The ChannelMonitor should always be the latest version, as we're required to persist it
494 // during the `commitment_signed_dance!()`.
495 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
497 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);
498 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
500 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
501 // force-close the channel.
502 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
503 assert!(nodes[0].node.list_channels().is_empty());
504 assert!(nodes[0].node.has_pending_payments());
505 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
507 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
508 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
510 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
511 // error, as the channel has hit the chain.
512 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
513 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
514 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
515 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
516 assert_eq!(as_err.len(), 1);
517 let bs_commitment_tx;
519 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
520 assert_eq!(node_id, nodes[1].node.get_our_node_id());
521 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
522 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", &nodes[1].node.get_our_node_id())) });
523 check_added_monitors!(nodes[1], 1);
524 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
526 _ => panic!("Unexpected event"),
528 check_closed_broadcast!(nodes[1], false);
530 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
531 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
532 // incoming HTLCs with the same payment hash later.
533 nodes[2].node.fail_htlc_backwards(&payment_hash);
534 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
535 check_added_monitors!(nodes[2], 1);
537 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
538 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
539 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
540 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
541 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
543 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
544 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
545 // after the commitment transaction, so always connect the commitment transaction.
546 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
547 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
549 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
550 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
551 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
552 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
553 assert_eq!(as_htlc_timeout.len(), 1);
555 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
556 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
557 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
558 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
561 // Create a new channel on which to retry the payment before we fail the payment via the
562 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
563 // connecting several blocks while creating the channel (implying time has passed).
564 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
565 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
566 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
568 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
569 // confirming, we will fail as it's considered still-pending...
570 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
571 match nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id) {
572 Err(PaymentSendFailure::DuplicatePayment) => {},
573 _ => panic!("Unexpected error")
575 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
577 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
578 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
579 // (which should also still work).
580 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
581 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
582 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
584 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
585 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
586 nodes_0_serialized = nodes[0].node.encode();
588 // After the payment failed, we're free to send it again.
589 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id).is_ok());
590 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
592 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);
593 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
595 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
597 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
598 // the payment is not (spuriously) listed as still pending.
599 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id).is_ok());
600 check_added_monitors!(nodes[0], 1);
601 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
602 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
604 match nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id) {
605 Err(PaymentSendFailure::DuplicatePayment) => {},
606 _ => panic!("Unexpected error")
608 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
610 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
611 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
612 nodes_0_serialized = nodes[0].node.encode();
614 // Check that after reload we can send the payment again (though we shouldn't, since it was
615 // claimed previously).
616 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);
617 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
619 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
621 match nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id) {
622 Err(PaymentSendFailure::DuplicatePayment) => {},
623 _ => panic!("Unexpected error")
625 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
629 fn test_completed_payment_not_retryable_on_reload() {
630 do_test_completed_payment_not_retryable_on_reload(true);
631 do_test_completed_payment_not_retryable_on_reload(false);
635 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
636 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
637 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
638 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
639 // the ChannelMonitor tells it to.
641 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
642 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
643 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
644 let chanmon_cfgs = create_chanmon_cfgs(2);
645 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
646 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
647 let persister: test_utils::TestPersister;
648 let new_chain_monitor: test_utils::TestChainMonitor;
649 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>;
650 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
652 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
654 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
656 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
657 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
658 check_closed_broadcast!(nodes[0], true);
659 check_added_monitors!(nodes[0], 1);
660 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
662 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
663 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
665 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
666 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
667 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
668 assert_eq!(node_txn.len(), 3);
669 assert_eq!(node_txn[0], node_txn[1]);
670 check_spends!(node_txn[1], funding_tx);
671 check_spends!(node_txn[2], node_txn[1]);
672 let timeout_txn = vec![node_txn[2].clone()];
674 nodes[1].node.claim_funds(payment_preimage);
675 check_added_monitors!(nodes[1], 1);
676 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
678 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
679 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
680 check_closed_broadcast!(nodes[1], true);
681 check_added_monitors!(nodes[1], 1);
682 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
683 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
684 assert_eq!(claim_txn.len(), 1);
685 check_spends!(claim_txn[0], node_txn[1]);
687 header.prev_blockhash = nodes[0].best_block_hash();
688 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
690 if confirm_commitment_tx {
691 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
694 header.prev_blockhash = nodes[0].best_block_hash();
695 let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
698 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
699 connect_block(&nodes[0], &claim_block);
700 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
703 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
704 // returning InProgress. This should cause the claim event to never make its way to the
706 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
707 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
710 connect_blocks(&nodes[0], 1);
712 connect_block(&nodes[0], &claim_block);
715 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
716 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
717 .get_mut(&funding_txo).unwrap().drain().collect();
718 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
719 // If we're testing connection idempotency we may get substantially more.
720 assert!(mon_updates.len() >= 1);
721 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
722 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
724 // If we persist the ChannelManager here, we should get the PaymentSent event after
726 let mut chan_manager_serialized = Vec::new();
727 if !persist_manager_post_event {
728 chan_manager_serialized = nodes[0].node.encode();
731 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
732 // payment sent event.
733 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
734 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
735 for update in mon_updates {
736 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
739 expect_payment_failed!(nodes[0], payment_hash, false);
741 expect_payment_sent!(nodes[0], payment_preimage);
744 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
746 if persist_manager_post_event {
747 chan_manager_serialized = nodes[0].node.encode();
750 // Now reload nodes[0]...
751 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
753 if persist_manager_post_event {
754 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
755 } else if payment_timeout {
756 expect_payment_failed!(nodes[0], payment_hash, false);
758 expect_payment_sent!(nodes[0], payment_preimage);
761 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
762 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
763 // payment events should kick in, leaving us with no pending events here.
764 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
765 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
766 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
770 fn test_dup_htlc_onchain_fails_on_reload() {
771 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
772 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
773 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
774 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
775 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
776 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
780 fn test_fulfill_restart_failure() {
781 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
782 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
783 // again, or fail it, giving us free money.
785 // Of course probably they won't fail it and give us free money, but because we have code to
786 // handle it, we should test the logic for it anyway. We do that here.
787 let chanmon_cfgs = create_chanmon_cfgs(2);
788 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
789 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
790 let persister: test_utils::TestPersister;
791 let new_chain_monitor: test_utils::TestChainMonitor;
792 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>;
793 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
795 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
796 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
798 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
799 // pre-fulfill, which we do by serializing it here.
800 let chan_manager_serialized = nodes[1].node.encode();
801 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
803 nodes[1].node.claim_funds(payment_preimage);
804 check_added_monitors!(nodes[1], 1);
805 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
807 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
808 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
809 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
811 // Now reload nodes[1]...
812 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
814 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
815 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
817 nodes[1].node.fail_htlc_backwards(&payment_hash);
818 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
819 check_added_monitors!(nodes[1], 1);
820 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
821 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
822 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
823 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
824 // it had already considered the payment fulfilled, and now they just got free money.
825 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
829 fn get_ldk_payment_preimage() {
830 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
831 let chanmon_cfgs = create_chanmon_cfgs(2);
832 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
833 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
834 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
835 create_announced_chan_between_nodes(&nodes, 0, 1);
837 let amt_msat = 60_000;
838 let expiry_secs = 60 * 60;
839 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
841 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
842 .with_features(nodes[1].node.invoice_features());
843 let scorer = test_utils::TestScorer::new();
844 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
845 let random_seed_bytes = keys_manager.get_secure_random_bytes();
846 let route = get_route(
847 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
848 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
849 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
850 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
851 check_added_monitors!(nodes[0], 1);
853 // Make sure to use `get_payment_preimage`
854 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
855 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
856 assert_eq!(events.len(), 1);
857 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
858 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
862 fn sent_probe_is_probe_of_sending_node() {
863 let chanmon_cfgs = create_chanmon_cfgs(3);
864 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
865 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
866 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
868 create_announced_chan_between_nodes(&nodes, 0, 1);
869 create_announced_chan_between_nodes(&nodes, 1, 2);
871 // First check we refuse to build a single-hop probe
872 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
873 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
875 // Then build an actual two-hop probing path
876 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
878 match nodes[0].node.send_probe(route.paths[0].clone()) {
879 Ok((payment_hash, payment_id)) => {
880 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
881 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
882 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
887 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
888 check_added_monitors!(nodes[0], 1);
892 fn successful_probe_yields_event() {
893 let chanmon_cfgs = create_chanmon_cfgs(3);
894 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
895 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
896 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
898 create_announced_chan_between_nodes(&nodes, 0, 1);
899 create_announced_chan_between_nodes(&nodes, 1, 2);
901 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
903 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
905 // node[0] -- update_add_htlcs -> node[1]
906 check_added_monitors!(nodes[0], 1);
907 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
908 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
909 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
910 check_added_monitors!(nodes[1], 0);
911 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
912 expect_pending_htlcs_forwardable!(nodes[1]);
914 // node[1] -- update_add_htlcs -> node[2]
915 check_added_monitors!(nodes[1], 1);
916 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
917 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
918 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
919 check_added_monitors!(nodes[2], 0);
920 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
922 // node[1] <- update_fail_htlcs -- node[2]
923 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
924 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
925 check_added_monitors!(nodes[1], 0);
926 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
928 // node[0] <- update_fail_htlcs -- node[1]
929 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
930 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
931 check_added_monitors!(nodes[0], 0);
932 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
934 let mut events = nodes[0].node.get_and_clear_pending_events();
935 assert_eq!(events.len(), 1);
936 match events.drain(..).next().unwrap() {
937 crate::util::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
938 assert_eq!(payment_id, ev_pid);
939 assert_eq!(payment_hash, ev_ph);
943 assert!(!nodes[0].node.has_pending_payments());
947 fn failed_probe_yields_event() {
948 let chanmon_cfgs = create_chanmon_cfgs(3);
949 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
950 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
951 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
953 create_announced_chan_between_nodes(&nodes, 0, 1);
954 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
956 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
958 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
960 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
962 // node[0] -- update_add_htlcs -> node[1]
963 check_added_monitors!(nodes[0], 1);
964 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
965 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
966 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
967 check_added_monitors!(nodes[1], 0);
968 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
969 expect_pending_htlcs_forwardable!(nodes[1]);
971 // node[0] <- update_fail_htlcs -- node[1]
972 check_added_monitors!(nodes[1], 1);
973 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
974 // Skip the PendingHTLCsForwardable event
975 let _events = nodes[1].node.get_and_clear_pending_events();
976 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
977 check_added_monitors!(nodes[0], 0);
978 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
980 let mut events = nodes[0].node.get_and_clear_pending_events();
981 assert_eq!(events.len(), 1);
982 match events.drain(..).next().unwrap() {
983 crate::util::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
984 assert_eq!(payment_id, ev_pid);
985 assert_eq!(payment_hash, ev_ph);
989 assert!(!nodes[0].node.has_pending_payments());
993 fn onchain_failed_probe_yields_event() {
994 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
996 let chanmon_cfgs = create_chanmon_cfgs(3);
997 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
998 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
999 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1001 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1002 create_announced_chan_between_nodes(&nodes, 1, 2);
1004 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1006 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1007 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1008 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1010 // node[0] -- update_add_htlcs -> node[1]
1011 check_added_monitors!(nodes[0], 1);
1012 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1013 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1014 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1015 check_added_monitors!(nodes[1], 0);
1016 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1017 expect_pending_htlcs_forwardable!(nodes[1]);
1019 check_added_monitors!(nodes[1], 1);
1020 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1022 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1023 // Node A, which after 6 confirmations should result in a probe failure event.
1024 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1025 confirm_transaction(&nodes[0], &bs_txn[0]);
1026 check_closed_broadcast!(&nodes[0], true);
1027 check_added_monitors!(nodes[0], 1);
1029 let mut events = nodes[0].node.get_and_clear_pending_events();
1030 assert_eq!(events.len(), 2);
1031 let mut found_probe_failed = false;
1032 for event in events.drain(..) {
1034 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1035 assert_eq!(payment_id, ev_pid);
1036 assert_eq!(payment_hash, ev_ph);
1037 found_probe_failed = true;
1039 Event::ChannelClosed { .. } => {},
1043 assert!(found_probe_failed);
1044 assert!(!nodes[0].node.has_pending_payments());
1048 fn claimed_send_payment_idempotent() {
1049 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1050 let chanmon_cfgs = create_chanmon_cfgs(2);
1051 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1052 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1053 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1055 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1057 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1058 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1060 macro_rules! check_send_rejected {
1062 // If we try to resend a new payment with a different payment_hash but with the same
1063 // payment_id, it should be rejected.
1064 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1066 Err(PaymentSendFailure::DuplicatePayment) => {},
1067 _ => panic!("Unexpected send result: {:?}", send_result),
1070 // Further, if we try to send a spontaneous payment with the same payment_id it should
1071 // also be rejected.
1072 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1074 Err(PaymentSendFailure::DuplicatePayment) => {},
1075 _ => panic!("Unexpected send result: {:?}", send_result),
1080 check_send_rejected!();
1082 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1083 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1084 // we must remain just as idempotent as we were before.
1085 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1087 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1088 nodes[0].node.timer_tick_occurred();
1091 check_send_rejected!();
1093 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1094 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1095 // the payment complete. However, they could have called `send_payment` while the event was
1096 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1097 // after the event is handled a duplicate payment should sitll be rejected.
1098 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1099 check_send_rejected!();
1101 // If relatively little time has passed, a duplicate payment should still fail.
1102 nodes[0].node.timer_tick_occurred();
1103 check_send_rejected!();
1105 // However, after some time has passed (at least more than the one timer tick above), a
1106 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1107 // references to the old payment data.
1108 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1109 nodes[0].node.timer_tick_occurred();
1112 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1113 check_added_monitors!(nodes[0], 1);
1114 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1115 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1119 fn abandoned_send_payment_idempotent() {
1120 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1122 let chanmon_cfgs = create_chanmon_cfgs(2);
1123 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1124 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1125 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1127 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1129 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1130 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1132 macro_rules! check_send_rejected {
1134 // If we try to resend a new payment with a different payment_hash but with the same
1135 // payment_id, it should be rejected.
1136 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1138 Err(PaymentSendFailure::DuplicatePayment) => {},
1139 _ => panic!("Unexpected send result: {:?}", send_result),
1142 // Further, if we try to send a spontaneous payment with the same payment_id it should
1143 // also be rejected.
1144 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1146 Err(PaymentSendFailure::DuplicatePayment) => {},
1147 _ => panic!("Unexpected send result: {:?}", send_result),
1152 check_send_rejected!();
1154 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1155 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1157 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1159 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1160 nodes[0].node.timer_tick_occurred();
1162 check_send_rejected!();
1164 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash);
1166 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1167 // failed payment back.
1168 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1169 check_added_monitors!(nodes[0], 1);
1170 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1171 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1174 #[derive(PartialEq)]
1175 enum InterceptTest {
1182 fn test_trivial_inflight_htlc_tracking(){
1183 // In this test, we test three scenarios:
1184 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1185 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1186 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1187 let chanmon_cfgs = create_chanmon_cfgs(3);
1188 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1189 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1190 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1192 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1193 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1195 // Send and claim the payment. Inflight HTLCs should be empty.
1196 let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1197 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1199 let mut node_0_per_peer_lock;
1200 let mut node_0_peer_state_lock;
1201 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1203 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1204 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1205 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1206 channel_1.get_short_channel_id().unwrap()
1208 assert_eq!(chan_1_used_liquidity, None);
1211 let mut node_1_per_peer_lock;
1212 let mut node_1_peer_state_lock;
1213 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1215 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1216 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1217 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1218 channel_2.get_short_channel_id().unwrap()
1221 assert_eq!(chan_2_used_liquidity, None);
1223 let pending_payments = nodes[0].node.list_recent_payments();
1224 assert_eq!(pending_payments.len(), 1);
1225 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1227 // Remove fulfilled payment
1228 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1229 nodes[0].node.timer_tick_occurred();
1232 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1233 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1234 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1236 let mut node_0_per_peer_lock;
1237 let mut node_0_peer_state_lock;
1238 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1240 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1241 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1242 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1243 channel_1.get_short_channel_id().unwrap()
1245 // First hop accounts for expected 1000 msat fee
1246 assert_eq!(chan_1_used_liquidity, Some(501000));
1249 let mut node_1_per_peer_lock;
1250 let mut node_1_peer_state_lock;
1251 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1253 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1254 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1255 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1256 channel_2.get_short_channel_id().unwrap()
1259 assert_eq!(chan_2_used_liquidity, Some(500000));
1261 let pending_payments = nodes[0].node.list_recent_payments();
1262 assert_eq!(pending_payments.len(), 1);
1263 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1265 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1266 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1268 // Remove fulfilled payment
1269 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1270 nodes[0].node.timer_tick_occurred();
1273 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1275 let mut node_0_per_peer_lock;
1276 let mut node_0_peer_state_lock;
1277 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1279 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1280 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1281 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1282 channel_1.get_short_channel_id().unwrap()
1284 assert_eq!(chan_1_used_liquidity, None);
1287 let mut node_1_per_peer_lock;
1288 let mut node_1_peer_state_lock;
1289 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1291 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1292 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1293 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1294 channel_2.get_short_channel_id().unwrap()
1296 assert_eq!(chan_2_used_liquidity, None);
1299 let pending_payments = nodes[0].node.list_recent_payments();
1300 assert_eq!(pending_payments.len(), 0);
1304 fn test_holding_cell_inflight_htlcs() {
1305 let chanmon_cfgs = create_chanmon_cfgs(2);
1306 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1307 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1308 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1309 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1311 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1312 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1314 // Queue up two payments - one will be delivered right away, one immediately goes into the
1315 // holding cell as nodes[0] is AwaitingRAA.
1317 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1318 check_added_monitors!(nodes[0], 1);
1319 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1320 check_added_monitors!(nodes[0], 0);
1323 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1326 let mut node_0_per_peer_lock;
1327 let mut node_0_peer_state_lock;
1328 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1330 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1331 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1332 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1333 channel.get_short_channel_id().unwrap()
1336 assert_eq!(used_liquidity, Some(2000000));
1339 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1340 nodes[0].node.get_and_clear_pending_msg_events();
1344 fn intercepted_payment() {
1345 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1346 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1347 // payment or (b) fail the payment.
1348 do_test_intercepted_payment(InterceptTest::Forward);
1349 do_test_intercepted_payment(InterceptTest::Fail);
1350 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1351 do_test_intercepted_payment(InterceptTest::Timeout);
1354 fn do_test_intercepted_payment(test: InterceptTest) {
1355 let chanmon_cfgs = create_chanmon_cfgs(3);
1356 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1358 let mut zero_conf_chan_config = test_default_channel_config();
1359 zero_conf_chan_config.manually_accept_inbound_channels = true;
1360 let mut intercept_forwards_config = test_default_channel_config();
1361 intercept_forwards_config.accept_intercept_htlcs = true;
1362 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1364 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1365 let scorer = test_utils::TestScorer::new();
1366 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1368 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1370 let amt_msat = 100_000;
1371 let intercept_scid = nodes[1].node.get_intercept_scid();
1372 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1373 .with_route_hints(vec![
1374 RouteHint(vec![RouteHintHop {
1375 src_node_id: nodes[1].node.get_our_node_id(),
1376 short_channel_id: intercept_scid,
1379 proportional_millionths: 0,
1381 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1382 htlc_minimum_msat: None,
1383 htlc_maximum_msat: None,
1386 .with_features(nodes[2].node.invoice_features());
1387 let route_params = RouteParameters {
1389 final_value_msat: amt_msat,
1391 let route = get_route(
1392 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1393 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1394 route_params.payment_params.final_cltv_expiry_delta, nodes[0].logger, &scorer,
1398 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1399 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1400 let payment_event = {
1402 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1403 assert_eq!(added_monitors.len(), 1);
1404 added_monitors.clear();
1406 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1407 assert_eq!(events.len(), 1);
1408 SendEvent::from_event(events.remove(0))
1410 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1411 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1413 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1414 let events = nodes[1].node.get_and_clear_pending_events();
1415 assert_eq!(events.len(), 1);
1416 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1417 crate::util::events::Event::HTLCIntercepted {
1418 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1420 assert_eq!(pmt_hash, payment_hash);
1421 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1422 assert_eq!(short_channel_id, intercept_scid);
1423 (intercept_id, expected_outbound_amount_msat)
1428 // Check for unknown channel id error.
1429 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();
1430 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()) });
1432 if test == InterceptTest::Fail {
1433 // Ensure we can fail the intercepted payment back.
1434 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1435 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1436 nodes[1].node.process_pending_htlc_forwards();
1437 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1438 check_added_monitors!(&nodes[1], 1);
1439 assert!(update_fail.update_fail_htlcs.len() == 1);
1440 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1441 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1442 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1444 // Ensure the payment fails with the expected error.
1445 let fail_conditions = PaymentFailedConditions::new()
1446 .blamed_scid(intercept_scid)
1447 .blamed_chan_closed(true)
1448 .expected_htlc_error_data(0x4000 | 10, &[]);
1449 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1450 } else if test == InterceptTest::Forward {
1451 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1452 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1453 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();
1454 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1455 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1457 // Open the just-in-time channel so the payment can then be forwarded.
1458 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1460 // Finally, forward the intercepted payment through and claim it.
1461 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1462 expect_pending_htlcs_forwardable!(nodes[1]);
1464 let payment_event = {
1466 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1467 assert_eq!(added_monitors.len(), 1);
1468 added_monitors.clear();
1470 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1471 assert_eq!(events.len(), 1);
1472 SendEvent::from_event(events.remove(0))
1474 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1475 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1476 expect_pending_htlcs_forwardable!(nodes[2]);
1478 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1479 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1480 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1481 let events = nodes[0].node.get_and_clear_pending_events();
1482 assert_eq!(events.len(), 2);
1484 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1485 assert_eq!(payment_preimage, *ev_preimage);
1486 assert_eq!(payment_hash, *ev_hash);
1487 assert_eq!(fee_paid_msat, &Some(1000));
1489 _ => panic!("Unexpected event")
1492 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1493 assert_eq!(hash, Some(payment_hash));
1495 _ => panic!("Unexpected event")
1497 } else if test == InterceptTest::Timeout {
1498 let mut block = Block {
1499 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1502 connect_block(&nodes[0], &block);
1503 connect_block(&nodes[1], &block);
1504 for _ in 0..TEST_FINAL_CLTV {
1505 block.header.prev_blockhash = block.block_hash();
1506 connect_block(&nodes[0], &block);
1507 connect_block(&nodes[1], &block);
1509 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1510 check_added_monitors!(nodes[1], 1);
1511 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1512 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1513 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1514 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1515 assert!(htlc_timeout_updates.update_fee.is_none());
1517 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1518 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1519 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1521 // Check for unknown intercept id error.
1522 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1523 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();
1524 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1525 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1526 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1530 #[derive(PartialEq)]
1541 fn automatic_retries() {
1542 do_automatic_retries(AutoRetry::Success);
1543 do_automatic_retries(AutoRetry::Spontaneous);
1544 do_automatic_retries(AutoRetry::FailAttempts);
1545 do_automatic_retries(AutoRetry::FailTimeout);
1546 do_automatic_retries(AutoRetry::FailOnRestart);
1547 do_automatic_retries(AutoRetry::FailOnRetry);
1549 fn do_automatic_retries(test: AutoRetry) {
1550 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1552 let chanmon_cfgs = create_chanmon_cfgs(3);
1553 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1554 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1557 let new_chain_monitor;
1558 let node_0_deserialized;
1560 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1561 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1562 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1564 // Marshall data to send the payment
1565 #[cfg(feature = "std")]
1566 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1567 #[cfg(not(feature = "std"))]
1568 let payment_expiry_secs = 60 * 60;
1569 let amt_msat = 1000;
1570 let mut invoice_features = InvoiceFeatures::empty();
1571 invoice_features.set_variable_length_onion_required();
1572 invoice_features.set_payment_secret_required();
1573 invoice_features.set_basic_mpp_optional();
1574 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1575 .with_expiry_time(payment_expiry_secs as u64)
1576 .with_features(invoice_features);
1577 let route_params = RouteParameters {
1579 final_value_msat: amt_msat,
1581 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1583 macro_rules! pass_failed_attempt_with_retry_along_path {
1584 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1585 // Send a payment attempt that fails due to lack of liquidity on the second hop
1586 check_added_monitors!(nodes[0], 1);
1587 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1588 let mut update_add = update_0.update_add_htlcs[0].clone();
1589 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1590 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1591 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1592 nodes[1].node.process_pending_htlc_forwards();
1593 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1594 vec![HTLCDestination::NextHopChannel {
1595 node_id: Some(nodes[2].node.get_our_node_id()),
1596 channel_id: $failing_channel_id,
1598 nodes[1].node.process_pending_htlc_forwards();
1599 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1600 check_added_monitors!(&nodes[1], 1);
1601 assert!(update_1.update_fail_htlcs.len() == 1);
1602 let fail_msg = update_1.update_fail_htlcs[0].clone();
1603 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1604 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1606 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1607 let mut events = nodes[0].node.get_and_clear_pending_events();
1608 assert_eq!(events.len(), 2);
1610 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1611 assert_eq!(payment_hash, ev_payment_hash);
1612 assert_eq!(payment_failed_permanently, false);
1614 _ => panic!("Unexpected event"),
1616 if $expect_pending_htlcs_forwardable {
1618 Event::PendingHTLCsForwardable { .. } => {},
1619 _ => panic!("Unexpected event"),
1623 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1624 assert_eq!(payment_hash, ev_payment_hash);
1626 _ => panic!("Unexpected event"),
1632 if test == AutoRetry::Success {
1633 // Test that we can succeed on the first retry.
1634 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1635 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1637 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1638 // attempt, since the initial second hop channel will be excluded from pathfinding
1639 create_announced_chan_between_nodes(&nodes, 1, 2);
1641 // We retry payments in `process_pending_htlc_forwards`
1642 nodes[0].node.process_pending_htlc_forwards();
1643 check_added_monitors!(nodes[0], 1);
1644 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1645 assert_eq!(msg_events.len(), 1);
1646 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1647 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1648 } else if test == AutoRetry::Spontaneous {
1649 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1650 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1652 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1653 // attempt, since the initial second hop channel will be excluded from pathfinding
1654 create_announced_chan_between_nodes(&nodes, 1, 2);
1656 // We retry payments in `process_pending_htlc_forwards`
1657 nodes[0].node.process_pending_htlc_forwards();
1658 check_added_monitors!(nodes[0], 1);
1659 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1660 assert_eq!(msg_events.len(), 1);
1661 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1662 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1663 } else if test == AutoRetry::FailAttempts {
1664 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1665 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1666 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1668 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1669 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1670 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1672 // We retry payments in `process_pending_htlc_forwards`
1673 nodes[0].node.process_pending_htlc_forwards();
1674 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1676 // Ensure we won't retry a second time.
1677 nodes[0].node.process_pending_htlc_forwards();
1678 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1679 assert_eq!(msg_events.len(), 0);
1680 } else if test == AutoRetry::FailTimeout {
1681 #[cfg(not(feature = "no-std"))] {
1682 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1683 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();
1684 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1686 // Advance the time so the second attempt fails due to timeout.
1687 SinceEpoch::advance(Duration::from_secs(61));
1689 // Make sure we don't retry again.
1690 nodes[0].node.process_pending_htlc_forwards();
1691 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1692 assert_eq!(msg_events.len(), 0);
1694 let mut events = nodes[0].node.get_and_clear_pending_events();
1695 assert_eq!(events.len(), 1);
1697 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1698 assert_eq!(payment_hash, *ev_payment_hash);
1699 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1701 _ => panic!("Unexpected event"),
1704 } else if test == AutoRetry::FailOnRestart {
1705 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1706 // attempts remaining prior to restart.
1707 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1708 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1710 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1711 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1712 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1714 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1715 nodes[0].node.process_pending_htlc_forwards();
1716 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1718 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1719 let node_encoded = nodes[0].node.encode();
1720 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1721 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1723 let mut events = nodes[0].node.get_and_clear_pending_events();
1724 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
1725 // Make sure we don't retry again.
1726 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1727 assert_eq!(msg_events.len(), 0);
1729 let mut events = nodes[0].node.get_and_clear_pending_events();
1730 assert_eq!(events.len(), 1);
1732 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1733 assert_eq!(payment_hash, *ev_payment_hash);
1734 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1736 _ => panic!("Unexpected event"),
1738 } else if test == AutoRetry::FailOnRetry {
1739 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1740 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1742 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1743 // fail to find a route.
1744 nodes[0].node.process_pending_htlc_forwards();
1745 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1746 assert_eq!(msg_events.len(), 0);
1748 let mut events = nodes[0].node.get_and_clear_pending_events();
1749 assert_eq!(events.len(), 1);
1751 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1752 assert_eq!(payment_hash, *ev_payment_hash);
1753 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1755 _ => panic!("Unexpected event"),
1761 fn auto_retry_partial_failure() {
1762 // Test that we'll retry appropriately on send partial failure and retry partial failure.
1763 let chanmon_cfgs = create_chanmon_cfgs(2);
1764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1766 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1768 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1769 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1770 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1772 // Marshall data to send the payment
1773 let amt_msat = 20_000;
1774 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1775 #[cfg(feature = "std")]
1776 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1777 #[cfg(not(feature = "std"))]
1778 let payment_expiry_secs = 60 * 60;
1779 let mut invoice_features = InvoiceFeatures::empty();
1780 invoice_features.set_variable_length_onion_required();
1781 invoice_features.set_payment_secret_required();
1782 invoice_features.set_basic_mpp_optional();
1783 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1784 .with_expiry_time(payment_expiry_secs as u64)
1785 .with_features(invoice_features);
1786 let route_params = RouteParameters {
1788 final_value_msat: amt_msat,
1791 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1792 // second (for the initial send path2 over chan_2) fails.
1793 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1794 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1795 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1796 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1797 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1798 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1799 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1801 // Configure the initial send, retry1 and retry2's paths.
1802 let send_route = Route {
1805 pubkey: nodes[1].node.get_our_node_id(),
1806 node_features: nodes[1].node.node_features(),
1807 short_channel_id: chan_1_id,
1808 channel_features: nodes[1].node.channel_features(),
1809 fee_msat: amt_msat / 2,
1810 cltv_expiry_delta: 100,
1813 pubkey: nodes[1].node.get_our_node_id(),
1814 node_features: nodes[1].node.node_features(),
1815 short_channel_id: chan_2_id,
1816 channel_features: nodes[1].node.channel_features(),
1817 fee_msat: amt_msat / 2,
1818 cltv_expiry_delta: 100,
1821 payment_params: Some(route_params.payment_params.clone()),
1823 let retry_1_route = Route {
1826 pubkey: nodes[1].node.get_our_node_id(),
1827 node_features: nodes[1].node.node_features(),
1828 short_channel_id: chan_1_id,
1829 channel_features: nodes[1].node.channel_features(),
1830 fee_msat: amt_msat / 4,
1831 cltv_expiry_delta: 100,
1834 pubkey: nodes[1].node.get_our_node_id(),
1835 node_features: nodes[1].node.node_features(),
1836 short_channel_id: chan_3_id,
1837 channel_features: nodes[1].node.channel_features(),
1838 fee_msat: amt_msat / 4,
1839 cltv_expiry_delta: 100,
1842 payment_params: Some(route_params.payment_params.clone()),
1844 let retry_2_route = Route {
1847 pubkey: nodes[1].node.get_our_node_id(),
1848 node_features: nodes[1].node.node_features(),
1849 short_channel_id: chan_1_id,
1850 channel_features: nodes[1].node.channel_features(),
1851 fee_msat: amt_msat / 4,
1852 cltv_expiry_delta: 100,
1855 payment_params: Some(route_params.payment_params.clone()),
1857 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1858 let mut payment_params = route_params.payment_params.clone();
1859 payment_params.previously_failed_channels.push(chan_2_id);
1860 nodes[0].router.expect_find_route(RouteParameters {
1861 payment_params, final_value_msat: amt_msat / 2,
1862 }, Ok(retry_1_route));
1863 let mut payment_params = route_params.payment_params.clone();
1864 payment_params.previously_failed_channels.push(chan_3_id);
1865 nodes[0].router.expect_find_route(RouteParameters {
1866 payment_params, final_value_msat: amt_msat / 4,
1867 }, Ok(retry_2_route));
1869 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1870 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1871 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1872 assert_eq!(closed_chan_events.len(), 4);
1873 match closed_chan_events[0] {
1874 Event::ChannelClosed { .. } => {},
1875 _ => panic!("Unexpected event"),
1877 match closed_chan_events[1] {
1878 Event::PaymentPathFailed { .. } => {},
1879 _ => panic!("Unexpected event"),
1881 match closed_chan_events[2] {
1882 Event::ChannelClosed { .. } => {},
1883 _ => panic!("Unexpected event"),
1885 match closed_chan_events[3] {
1886 Event::PaymentPathFailed { .. } => {},
1887 _ => panic!("Unexpected event"),
1890 // Pass the first part of the payment along the path.
1891 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1892 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1894 // First message is the first update_add, remaining messages are broadcasting channel updates and
1895 // errors for the permfailed channels
1896 assert_eq!(msg_events.len(), 5);
1897 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1899 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1900 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1901 check_added_monitors!(nodes[1], 1);
1902 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1904 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1905 check_added_monitors!(nodes[0], 1);
1906 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1908 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1909 check_added_monitors!(nodes[0], 1);
1910 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1912 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1913 check_added_monitors!(nodes[1], 1);
1915 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1916 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1917 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1918 check_added_monitors!(nodes[1], 1);
1919 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1921 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1922 check_added_monitors!(nodes[0], 1);
1924 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
1925 check_added_monitors!(nodes[0], 1);
1926 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1928 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1929 check_added_monitors!(nodes[1], 1);
1931 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1932 nodes[1].node.process_pending_htlc_forwards();
1933 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
1934 nodes[1].node.claim_funds(payment_preimage);
1935 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
1936 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1937 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
1939 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
1940 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
1941 check_added_monitors!(nodes[0], 1);
1942 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1944 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1945 check_added_monitors!(nodes[1], 4);
1946 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1948 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1949 check_added_monitors!(nodes[1], 1);
1950 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1952 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1953 check_added_monitors!(nodes[0], 1);
1955 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
1956 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
1957 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
1958 check_added_monitors!(nodes[0], 1);
1959 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1961 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
1962 check_added_monitors!(nodes[1], 1);
1964 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1965 check_added_monitors!(nodes[1], 1);
1966 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1968 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1969 check_added_monitors!(nodes[0], 1);
1970 expect_payment_sent!(nodes[0], payment_preimage);
1974 fn auto_retry_zero_attempts_send_error() {
1975 let chanmon_cfgs = create_chanmon_cfgs(2);
1976 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1977 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1978 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1980 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1981 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1983 // Marshall data to send the payment
1984 let amt_msat = 20_000;
1985 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1986 #[cfg(feature = "std")]
1987 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1988 #[cfg(not(feature = "std"))]
1989 let payment_expiry_secs = 60 * 60;
1990 let mut invoice_features = InvoiceFeatures::empty();
1991 invoice_features.set_variable_length_onion_required();
1992 invoice_features.set_payment_secret_required();
1993 invoice_features.set_basic_mpp_optional();
1994 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1995 .with_expiry_time(payment_expiry_secs as u64)
1996 .with_features(invoice_features);
1997 let route_params = RouteParameters {
1999 final_value_msat: amt_msat,
2002 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2003 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2004 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2005 let events = nodes[0].node.get_and_clear_pending_events();
2006 assert_eq!(events.len(), 3);
2007 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2008 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2009 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2010 check_added_monitors!(nodes[0], 2);
2014 fn fails_paying_after_rejected_by_payee() {
2015 let chanmon_cfgs = create_chanmon_cfgs(2);
2016 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2017 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2018 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2020 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2022 // Marshall data to send the payment
2023 let amt_msat = 20_000;
2024 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2025 #[cfg(feature = "std")]
2026 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2027 #[cfg(not(feature = "std"))]
2028 let payment_expiry_secs = 60 * 60;
2029 let mut invoice_features = InvoiceFeatures::empty();
2030 invoice_features.set_variable_length_onion_required();
2031 invoice_features.set_payment_secret_required();
2032 invoice_features.set_basic_mpp_optional();
2033 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2034 .with_expiry_time(payment_expiry_secs as u64)
2035 .with_features(invoice_features);
2036 let route_params = RouteParameters {
2038 final_value_msat: amt_msat,
2041 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2042 check_added_monitors!(nodes[0], 1);
2043 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2044 assert_eq!(events.len(), 1);
2045 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2046 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2047 check_added_monitors!(nodes[1], 0);
2048 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2049 expect_pending_htlcs_forwardable!(nodes[1]);
2050 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2052 nodes[1].node.fail_htlc_backwards(&payment_hash);
2053 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2054 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash);
2058 fn retry_multi_path_single_failed_payment() {
2059 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2060 let chanmon_cfgs = create_chanmon_cfgs(2);
2061 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2062 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2063 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2065 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2066 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2068 let amt_msat = 100_010_000;
2070 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2071 #[cfg(feature = "std")]
2072 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2073 #[cfg(not(feature = "std"))]
2074 let payment_expiry_secs = 60 * 60;
2075 let mut invoice_features = InvoiceFeatures::empty();
2076 invoice_features.set_variable_length_onion_required();
2077 invoice_features.set_payment_secret_required();
2078 invoice_features.set_basic_mpp_optional();
2079 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2080 .with_expiry_time(payment_expiry_secs as u64)
2081 .with_features(invoice_features);
2082 let route_params = RouteParameters {
2083 payment_params: payment_params.clone(),
2084 final_value_msat: amt_msat,
2087 let chans = nodes[0].node.list_usable_channels();
2088 let mut route = Route {
2091 pubkey: nodes[1].node.get_our_node_id(),
2092 node_features: nodes[1].node.node_features(),
2093 short_channel_id: chans[0].short_channel_id.unwrap(),
2094 channel_features: nodes[1].node.channel_features(),
2096 cltv_expiry_delta: 100,
2099 pubkey: nodes[1].node.get_our_node_id(),
2100 node_features: nodes[1].node.node_features(),
2101 short_channel_id: chans[1].short_channel_id.unwrap(),
2102 channel_features: nodes[1].node.channel_features(),
2103 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2104 cltv_expiry_delta: 100,
2107 payment_params: Some(payment_params),
2109 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2110 // On retry, split the payment across both channels.
2111 route.paths[0][0].fee_msat = 50_000_001;
2112 route.paths[1][0].fee_msat = 50_000_000;
2113 let mut pay_params = route.payment_params.clone().unwrap();
2114 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2115 nodes[0].router.expect_find_route(RouteParameters {
2116 payment_params: pay_params,
2117 // Note that the second request here requests the amount we originally failed to send,
2118 // not the amount remaining on the full payment, which should be changed.
2119 final_value_msat: 100_000_001,
2120 }, Ok(route.clone()));
2123 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2124 // The initial send attempt, 2 paths
2125 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2126 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2127 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2128 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2129 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2132 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2133 let events = nodes[0].node.get_and_clear_pending_events();
2134 assert_eq!(events.len(), 1);
2136 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2137 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2138 short_channel_id: Some(expected_scid), .. } =>
2140 assert_eq!(payment_hash, ev_payment_hash);
2141 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2142 assert!(err_msg.contains("max HTLC"));
2144 _ => panic!("Unexpected event"),
2146 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2147 assert_eq!(htlc_msgs.len(), 2);
2148 check_added_monitors!(nodes[0], 2);
2152 fn immediate_retry_on_failure() {
2153 // Tests that we can/will retry immediately after a failure
2154 let chanmon_cfgs = create_chanmon_cfgs(2);
2155 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2156 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2157 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2159 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2160 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2162 let amt_msat = 100_000_001;
2163 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2164 #[cfg(feature = "std")]
2165 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2166 #[cfg(not(feature = "std"))]
2167 let payment_expiry_secs = 60 * 60;
2168 let mut invoice_features = InvoiceFeatures::empty();
2169 invoice_features.set_variable_length_onion_required();
2170 invoice_features.set_payment_secret_required();
2171 invoice_features.set_basic_mpp_optional();
2172 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2173 .with_expiry_time(payment_expiry_secs as u64)
2174 .with_features(invoice_features);
2175 let route_params = RouteParameters {
2177 final_value_msat: amt_msat,
2180 let chans = nodes[0].node.list_usable_channels();
2181 let mut route = Route {
2184 pubkey: nodes[1].node.get_our_node_id(),
2185 node_features: nodes[1].node.node_features(),
2186 short_channel_id: chans[0].short_channel_id.unwrap(),
2187 channel_features: nodes[1].node.channel_features(),
2188 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2189 cltv_expiry_delta: 100,
2192 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2194 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2195 // On retry, split the payment across both channels.
2196 route.paths.push(route.paths[0].clone());
2197 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2198 route.paths[0][0].fee_msat = 50_000_000;
2199 route.paths[1][0].fee_msat = 50_000_001;
2200 let mut pay_params = route_params.payment_params.clone();
2201 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2202 nodes[0].router.expect_find_route(RouteParameters {
2203 payment_params: pay_params, final_value_msat: amt_msat,
2204 }, Ok(route.clone()));
2206 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2207 let events = nodes[0].node.get_and_clear_pending_events();
2208 assert_eq!(events.len(), 1);
2210 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2211 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2212 short_channel_id: Some(expected_scid), .. } =>
2214 assert_eq!(payment_hash, ev_payment_hash);
2215 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2216 assert!(err_msg.contains("max HTLC"));
2218 _ => panic!("Unexpected event"),
2220 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2221 assert_eq!(htlc_msgs.len(), 2);
2222 check_added_monitors!(nodes[0], 2);
2226 fn no_extra_retries_on_back_to_back_fail() {
2227 // In a previous release, we had a race where we may exceed the payment retry count if we
2228 // get two failures in a row with the second indicating that all paths had failed (this field,
2229 // `all_paths_failed`, has since been removed).
2230 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2231 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2232 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2233 // pending which we will see later. Thus, when we previously removed the retry tracking map
2234 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2235 // retry entry even though more events for the same payment were still pending. This led to
2236 // us retrying a payment again even though we'd already given up on it.
2238 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2239 // is used to remove the payment retry counter entries instead. This tests for the specific
2240 // excess-retry case while also testing `PaymentFailed` generation.
2242 let chanmon_cfgs = create_chanmon_cfgs(3);
2243 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2244 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2245 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2247 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2248 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2250 let amt_msat = 200_000_000;
2251 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2252 #[cfg(feature = "std")]
2253 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2254 #[cfg(not(feature = "std"))]
2255 let payment_expiry_secs = 60 * 60;
2256 let mut invoice_features = InvoiceFeatures::empty();
2257 invoice_features.set_variable_length_onion_required();
2258 invoice_features.set_payment_secret_required();
2259 invoice_features.set_basic_mpp_optional();
2260 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2261 .with_expiry_time(payment_expiry_secs as u64)
2262 .with_features(invoice_features);
2263 let route_params = RouteParameters {
2265 final_value_msat: amt_msat,
2268 let mut route = Route {
2271 pubkey: nodes[1].node.get_our_node_id(),
2272 node_features: nodes[1].node.node_features(),
2273 short_channel_id: chan_1_scid,
2274 channel_features: nodes[1].node.channel_features(),
2275 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2276 cltv_expiry_delta: 100,
2278 pubkey: nodes[2].node.get_our_node_id(),
2279 node_features: nodes[2].node.node_features(),
2280 short_channel_id: chan_2_scid,
2281 channel_features: nodes[2].node.channel_features(),
2282 fee_msat: 100_000_000,
2283 cltv_expiry_delta: 100,
2286 pubkey: nodes[1].node.get_our_node_id(),
2287 node_features: nodes[1].node.node_features(),
2288 short_channel_id: chan_1_scid,
2289 channel_features: nodes[1].node.channel_features(),
2290 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2291 cltv_expiry_delta: 100,
2293 pubkey: nodes[2].node.get_our_node_id(),
2294 node_features: nodes[2].node.node_features(),
2295 short_channel_id: chan_2_scid,
2296 channel_features: nodes[2].node.channel_features(),
2297 fee_msat: 100_000_000,
2298 cltv_expiry_delta: 100,
2301 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2303 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2304 let mut second_payment_params = route_params.payment_params.clone();
2305 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2306 // On retry, we'll only return one path
2307 route.paths.remove(1);
2308 route.paths[0][1].fee_msat = amt_msat;
2309 nodes[0].router.expect_find_route(RouteParameters {
2310 payment_params: second_payment_params,
2311 final_value_msat: amt_msat,
2312 }, Ok(route.clone()));
2314 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2315 let htlc_updates = SendEvent::from_node(&nodes[0]);
2316 check_added_monitors!(nodes[0], 1);
2317 assert_eq!(htlc_updates.msgs.len(), 1);
2319 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2320 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2321 check_added_monitors!(nodes[1], 1);
2322 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2324 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2325 check_added_monitors!(nodes[0], 1);
2326 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2328 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2329 check_added_monitors!(nodes[0], 1);
2330 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2332 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2333 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2334 check_added_monitors!(nodes[1], 1);
2335 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2337 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2338 check_added_monitors!(nodes[1], 1);
2339 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2341 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2342 check_added_monitors!(nodes[0], 1);
2344 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2345 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2346 check_added_monitors!(nodes[0], 1);
2347 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2349 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2350 check_added_monitors!(nodes[1], 1);
2351 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2353 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2354 check_added_monitors!(nodes[1], 1);
2355 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2357 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2358 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2359 check_added_monitors!(nodes[0], 1);
2361 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2362 check_added_monitors!(nodes[0], 1);
2363 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2365 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2366 check_added_monitors!(nodes[1], 1);
2367 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2368 check_added_monitors!(nodes[1], 1);
2369 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2371 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2372 check_added_monitors!(nodes[0], 1);
2374 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2375 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2378 // Previously, we retried payments in an event consumer, which would retry each
2379 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2380 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2381 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2382 // by adding the `PaymentFailed` event.
2384 // Because we now retry payments as a batch, we simply return a single-path route in the
2385 // second, batched, request, have that fail, ensure the payment was abandoned.
2386 let mut events = nodes[0].node.get_and_clear_pending_events();
2387 assert_eq!(events.len(), 3);
2389 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2390 assert_eq!(payment_hash, ev_payment_hash);
2391 assert_eq!(payment_failed_permanently, false);
2393 _ => panic!("Unexpected event"),
2396 Event::PendingHTLCsForwardable { .. } => {},
2397 _ => panic!("Unexpected event"),
2400 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2401 assert_eq!(payment_hash, ev_payment_hash);
2402 assert_eq!(payment_failed_permanently, false);
2404 _ => panic!("Unexpected event"),
2407 nodes[0].node.process_pending_htlc_forwards();
2408 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2409 check_added_monitors!(nodes[0], 1);
2411 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2412 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2413 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2414 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2415 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2417 let mut events = nodes[0].node.get_and_clear_pending_events();
2418 assert_eq!(events.len(), 2);
2420 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2421 assert_eq!(payment_hash, ev_payment_hash);
2422 assert_eq!(payment_failed_permanently, false);
2424 _ => panic!("Unexpected event"),
2427 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
2428 assert_eq!(payment_hash, *ev_payment_hash);
2429 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2431 _ => panic!("Unexpected event"),
2436 fn test_simple_partial_retry() {
2437 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2438 // full amount of the payment, rather than only the missing amount. Here we simply test for
2439 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2440 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2442 let chanmon_cfgs = create_chanmon_cfgs(3);
2443 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2444 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2445 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2447 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2448 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2450 let amt_msat = 200_000_000;
2451 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2452 #[cfg(feature = "std")]
2453 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2454 #[cfg(not(feature = "std"))]
2455 let payment_expiry_secs = 60 * 60;
2456 let mut invoice_features = InvoiceFeatures::empty();
2457 invoice_features.set_variable_length_onion_required();
2458 invoice_features.set_payment_secret_required();
2459 invoice_features.set_basic_mpp_optional();
2460 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2461 .with_expiry_time(payment_expiry_secs as u64)
2462 .with_features(invoice_features);
2463 let route_params = RouteParameters {
2465 final_value_msat: amt_msat,
2468 let mut route = Route {
2471 pubkey: nodes[1].node.get_our_node_id(),
2472 node_features: nodes[1].node.node_features(),
2473 short_channel_id: chan_1_scid,
2474 channel_features: nodes[1].node.channel_features(),
2475 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2476 cltv_expiry_delta: 100,
2478 pubkey: nodes[2].node.get_our_node_id(),
2479 node_features: nodes[2].node.node_features(),
2480 short_channel_id: chan_2_scid,
2481 channel_features: nodes[2].node.channel_features(),
2482 fee_msat: 100_000_000,
2483 cltv_expiry_delta: 100,
2486 pubkey: nodes[1].node.get_our_node_id(),
2487 node_features: nodes[1].node.node_features(),
2488 short_channel_id: chan_1_scid,
2489 channel_features: nodes[1].node.channel_features(),
2491 cltv_expiry_delta: 100,
2493 pubkey: nodes[2].node.get_our_node_id(),
2494 node_features: nodes[2].node.node_features(),
2495 short_channel_id: chan_2_scid,
2496 channel_features: nodes[2].node.channel_features(),
2497 fee_msat: 100_000_000,
2498 cltv_expiry_delta: 100,
2501 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2503 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2504 let mut second_payment_params = route_params.payment_params.clone();
2505 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2506 // On retry, we'll only be asked for one path (or 100k sats)
2507 route.paths.remove(0);
2508 nodes[0].router.expect_find_route(RouteParameters {
2509 payment_params: second_payment_params,
2510 final_value_msat: amt_msat / 2,
2511 }, Ok(route.clone()));
2513 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2514 let htlc_updates = SendEvent::from_node(&nodes[0]);
2515 check_added_monitors!(nodes[0], 1);
2516 assert_eq!(htlc_updates.msgs.len(), 1);
2518 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2519 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2520 check_added_monitors!(nodes[1], 1);
2521 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2523 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2524 check_added_monitors!(nodes[0], 1);
2525 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2527 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2528 check_added_monitors!(nodes[0], 1);
2529 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2531 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2532 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2533 check_added_monitors!(nodes[1], 1);
2534 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2536 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2537 check_added_monitors!(nodes[1], 1);
2538 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2540 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2541 check_added_monitors!(nodes[0], 1);
2543 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2544 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2545 check_added_monitors!(nodes[0], 1);
2546 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2548 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2549 check_added_monitors!(nodes[1], 1);
2551 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2552 check_added_monitors!(nodes[1], 1);
2554 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2556 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2557 check_added_monitors!(nodes[0], 1);
2559 let mut events = nodes[0].node.get_and_clear_pending_events();
2560 assert_eq!(events.len(), 2);
2562 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2563 assert_eq!(payment_hash, ev_payment_hash);
2564 assert_eq!(payment_failed_permanently, false);
2566 _ => panic!("Unexpected event"),
2569 Event::PendingHTLCsForwardable { .. } => {},
2570 _ => panic!("Unexpected event"),
2573 nodes[0].node.process_pending_htlc_forwards();
2574 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2575 check_added_monitors!(nodes[0], 1);
2577 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2578 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2580 expect_pending_htlcs_forwardable!(nodes[1]);
2581 check_added_monitors!(nodes[1], 1);
2583 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2584 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2585 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2586 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2588 expect_pending_htlcs_forwardable!(nodes[2]);
2589 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2593 #[cfg(feature = "std")]
2594 fn test_threaded_payment_retries() {
2595 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2596 // a single thread and would happily let multiple threads run retries at the same time. Because
2597 // retries are done by first calculating the amount we need to retry, then dropping the
2598 // relevant lock, then actually sending, we would happily let multiple threads retry the same
2599 // amount at the same time, overpaying our original HTLC!
2600 let chanmon_cfgs = create_chanmon_cfgs(4);
2601 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2602 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2603 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2605 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2606 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2607 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2608 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2610 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2611 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2612 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2613 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2615 let amt_msat = 100_000_000;
2616 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2617 #[cfg(feature = "std")]
2618 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2619 #[cfg(not(feature = "std"))]
2620 let payment_expiry_secs = 60 * 60;
2621 let mut invoice_features = InvoiceFeatures::empty();
2622 invoice_features.set_variable_length_onion_required();
2623 invoice_features.set_payment_secret_required();
2624 invoice_features.set_basic_mpp_optional();
2625 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2626 .with_expiry_time(payment_expiry_secs as u64)
2627 .with_features(invoice_features);
2628 let mut route_params = RouteParameters {
2630 final_value_msat: amt_msat,
2633 let mut route = Route {
2636 pubkey: nodes[1].node.get_our_node_id(),
2637 node_features: nodes[1].node.node_features(),
2638 short_channel_id: chan_1_scid,
2639 channel_features: nodes[1].node.channel_features(),
2641 cltv_expiry_delta: 100,
2643 pubkey: nodes[3].node.get_our_node_id(),
2644 node_features: nodes[2].node.node_features(),
2645 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2646 channel_features: nodes[2].node.channel_features(),
2647 fee_msat: amt_msat / 1000,
2648 cltv_expiry_delta: 100,
2651 pubkey: nodes[2].node.get_our_node_id(),
2652 node_features: nodes[2].node.node_features(),
2653 short_channel_id: chan_3_scid,
2654 channel_features: nodes[2].node.channel_features(),
2656 cltv_expiry_delta: 100,
2658 pubkey: nodes[3].node.get_our_node_id(),
2659 node_features: nodes[3].node.node_features(),
2660 short_channel_id: chan_4_scid,
2661 channel_features: nodes[3].node.channel_features(),
2662 fee_msat: amt_msat - amt_msat / 1000,
2663 cltv_expiry_delta: 100,
2666 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2668 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2670 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
2671 check_added_monitors!(nodes[0], 2);
2672 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2673 assert_eq!(send_msg_events.len(), 2);
2674 send_msg_events.retain(|msg|
2675 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
2676 // Drop the commitment update for nodes[2], we can just let that one sit pending
2678 *node_id == nodes[1].node.get_our_node_id()
2679 } else { panic!(); }
2682 // from here on out, the retry `RouteParameters` amount will be amt/1000
2683 route_params.final_value_msat /= 1000;
2686 let end_time = Instant::now() + Duration::from_secs(1);
2687 macro_rules! thread_body { () => { {
2688 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
2689 let node_ref = NodePtr::from_node(&nodes[0]);
2691 let node_a = unsafe { &*node_ref.0 };
2692 while Instant::now() < end_time {
2693 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2694 // Ignore if we have any pending events, just always pretend we just got a
2695 // PendingHTLCsForwardable
2696 node_a.node.process_pending_htlc_forwards();
2700 let mut threads = Vec::new();
2701 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
2703 // Back in the main thread, poll pending messages and make sure that we never have more than
2704 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
2705 // there are HTLC messages shoved in while its running. This allows us to test that we never
2706 // generate an additional update_add_htlc until we've fully failed the first.
2707 let mut previously_failed_channels = Vec::new();
2709 assert_eq!(send_msg_events.len(), 1);
2710 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
2711 assert_eq!(send_event.msgs.len(), 1);
2713 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
2714 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
2716 // Note that we only push one route into `expect_find_route` at a time, because that's all
2717 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
2718 // we should still ultimately fail for the same reason - because we're trying to send too
2719 // many HTLCs at once.
2720 let mut new_route_params = route_params.clone();
2721 previously_failed_channels.push(route.paths[0][1].short_channel_id);
2722 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
2723 route.paths[0][1].short_channel_id += 1;
2724 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
2726 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2727 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
2728 // The "normal" commitment_signed_dance delivers the final RAA and then calls
2729 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
2730 // This races with our other threads which may generate an add-HTLCs commitment update via
2731 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
2732 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
2733 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
2734 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
2736 let cur_time = Instant::now();
2737 if cur_time > end_time {
2738 for thread in threads.drain(..) { thread.join().unwrap(); }
2741 // Make sure we have some events to handle when we go around...
2742 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2743 nodes[0].node.process_pending_htlc_forwards();
2744 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2745 check_added_monitors!(nodes[0], 2);
2747 if cur_time > end_time {
2753 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
2754 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
2755 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
2756 // it was last persisted.
2757 let chanmon_cfgs = create_chanmon_cfgs(2);
2758 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2759 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2760 let (persister_a, persister_b, persister_c);
2761 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
2762 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
2763 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2765 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2767 let mut nodes_0_serialized = Vec::new();
2768 if !persist_manager_with_payment {
2769 nodes_0_serialized = nodes[0].node.encode();
2772 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2774 if persist_manager_with_payment {
2775 nodes_0_serialized = nodes[0].node.encode();
2778 nodes[1].node.claim_funds(our_payment_preimage);
2779 check_added_monitors!(nodes[1], 1);
2780 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
2782 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2783 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2784 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
2785 check_added_monitors!(nodes[0], 1);
2787 // The ChannelMonitor should always be the latest version, as we're required to persist it
2788 // during the commitment signed handling.
2789 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2790 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
2792 let events = nodes[0].node.get_and_clear_pending_events();
2793 assert_eq!(events.len(), 2);
2794 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
2795 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
2796 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
2797 // the double-claim that would otherwise appear at the end of this test.
2798 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2799 assert_eq!(as_broadcasted_txn.len(), 1);
2801 // Ensure that, even after some time, if we restart we still include *something* in the current
2802 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
2803 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
2804 // A naive implementation of the fix here would wipe the pending payments set, causing a
2805 // failure event when we restart.
2806 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2808 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2809 reload_node!(nodes[0], test_default_channel_config(), &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister_b, chain_monitor_b, nodes_0_deserialized_b);
2810 let events = nodes[0].node.get_and_clear_pending_events();
2811 assert!(events.is_empty());
2813 // Ensure that we don't generate any further events even after the channel-closing commitment
2814 // transaction is confirmed on-chain.
2815 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
2816 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2818 let events = nodes[0].node.get_and_clear_pending_events();
2819 assert!(events.is_empty());
2821 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2822 reload_node!(nodes[0], test_default_channel_config(), &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister_c, chain_monitor_c, nodes_0_deserialized_c);
2823 let events = nodes[0].node.get_and_clear_pending_events();
2824 assert!(events.is_empty());
2828 fn no_missing_sent_on_midpoint_reload() {
2829 do_no_missing_sent_on_midpoint_reload(false);
2830 do_no_missing_sent_on_midpoint_reload(true);