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, HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::sign::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason};
19 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
20 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails, RecipientOnionFields};
21 use crate::ln::features::InvoiceFeatures;
23 use crate::ln::msgs::ChannelMessageHandler;
24 use crate::ln::outbound_payment::Retry;
25 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
26 use crate::routing::router::{get_route, Path, PaymentParameters, Route, Router, RouteHint, RouteHintHop, RouteHop, RouteParameters};
27 use crate::routing::scoring::ChannelUsage;
28 use crate::util::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
31 use crate::util::string::UntrustedString;
33 use bitcoin::network::constants::Network;
35 use crate::prelude::*;
37 use crate::ln::functional_test_utils::*;
38 use crate::routing::gossip::NodeId;
39 #[cfg(feature = "std")]
41 crate::util::time::tests::SinceEpoch,
42 std::time::{SystemTime, Instant, Duration}
47 let chanmon_cfgs = create_chanmon_cfgs(4);
48 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
49 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
50 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
52 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
53 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
54 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
55 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
57 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
58 let path = route.paths[0].clone();
59 route.paths.push(path);
60 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
61 route.paths[0].hops[0].short_channel_id = chan_1_id;
62 route.paths[0].hops[1].short_channel_id = chan_3_id;
63 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
64 route.paths[1].hops[0].short_channel_id = chan_2_id;
65 route.paths[1].hops[1].short_channel_id = chan_4_id;
66 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
67 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
72 let chanmon_cfgs = create_chanmon_cfgs(4);
73 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
74 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
75 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
77 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
78 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
79 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
80 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
82 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
84 let amt_msat = 1_000_000;
85 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
86 let path = route.paths[0].clone();
87 route.paths.push(path);
88 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
89 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
90 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
91 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
92 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
93 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
95 // Initiate the MPP payment.
96 let payment_id = PaymentId(payment_hash.0);
97 let mut route_params = RouteParameters {
98 payment_params: route.payment_params.clone().unwrap(),
99 final_value_msat: amt_msat,
102 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
103 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
104 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
105 check_added_monitors!(nodes[0], 2); // one monitor per path
106 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
107 assert_eq!(events.len(), 2);
109 // Pass half of the payment along the success path.
110 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
111 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
113 // Add the HTLC along the first hop.
114 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
115 let (update_add, commitment_signed) = match fail_path_msgs_1 {
116 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 } } => {
117 assert_eq!(update_add_htlcs.len(), 1);
118 assert!(update_fail_htlcs.is_empty());
119 assert!(update_fulfill_htlcs.is_empty());
120 assert!(update_fail_malformed_htlcs.is_empty());
121 assert!(update_fee.is_none());
122 (update_add_htlcs[0].clone(), commitment_signed.clone())
124 _ => panic!("Unexpected event"),
126 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
127 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
129 // Attempt to forward the payment and complete the 2nd path's failure.
130 expect_pending_htlcs_forwardable!(&nodes[2]);
131 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 }]);
132 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
133 assert!(htlc_updates.update_add_htlcs.is_empty());
134 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
135 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
136 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
137 check_added_monitors!(nodes[2], 1);
138 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
139 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
140 let mut events = nodes[0].node.get_and_clear_pending_events();
142 Event::PendingHTLCsForwardable { .. } => {},
143 _ => panic!("Unexpected event")
146 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
148 // Rebalance the channel so the second half of the payment can succeed.
149 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
151 // Retry the second half of the payment and make sure it succeeds.
152 route.paths.remove(0);
153 route_params.final_value_msat = 1_000_000;
154 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
155 nodes[0].router.expect_find_route(route_params, Ok(route));
156 nodes[0].node.process_pending_htlc_forwards();
157 check_added_monitors!(nodes[0], 1);
158 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
159 assert_eq!(events.len(), 1);
160 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
161 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
164 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
165 let chanmon_cfgs = create_chanmon_cfgs(4);
166 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
167 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
168 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
170 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
171 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
172 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
173 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
175 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
176 let path = route.paths[0].clone();
177 route.paths.push(path);
178 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
179 route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
180 route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
181 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
182 route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
183 route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
185 // Initiate the MPP payment.
186 nodes[0].node.send_payment_with_route(&route, payment_hash,
187 RecipientOnionFields::secret_only(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_with_route(&route, payment_hash,
260 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
261 ), true, APIError::ChannelUnavailable { ref err },
262 assert_eq!(err, "Peer for first hop currently disconnected"));
264 assert!(!nodes[0].node.has_pending_payments());
267 fn do_retry_with_no_persist(confirm_before_reload: bool) {
268 // If we send a pending payment and `send_payment` returns success, we should always either
269 // return a payment failure event or a payment success event, and on failure the payment should
272 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
273 // always persisted asynchronously), the ChannelManager has to reload some payment data from
274 // ChannelMonitor(s) in some cases. This tests that reloading.
276 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
277 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
278 // which has separate codepaths for "commitment transaction already confirmed" and not.
279 let chanmon_cfgs = create_chanmon_cfgs(3);
280 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
281 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
282 let persister: test_utils::TestPersister;
283 let new_chain_monitor: test_utils::TestChainMonitor;
284 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>;
285 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
287 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
288 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
290 // Serialize the ChannelManager prior to sending payments
291 let nodes_0_serialized = nodes[0].node.encode();
293 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
295 let amt_msat = 1_000_000;
296 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
297 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
298 let route_params = RouteParameters {
299 payment_params: route.payment_params.clone().unwrap(),
300 final_value_msat: amt_msat,
302 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
303 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
304 check_added_monitors!(nodes[0], 1);
306 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
307 assert_eq!(events.len(), 1);
308 let payment_event = SendEvent::from_event(events.pop().unwrap());
309 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
311 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
312 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
313 // which would prevent retry.
314 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
315 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
317 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
318 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
319 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
320 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
322 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
324 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
325 if confirm_before_reload {
326 mine_transaction(&nodes[0], &as_commitment_tx);
327 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
330 // The ChannelMonitor should always be the latest version, as we're required to persist it
331 // during the `commitment_signed_dance!()`.
332 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
333 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
335 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
336 // force-close the channel.
337 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
338 assert!(nodes[0].node.list_channels().is_empty());
339 assert!(nodes[0].node.has_pending_payments());
340 nodes[0].node.timer_tick_occurred();
341 if !confirm_before_reload {
342 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
343 assert_eq!(as_broadcasted_txn.len(), 1);
344 assert_eq!(as_broadcasted_txn[0].txid(), as_commitment_tx.txid());
346 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
348 check_added_monitors!(nodes[0], 1);
350 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
351 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
352 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
354 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
356 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
357 // error, as the channel has hit the chain.
358 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
359 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
361 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
362 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
363 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
364 assert_eq!(as_err.len(), 1);
366 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
367 assert_eq!(node_id, nodes[1].node.get_our_node_id());
368 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
369 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())) });
370 check_added_monitors!(nodes[1], 1);
371 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
373 _ => panic!("Unexpected event"),
375 check_closed_broadcast!(nodes[1], false);
377 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
378 // we close in a moment.
379 nodes[2].node.claim_funds(payment_preimage_1);
380 check_added_monitors!(nodes[2], 1);
381 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
383 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
384 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
385 check_added_monitors!(nodes[1], 1);
386 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
387 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
389 if confirm_before_reload {
390 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
391 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
394 // Create a new channel on which to retry the payment before we fail the payment via the
395 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
396 // connecting several blocks while creating the channel (implying time has passed).
397 create_announced_chan_between_nodes(&nodes, 0, 1);
398 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
400 mine_transaction(&nodes[1], &as_commitment_tx);
401 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
402 assert_eq!(bs_htlc_claim_txn.len(), 1);
403 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
405 if !confirm_before_reload {
406 mine_transaction(&nodes[0], &as_commitment_tx);
408 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
409 expect_payment_sent!(nodes[0], payment_preimage_1);
410 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
411 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
412 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
413 assert_eq!(txn.len(), 2);
414 (txn.remove(0), txn.remove(0))
416 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
417 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
418 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
419 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
421 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
423 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
424 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
426 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
427 // reloaded) via a route over the new channel, which work without issue and eventually be
428 // received and claimed at the recipient just like any other payment.
429 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
431 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
432 // and not the original fee. We also update node[1]'s relevant config as
433 // do_claim_payment_along_route expects us to never overpay.
435 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
436 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
437 .unwrap().lock().unwrap();
438 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
439 let mut new_config = channel.config();
440 new_config.forwarding_fee_base_msat += 100_000;
441 channel.update_config(&new_config);
442 new_route.paths[0].hops[0].fee_msat += 100_000;
445 // Force expiration of the channel's previous config.
446 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
447 nodes[1].node.timer_tick_occurred();
450 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
451 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
452 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
453 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
454 check_added_monitors!(nodes[0], 1);
455 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
456 assert_eq!(events.len(), 1);
457 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
458 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
459 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
463 fn retry_with_no_persist() {
464 do_retry_with_no_persist(true);
465 do_retry_with_no_persist(false);
468 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
469 // Test that an off-chain completed payment is not retryable on restart. This was previously
470 // broken for dust payments, but we test for both dust and non-dust payments.
472 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
474 let chanmon_cfgs = create_chanmon_cfgs(3);
475 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
477 let mut manually_accept_config = test_default_channel_config();
478 manually_accept_config.manually_accept_inbound_channels = true;
480 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
482 let first_persister: test_utils::TestPersister;
483 let first_new_chain_monitor: test_utils::TestChainMonitor;
484 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>;
485 let second_persister: test_utils::TestPersister;
486 let second_new_chain_monitor: test_utils::TestChainMonitor;
487 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>;
488 let third_persister: test_utils::TestPersister;
489 let third_new_chain_monitor: test_utils::TestChainMonitor;
490 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>;
492 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
494 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
495 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
496 confirm_transaction(&nodes[0], &funding_tx);
497 confirm_transaction(&nodes[1], &funding_tx);
498 // Ignore the announcement_signatures messages
499 nodes[0].node.get_and_clear_pending_msg_events();
500 nodes[1].node.get_and_clear_pending_msg_events();
501 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
503 // Serialize the ChannelManager prior to sending payments
504 let mut nodes_0_serialized = nodes[0].node.encode();
506 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
507 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 });
509 // The ChannelMonitor should always be the latest version, as we're required to persist it
510 // during the `commitment_signed_dance!()`.
511 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
513 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);
514 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
516 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
517 // force-close the channel.
518 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
519 nodes[0].node.timer_tick_occurred();
520 assert!(nodes[0].node.list_channels().is_empty());
521 assert!(nodes[0].node.has_pending_payments());
522 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
523 check_added_monitors!(nodes[0], 1);
525 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
526 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
528 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
530 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
531 // error, as the channel has hit the chain.
532 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
533 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
535 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
536 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
537 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
538 assert_eq!(as_err.len(), 1);
539 let bs_commitment_tx;
541 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
542 assert_eq!(node_id, nodes[1].node.get_our_node_id());
543 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
544 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())) });
545 check_added_monitors!(nodes[1], 1);
546 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
548 _ => panic!("Unexpected event"),
550 check_closed_broadcast!(nodes[1], false);
552 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
553 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
554 // incoming HTLCs with the same payment hash later.
555 nodes[2].node.fail_htlc_backwards(&payment_hash);
556 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
557 check_added_monitors!(nodes[2], 1);
559 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
560 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
561 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
562 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
563 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
565 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
566 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
567 // after the commitment transaction, so always connect the commitment transaction.
568 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
569 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
571 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
572 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
573 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
574 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
575 assert_eq!(as_htlc_timeout.len(), 1);
577 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
578 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
579 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
580 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
583 // Create a new channel on which to retry the payment before we fail the payment via the
584 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
585 // connecting several blocks while creating the channel (implying time has passed).
586 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
587 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
588 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
590 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
591 // confirming, we will fail as it's considered still-pending...
592 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
593 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
594 Err(PaymentSendFailure::DuplicatePayment) => {},
595 _ => panic!("Unexpected error")
597 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
599 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
600 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
601 // (which should also still work).
602 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
603 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
604 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
606 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
607 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
608 nodes_0_serialized = nodes[0].node.encode();
610 // After the payment failed, we're free to send it again.
611 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
612 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
613 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
615 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);
616 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
618 nodes[0].node.test_process_background_events();
619 check_added_monitors(&nodes[0], 1);
621 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
623 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
624 // the payment is not (spuriously) listed as still pending.
625 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
626 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
627 check_added_monitors!(nodes[0], 1);
628 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
629 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
631 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
632 Err(PaymentSendFailure::DuplicatePayment) => {},
633 _ => panic!("Unexpected error")
635 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
637 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
638 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
639 nodes_0_serialized = nodes[0].node.encode();
641 // Check that after reload we can send the payment again (though we shouldn't, since it was
642 // claimed previously).
643 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);
644 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
646 nodes[0].node.test_process_background_events();
647 check_added_monitors(&nodes[0], 1);
649 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
651 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
652 Err(PaymentSendFailure::DuplicatePayment) => {},
653 _ => panic!("Unexpected error")
655 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
659 fn test_completed_payment_not_retryable_on_reload() {
660 do_test_completed_payment_not_retryable_on_reload(true);
661 do_test_completed_payment_not_retryable_on_reload(false);
665 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
666 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
667 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
668 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
669 // the ChannelMonitor tells it to.
671 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
672 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
673 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
674 let chanmon_cfgs = create_chanmon_cfgs(2);
675 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
676 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
677 let persister: test_utils::TestPersister;
678 let new_chain_monitor: test_utils::TestChainMonitor;
679 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>;
680 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
682 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
684 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
686 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
687 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
688 check_closed_broadcast!(nodes[0], true);
689 check_added_monitors!(nodes[0], 1);
690 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
692 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
693 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
695 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
696 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
697 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
698 assert_eq!(node_txn.len(), 3);
699 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
700 check_spends!(node_txn[1], funding_tx);
701 check_spends!(node_txn[2], node_txn[1]);
702 let timeout_txn = vec![node_txn[2].clone()];
704 nodes[1].node.claim_funds(payment_preimage);
705 check_added_monitors!(nodes[1], 1);
706 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
708 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[1].clone()]));
709 check_closed_broadcast!(nodes[1], true);
710 check_added_monitors!(nodes[1], 1);
711 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
712 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
713 assert_eq!(claim_txn.len(), 1);
714 check_spends!(claim_txn[0], node_txn[1]);
716 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[1].clone()]));
718 if confirm_commitment_tx {
719 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
722 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] });
725 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
726 connect_block(&nodes[0], &claim_block);
727 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
730 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
731 // returning InProgress. This should cause the claim event to never make its way to the
733 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
734 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
737 connect_blocks(&nodes[0], 1);
739 connect_block(&nodes[0], &claim_block);
742 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
743 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
744 .get_mut(&funding_txo).unwrap().drain().collect();
745 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
746 // If we're testing connection idempotency we may get substantially more.
747 assert!(mon_updates.len() >= 1);
748 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
749 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
751 // If we persist the ChannelManager here, we should get the PaymentSent event after
753 let mut chan_manager_serialized = Vec::new();
754 if !persist_manager_post_event {
755 chan_manager_serialized = nodes[0].node.encode();
758 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
759 // payment sent event.
760 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
761 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
762 for update in mon_updates {
763 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
766 expect_payment_failed!(nodes[0], payment_hash, false);
768 expect_payment_sent!(nodes[0], payment_preimage);
771 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
773 if persist_manager_post_event {
774 chan_manager_serialized = nodes[0].node.encode();
777 // Now reload nodes[0]...
778 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
780 if persist_manager_post_event {
781 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
782 } else if payment_timeout {
783 expect_payment_failed!(nodes[0], payment_hash, false);
785 expect_payment_sent!(nodes[0], payment_preimage);
788 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
789 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
790 // payment events should kick in, leaving us with no pending events here.
791 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
792 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
793 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
794 check_added_monitors(&nodes[0], 1);
798 fn test_dup_htlc_onchain_fails_on_reload() {
799 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
800 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
801 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
802 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
803 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
804 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
808 fn test_fulfill_restart_failure() {
809 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
810 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
811 // again, or fail it, giving us free money.
813 // Of course probably they won't fail it and give us free money, but because we have code to
814 // handle it, we should test the logic for it anyway. We do that here.
815 let chanmon_cfgs = create_chanmon_cfgs(2);
816 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
817 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
818 let persister: test_utils::TestPersister;
819 let new_chain_monitor: test_utils::TestChainMonitor;
820 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>;
821 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
823 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
824 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
826 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
827 // pre-fulfill, which we do by serializing it here.
828 let chan_manager_serialized = nodes[1].node.encode();
829 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
831 nodes[1].node.claim_funds(payment_preimage);
832 check_added_monitors!(nodes[1], 1);
833 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
835 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
836 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
837 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
839 // Now reload nodes[1]...
840 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
842 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
843 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
845 nodes[1].node.fail_htlc_backwards(&payment_hash);
846 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
847 check_added_monitors!(nodes[1], 1);
848 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
849 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
850 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
851 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
852 // it had already considered the payment fulfilled, and now they just got free money.
853 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
857 fn get_ldk_payment_preimage() {
858 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
859 let chanmon_cfgs = create_chanmon_cfgs(2);
860 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
861 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
862 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
863 create_announced_chan_between_nodes(&nodes, 0, 1);
865 let amt_msat = 60_000;
866 let expiry_secs = 60 * 60;
867 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
869 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
870 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
871 let scorer = test_utils::TestScorer::new();
872 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
873 let random_seed_bytes = keys_manager.get_secure_random_bytes();
874 let route = get_route(
875 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
876 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
877 amt_msat, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
878 nodes[0].node.send_payment_with_route(&route, payment_hash,
879 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
880 check_added_monitors!(nodes[0], 1);
882 // Make sure to use `get_payment_preimage`
883 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
884 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
885 assert_eq!(events.len(), 1);
886 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
887 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
891 fn sent_probe_is_probe_of_sending_node() {
892 let chanmon_cfgs = create_chanmon_cfgs(3);
893 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
894 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
895 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
897 create_announced_chan_between_nodes(&nodes, 0, 1);
898 create_announced_chan_between_nodes(&nodes, 1, 2);
900 // First check we refuse to build a single-hop probe
901 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
902 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
904 // Then build an actual two-hop probing path
905 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
907 match nodes[0].node.send_probe(route.paths[0].clone()) {
908 Ok((payment_hash, payment_id)) => {
909 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
910 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
911 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
916 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
917 check_added_monitors!(nodes[0], 1);
921 fn successful_probe_yields_event() {
922 let chanmon_cfgs = create_chanmon_cfgs(3);
923 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
924 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
925 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
927 create_announced_chan_between_nodes(&nodes, 0, 1);
928 create_announced_chan_between_nodes(&nodes, 1, 2);
930 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
932 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
934 // node[0] -- update_add_htlcs -> node[1]
935 check_added_monitors!(nodes[0], 1);
936 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
937 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
938 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
939 check_added_monitors!(nodes[1], 0);
940 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
941 expect_pending_htlcs_forwardable!(nodes[1]);
943 // node[1] -- update_add_htlcs -> node[2]
944 check_added_monitors!(nodes[1], 1);
945 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
946 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
947 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
948 check_added_monitors!(nodes[2], 0);
949 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
951 // node[1] <- update_fail_htlcs -- node[2]
952 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
953 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
954 check_added_monitors!(nodes[1], 0);
955 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
957 // node[0] <- update_fail_htlcs -- node[1]
958 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
959 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
960 check_added_monitors!(nodes[0], 0);
961 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
963 let mut events = nodes[0].node.get_and_clear_pending_events();
964 assert_eq!(events.len(), 1);
965 match events.drain(..).next().unwrap() {
966 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
967 assert_eq!(payment_id, ev_pid);
968 assert_eq!(payment_hash, ev_ph);
972 assert!(!nodes[0].node.has_pending_payments());
976 fn failed_probe_yields_event() {
977 let chanmon_cfgs = create_chanmon_cfgs(3);
978 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
979 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
980 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
982 create_announced_chan_between_nodes(&nodes, 0, 1);
983 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
985 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
987 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000);
989 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
991 // node[0] -- update_add_htlcs -> node[1]
992 check_added_monitors!(nodes[0], 1);
993 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
994 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
995 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
996 check_added_monitors!(nodes[1], 0);
997 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
998 expect_pending_htlcs_forwardable!(nodes[1]);
1000 // node[0] <- update_fail_htlcs -- node[1]
1001 check_added_monitors!(nodes[1], 1);
1002 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1003 // Skip the PendingHTLCsForwardable event
1004 let _events = nodes[1].node.get_and_clear_pending_events();
1005 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1006 check_added_monitors!(nodes[0], 0);
1007 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1009 let mut events = nodes[0].node.get_and_clear_pending_events();
1010 assert_eq!(events.len(), 1);
1011 match events.drain(..).next().unwrap() {
1012 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1013 assert_eq!(payment_id, ev_pid);
1014 assert_eq!(payment_hash, ev_ph);
1018 assert!(!nodes[0].node.has_pending_payments());
1022 fn onchain_failed_probe_yields_event() {
1023 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1025 let chanmon_cfgs = create_chanmon_cfgs(3);
1026 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1027 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1028 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1030 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1031 create_announced_chan_between_nodes(&nodes, 1, 2);
1033 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1035 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1036 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000);
1037 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1039 // node[0] -- update_add_htlcs -> node[1]
1040 check_added_monitors!(nodes[0], 1);
1041 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1042 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1043 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1044 check_added_monitors!(nodes[1], 0);
1045 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1046 expect_pending_htlcs_forwardable!(nodes[1]);
1048 check_added_monitors!(nodes[1], 1);
1049 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1051 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1052 // Node A, which after 6 confirmations should result in a probe failure event.
1053 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1054 confirm_transaction(&nodes[0], &bs_txn[0]);
1055 check_closed_broadcast!(&nodes[0], true);
1056 check_added_monitors!(nodes[0], 1);
1058 let mut events = nodes[0].node.get_and_clear_pending_events();
1059 assert_eq!(events.len(), 2);
1060 let mut found_probe_failed = false;
1061 for event in events.drain(..) {
1063 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1064 assert_eq!(payment_id, ev_pid);
1065 assert_eq!(payment_hash, ev_ph);
1066 found_probe_failed = true;
1068 Event::ChannelClosed { .. } => {},
1072 assert!(found_probe_failed);
1073 assert!(!nodes[0].node.has_pending_payments());
1077 fn claimed_send_payment_idempotent() {
1078 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1079 let chanmon_cfgs = create_chanmon_cfgs(2);
1080 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1081 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1082 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1084 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1086 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1087 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1089 macro_rules! check_send_rejected {
1091 // If we try to resend a new payment with a different payment_hash but with the same
1092 // payment_id, it should be rejected.
1093 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1094 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1096 Err(PaymentSendFailure::DuplicatePayment) => {},
1097 _ => panic!("Unexpected send result: {:?}", send_result),
1100 // Further, if we try to send a spontaneous payment with the same payment_id it should
1101 // also be rejected.
1102 let send_result = nodes[0].node.send_spontaneous_payment(
1103 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1105 Err(PaymentSendFailure::DuplicatePayment) => {},
1106 _ => panic!("Unexpected send result: {:?}", send_result),
1111 check_send_rejected!();
1113 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1114 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1115 // we must remain just as idempotent as we were before.
1116 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1118 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1119 nodes[0].node.timer_tick_occurred();
1122 check_send_rejected!();
1124 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1125 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1126 // the payment complete. However, they could have called `send_payment` while the event was
1127 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1128 // after the event is handled a duplicate payment should sitll be rejected.
1129 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1130 check_send_rejected!();
1132 // If relatively little time has passed, a duplicate payment should still fail.
1133 nodes[0].node.timer_tick_occurred();
1134 check_send_rejected!();
1136 // However, after some time has passed (at least more than the one timer tick above), a
1137 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1138 // references to the old payment data.
1139 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1140 nodes[0].node.timer_tick_occurred();
1143 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1144 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1145 check_added_monitors!(nodes[0], 1);
1146 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1147 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1151 fn abandoned_send_payment_idempotent() {
1152 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1154 let chanmon_cfgs = create_chanmon_cfgs(2);
1155 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1156 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1157 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1159 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1161 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1162 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1164 macro_rules! check_send_rejected {
1166 // If we try to resend a new payment with a different payment_hash but with the same
1167 // payment_id, it should be rejected.
1168 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1169 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1171 Err(PaymentSendFailure::DuplicatePayment) => {},
1172 _ => panic!("Unexpected send result: {:?}", send_result),
1175 // Further, if we try to send a spontaneous payment with the same payment_id it should
1176 // also be rejected.
1177 let send_result = nodes[0].node.send_spontaneous_payment(
1178 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1180 Err(PaymentSendFailure::DuplicatePayment) => {},
1181 _ => panic!("Unexpected send result: {:?}", send_result),
1186 check_send_rejected!();
1188 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1189 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1191 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1193 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1194 nodes[0].node.timer_tick_occurred();
1196 check_send_rejected!();
1198 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1200 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1201 // failed payment back.
1202 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1203 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1204 check_added_monitors!(nodes[0], 1);
1205 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1206 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1209 #[derive(PartialEq)]
1210 enum InterceptTest {
1217 fn test_trivial_inflight_htlc_tracking(){
1218 // In this test, we test three scenarios:
1219 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1220 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1221 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1222 let chanmon_cfgs = create_chanmon_cfgs(3);
1223 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1224 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1225 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1227 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1228 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1230 // Send and claim the payment. Inflight HTLCs should be empty.
1231 let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1232 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1234 let mut node_0_per_peer_lock;
1235 let mut node_0_peer_state_lock;
1236 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1238 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1239 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1240 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1241 channel_1.get_short_channel_id().unwrap()
1243 assert_eq!(chan_1_used_liquidity, None);
1246 let mut node_1_per_peer_lock;
1247 let mut node_1_peer_state_lock;
1248 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1250 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1251 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1252 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1253 channel_2.get_short_channel_id().unwrap()
1256 assert_eq!(chan_2_used_liquidity, None);
1258 let pending_payments = nodes[0].node.list_recent_payments();
1259 assert_eq!(pending_payments.len(), 1);
1260 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1262 // Remove fulfilled payment
1263 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1264 nodes[0].node.timer_tick_occurred();
1267 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1268 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1269 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1271 let mut node_0_per_peer_lock;
1272 let mut node_0_peer_state_lock;
1273 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1275 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1276 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1277 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1278 channel_1.get_short_channel_id().unwrap()
1280 // First hop accounts for expected 1000 msat fee
1281 assert_eq!(chan_1_used_liquidity, Some(501000));
1284 let mut node_1_per_peer_lock;
1285 let mut node_1_peer_state_lock;
1286 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1288 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1289 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1290 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1291 channel_2.get_short_channel_id().unwrap()
1294 assert_eq!(chan_2_used_liquidity, Some(500000));
1296 let pending_payments = nodes[0].node.list_recent_payments();
1297 assert_eq!(pending_payments.len(), 1);
1298 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1300 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1301 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1303 // Remove fulfilled payment
1304 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1305 nodes[0].node.timer_tick_occurred();
1308 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1310 let mut node_0_per_peer_lock;
1311 let mut node_0_peer_state_lock;
1312 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1314 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1315 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1316 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1317 channel_1.get_short_channel_id().unwrap()
1319 assert_eq!(chan_1_used_liquidity, None);
1322 let mut node_1_per_peer_lock;
1323 let mut node_1_peer_state_lock;
1324 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1326 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1327 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1328 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1329 channel_2.get_short_channel_id().unwrap()
1331 assert_eq!(chan_2_used_liquidity, None);
1334 let pending_payments = nodes[0].node.list_recent_payments();
1335 assert_eq!(pending_payments.len(), 0);
1339 fn test_holding_cell_inflight_htlcs() {
1340 let chanmon_cfgs = create_chanmon_cfgs(2);
1341 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1342 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1343 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1344 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1346 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1347 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1349 // Queue up two payments - one will be delivered right away, one immediately goes into the
1350 // holding cell as nodes[0] is AwaitingRAA.
1352 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1353 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1354 check_added_monitors!(nodes[0], 1);
1355 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1356 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1357 check_added_monitors!(nodes[0], 0);
1360 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1363 let mut node_0_per_peer_lock;
1364 let mut node_0_peer_state_lock;
1365 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1367 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1368 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1369 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1370 channel.get_short_channel_id().unwrap()
1373 assert_eq!(used_liquidity, Some(2000000));
1376 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1377 nodes[0].node.get_and_clear_pending_msg_events();
1381 fn intercepted_payment() {
1382 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1383 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1384 // payment or (b) fail the payment.
1385 do_test_intercepted_payment(InterceptTest::Forward);
1386 do_test_intercepted_payment(InterceptTest::Fail);
1387 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1388 do_test_intercepted_payment(InterceptTest::Timeout);
1391 fn do_test_intercepted_payment(test: InterceptTest) {
1392 let chanmon_cfgs = create_chanmon_cfgs(3);
1393 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1395 let mut zero_conf_chan_config = test_default_channel_config();
1396 zero_conf_chan_config.manually_accept_inbound_channels = true;
1397 let mut intercept_forwards_config = test_default_channel_config();
1398 intercept_forwards_config.accept_intercept_htlcs = true;
1399 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1401 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1402 let scorer = test_utils::TestScorer::new();
1403 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1405 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1407 let amt_msat = 100_000;
1408 let intercept_scid = nodes[1].node.get_intercept_scid();
1409 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1410 .with_route_hints(vec![
1411 RouteHint(vec![RouteHintHop {
1412 src_node_id: nodes[1].node.get_our_node_id(),
1413 short_channel_id: intercept_scid,
1416 proportional_millionths: 0,
1418 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1419 htlc_minimum_msat: None,
1420 htlc_maximum_msat: None,
1423 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1424 let route_params = RouteParameters {
1426 final_value_msat: amt_msat,
1428 let route = get_route(
1429 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1430 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1431 nodes[0].logger, &scorer, &(), &random_seed_bytes,
1434 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1435 nodes[0].node.send_payment_with_route(&route, payment_hash,
1436 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1437 let payment_event = {
1439 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1440 assert_eq!(added_monitors.len(), 1);
1441 added_monitors.clear();
1443 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1444 assert_eq!(events.len(), 1);
1445 SendEvent::from_event(events.remove(0))
1447 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1448 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1450 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1451 let events = nodes[1].node.get_and_clear_pending_events();
1452 assert_eq!(events.len(), 1);
1453 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1454 crate::events::Event::HTLCIntercepted {
1455 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1457 assert_eq!(pmt_hash, payment_hash);
1458 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1459 assert_eq!(short_channel_id, intercept_scid);
1460 (intercept_id, expected_outbound_amount_msat)
1465 // Check for unknown channel id error.
1466 let unknown_chan_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &[42; 32], nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1467 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1469 if test == InterceptTest::Fail {
1470 // Ensure we can fail the intercepted payment back.
1471 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1472 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1473 nodes[1].node.process_pending_htlc_forwards();
1474 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1475 check_added_monitors!(&nodes[1], 1);
1476 assert!(update_fail.update_fail_htlcs.len() == 1);
1477 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1478 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1479 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1481 // Ensure the payment fails with the expected error.
1482 let fail_conditions = PaymentFailedConditions::new()
1483 .blamed_scid(intercept_scid)
1484 .blamed_chan_closed(true)
1485 .expected_htlc_error_data(0x4000 | 10, &[]);
1486 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1487 } else if test == InterceptTest::Forward {
1488 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1489 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1490 let unusable_chan_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &temp_chan_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1491 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1492 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1494 // Open the just-in-time channel so the payment can then be forwarded.
1495 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1497 // Finally, forward the intercepted payment through and claim it.
1498 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1499 expect_pending_htlcs_forwardable!(nodes[1]);
1501 let payment_event = {
1503 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1504 assert_eq!(added_monitors.len(), 1);
1505 added_monitors.clear();
1507 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1508 assert_eq!(events.len(), 1);
1509 SendEvent::from_event(events.remove(0))
1511 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1512 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1513 expect_pending_htlcs_forwardable!(nodes[2]);
1515 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1516 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1517 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1518 let events = nodes[0].node.get_and_clear_pending_events();
1519 assert_eq!(events.len(), 2);
1521 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1522 assert_eq!(payment_preimage, *ev_preimage);
1523 assert_eq!(payment_hash, *ev_hash);
1524 assert_eq!(fee_paid_msat, &Some(1000));
1526 _ => panic!("Unexpected event")
1529 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1530 assert_eq!(hash, Some(payment_hash));
1532 _ => panic!("Unexpected event")
1534 } else if test == InterceptTest::Timeout {
1535 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
1536 connect_block(&nodes[0], &block);
1537 connect_block(&nodes[1], &block);
1538 for _ in 0..TEST_FINAL_CLTV {
1539 block.header.prev_blockhash = block.block_hash();
1540 connect_block(&nodes[0], &block);
1541 connect_block(&nodes[1], &block);
1543 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1544 check_added_monitors!(nodes[1], 1);
1545 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1546 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1547 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1548 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1549 assert!(htlc_timeout_updates.update_fee.is_none());
1551 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1552 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1553 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1555 // Check for unknown intercept id error.
1556 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1557 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();
1558 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1559 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1560 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1564 #[derive(PartialEq)]
1575 fn automatic_retries() {
1576 do_automatic_retries(AutoRetry::Success);
1577 do_automatic_retries(AutoRetry::Spontaneous);
1578 do_automatic_retries(AutoRetry::FailAttempts);
1579 do_automatic_retries(AutoRetry::FailTimeout);
1580 do_automatic_retries(AutoRetry::FailOnRestart);
1581 do_automatic_retries(AutoRetry::FailOnRetry);
1583 fn do_automatic_retries(test: AutoRetry) {
1584 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1586 let chanmon_cfgs = create_chanmon_cfgs(3);
1587 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1588 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1591 let new_chain_monitor;
1592 let node_0_deserialized;
1594 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1595 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1596 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1598 // Marshall data to send the payment
1599 #[cfg(feature = "std")]
1600 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1601 #[cfg(not(feature = "std"))]
1602 let payment_expiry_secs = 60 * 60;
1603 let amt_msat = 1000;
1604 let mut invoice_features = InvoiceFeatures::empty();
1605 invoice_features.set_variable_length_onion_required();
1606 invoice_features.set_payment_secret_required();
1607 invoice_features.set_basic_mpp_optional();
1608 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1609 .with_expiry_time(payment_expiry_secs as u64)
1610 .with_bolt11_features(invoice_features).unwrap();
1611 let route_params = RouteParameters {
1613 final_value_msat: amt_msat,
1615 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1617 macro_rules! pass_failed_attempt_with_retry_along_path {
1618 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1619 // Send a payment attempt that fails due to lack of liquidity on the second hop
1620 check_added_monitors!(nodes[0], 1);
1621 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1622 let mut update_add = update_0.update_add_htlcs[0].clone();
1623 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1624 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1625 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1626 nodes[1].node.process_pending_htlc_forwards();
1627 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1628 vec![HTLCDestination::NextHopChannel {
1629 node_id: Some(nodes[2].node.get_our_node_id()),
1630 channel_id: $failing_channel_id,
1632 nodes[1].node.process_pending_htlc_forwards();
1633 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1634 check_added_monitors!(&nodes[1], 1);
1635 assert!(update_1.update_fail_htlcs.len() == 1);
1636 let fail_msg = update_1.update_fail_htlcs[0].clone();
1637 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1638 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1640 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1641 let mut events = nodes[0].node.get_and_clear_pending_events();
1642 assert_eq!(events.len(), 2);
1644 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1645 assert_eq!(payment_hash, ev_payment_hash);
1646 assert_eq!(payment_failed_permanently, false);
1648 _ => panic!("Unexpected event"),
1650 if $expect_pending_htlcs_forwardable {
1652 Event::PendingHTLCsForwardable { .. } => {},
1653 _ => panic!("Unexpected event"),
1657 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1658 assert_eq!(payment_hash, ev_payment_hash);
1660 _ => panic!("Unexpected event"),
1666 if test == AutoRetry::Success {
1667 // Test that we can succeed on the first retry.
1668 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1669 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1670 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1672 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1673 // attempt, since the initial second hop channel will be excluded from pathfinding
1674 create_announced_chan_between_nodes(&nodes, 1, 2);
1676 // We retry payments in `process_pending_htlc_forwards`
1677 nodes[0].node.process_pending_htlc_forwards();
1678 check_added_monitors!(nodes[0], 1);
1679 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1680 assert_eq!(msg_events.len(), 1);
1681 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1682 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1683 } else if test == AutoRetry::Spontaneous {
1684 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
1685 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
1686 Retry::Attempts(1)).unwrap();
1687 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1689 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1690 // attempt, since the initial second hop channel will be excluded from pathfinding
1691 create_announced_chan_between_nodes(&nodes, 1, 2);
1693 // We retry payments in `process_pending_htlc_forwards`
1694 nodes[0].node.process_pending_htlc_forwards();
1695 check_added_monitors!(nodes[0], 1);
1696 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1697 assert_eq!(msg_events.len(), 1);
1698 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1699 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1700 } else if test == AutoRetry::FailAttempts {
1701 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1702 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1703 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1704 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1706 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1707 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1708 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1710 // We retry payments in `process_pending_htlc_forwards`
1711 nodes[0].node.process_pending_htlc_forwards();
1712 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1714 // Ensure we won't retry a second time.
1715 nodes[0].node.process_pending_htlc_forwards();
1716 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1717 assert_eq!(msg_events.len(), 0);
1718 } else if test == AutoRetry::FailTimeout {
1719 #[cfg(not(feature = "no-std"))] {
1720 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1721 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1722 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
1723 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1725 // Advance the time so the second attempt fails due to timeout.
1726 SinceEpoch::advance(Duration::from_secs(61));
1728 // Make sure we don't retry again.
1729 nodes[0].node.process_pending_htlc_forwards();
1730 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1731 assert_eq!(msg_events.len(), 0);
1733 let mut events = nodes[0].node.get_and_clear_pending_events();
1734 assert_eq!(events.len(), 1);
1736 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1737 assert_eq!(payment_hash, *ev_payment_hash);
1738 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1739 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
1741 _ => panic!("Unexpected event"),
1744 } else if test == AutoRetry::FailOnRestart {
1745 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1746 // attempts remaining prior to restart.
1747 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1748 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1749 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1751 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1752 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1753 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1755 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1756 nodes[0].node.process_pending_htlc_forwards();
1757 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1759 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1760 let node_encoded = nodes[0].node.encode();
1761 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1762 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1764 let mut events = nodes[0].node.get_and_clear_pending_events();
1765 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
1766 // Make sure we don't retry again.
1767 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1768 assert_eq!(msg_events.len(), 0);
1770 let mut events = nodes[0].node.get_and_clear_pending_events();
1771 assert_eq!(events.len(), 1);
1773 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1774 assert_eq!(payment_hash, *ev_payment_hash);
1775 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1776 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
1778 _ => panic!("Unexpected event"),
1780 } else if test == AutoRetry::FailOnRetry {
1781 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1782 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1783 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1785 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1786 // fail to find a route.
1787 nodes[0].node.process_pending_htlc_forwards();
1788 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1789 assert_eq!(msg_events.len(), 0);
1791 let mut events = nodes[0].node.get_and_clear_pending_events();
1792 assert_eq!(events.len(), 1);
1794 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1795 assert_eq!(payment_hash, *ev_payment_hash);
1796 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1797 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
1799 _ => panic!("Unexpected event"),
1805 fn auto_retry_partial_failure() {
1806 // Test that we'll retry appropriately on send partial failure and retry partial failure.
1807 let chanmon_cfgs = create_chanmon_cfgs(2);
1808 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1809 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1810 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1812 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1813 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1814 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1816 // Marshall data to send the payment
1817 let amt_msat = 20_000;
1818 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1819 #[cfg(feature = "std")]
1820 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1821 #[cfg(not(feature = "std"))]
1822 let payment_expiry_secs = 60 * 60;
1823 let mut invoice_features = InvoiceFeatures::empty();
1824 invoice_features.set_variable_length_onion_required();
1825 invoice_features.set_payment_secret_required();
1826 invoice_features.set_basic_mpp_optional();
1827 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1828 .with_expiry_time(payment_expiry_secs as u64)
1829 .with_bolt11_features(invoice_features).unwrap();
1830 let route_params = RouteParameters {
1832 final_value_msat: amt_msat,
1835 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1836 // second (for the initial send path2 over chan_2) fails.
1837 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1838 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1839 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1840 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1841 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1842 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1843 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1845 // Configure the initial send, retry1 and retry2's paths.
1846 let send_route = Route {
1848 Path { hops: vec![RouteHop {
1849 pubkey: nodes[1].node.get_our_node_id(),
1850 node_features: nodes[1].node.node_features(),
1851 short_channel_id: chan_1_id,
1852 channel_features: nodes[1].node.channel_features(),
1853 fee_msat: amt_msat / 2,
1854 cltv_expiry_delta: 100,
1855 }], blinded_tail: None },
1856 Path { hops: vec![RouteHop {
1857 pubkey: nodes[1].node.get_our_node_id(),
1858 node_features: nodes[1].node.node_features(),
1859 short_channel_id: chan_2_id,
1860 channel_features: nodes[1].node.channel_features(),
1861 fee_msat: amt_msat / 2,
1862 cltv_expiry_delta: 100,
1863 }], blinded_tail: None },
1865 payment_params: Some(route_params.payment_params.clone()),
1867 let retry_1_route = Route {
1869 Path { hops: vec![RouteHop {
1870 pubkey: nodes[1].node.get_our_node_id(),
1871 node_features: nodes[1].node.node_features(),
1872 short_channel_id: chan_1_id,
1873 channel_features: nodes[1].node.channel_features(),
1874 fee_msat: amt_msat / 4,
1875 cltv_expiry_delta: 100,
1876 }], blinded_tail: None },
1877 Path { hops: vec![RouteHop {
1878 pubkey: nodes[1].node.get_our_node_id(),
1879 node_features: nodes[1].node.node_features(),
1880 short_channel_id: chan_3_id,
1881 channel_features: nodes[1].node.channel_features(),
1882 fee_msat: amt_msat / 4,
1883 cltv_expiry_delta: 100,
1884 }], blinded_tail: None },
1886 payment_params: Some(route_params.payment_params.clone()),
1888 let retry_2_route = Route {
1890 Path { hops: vec![RouteHop {
1891 pubkey: nodes[1].node.get_our_node_id(),
1892 node_features: nodes[1].node.node_features(),
1893 short_channel_id: chan_1_id,
1894 channel_features: nodes[1].node.channel_features(),
1895 fee_msat: amt_msat / 4,
1896 cltv_expiry_delta: 100,
1897 }], blinded_tail: None },
1899 payment_params: Some(route_params.payment_params.clone()),
1901 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1902 let mut payment_params = route_params.payment_params.clone();
1903 payment_params.previously_failed_channels.push(chan_2_id);
1904 nodes[0].router.expect_find_route(RouteParameters {
1905 payment_params, final_value_msat: amt_msat / 2,
1906 }, Ok(retry_1_route));
1907 let mut payment_params = route_params.payment_params.clone();
1908 payment_params.previously_failed_channels.push(chan_3_id);
1909 nodes[0].router.expect_find_route(RouteParameters {
1910 payment_params, final_value_msat: amt_msat / 4,
1911 }, Ok(retry_2_route));
1913 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1914 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1915 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1916 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1917 assert_eq!(closed_chan_events.len(), 4);
1918 match closed_chan_events[0] {
1919 Event::ChannelClosed { .. } => {},
1920 _ => panic!("Unexpected event"),
1922 match closed_chan_events[1] {
1923 Event::PaymentPathFailed { .. } => {},
1924 _ => panic!("Unexpected event"),
1926 match closed_chan_events[2] {
1927 Event::ChannelClosed { .. } => {},
1928 _ => panic!("Unexpected event"),
1930 match closed_chan_events[3] {
1931 Event::PaymentPathFailed { .. } => {},
1932 _ => panic!("Unexpected event"),
1935 // Pass the first part of the payment along the path.
1936 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1937 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1939 // First message is the first update_add, remaining messages are broadcasting channel updates and
1940 // errors for the permfailed channels
1941 assert_eq!(msg_events.len(), 5);
1942 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1944 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1945 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1946 check_added_monitors!(nodes[1], 1);
1947 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1949 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1950 check_added_monitors!(nodes[0], 1);
1951 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1953 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1954 check_added_monitors!(nodes[0], 1);
1955 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1957 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1958 check_added_monitors!(nodes[1], 1);
1960 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1961 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1962 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1963 check_added_monitors!(nodes[1], 1);
1964 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1966 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1967 check_added_monitors!(nodes[0], 1);
1969 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
1970 check_added_monitors!(nodes[0], 1);
1971 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1973 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1974 check_added_monitors!(nodes[1], 1);
1976 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1977 nodes[1].node.process_pending_htlc_forwards();
1978 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
1979 nodes[1].node.claim_funds(payment_preimage);
1980 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
1981 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1982 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
1984 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
1985 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
1986 check_added_monitors!(nodes[0], 1);
1987 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1989 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1990 check_added_monitors!(nodes[1], 4);
1991 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1993 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1994 check_added_monitors!(nodes[1], 1);
1995 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1997 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1998 check_added_monitors!(nodes[0], 1);
2000 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2001 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2002 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2003 check_added_monitors!(nodes[0], 1);
2004 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2006 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2007 check_added_monitors!(nodes[1], 1);
2009 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2010 check_added_monitors!(nodes[1], 1);
2011 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2013 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2014 check_added_monitors!(nodes[0], 1);
2015 expect_payment_sent!(nodes[0], payment_preimage);
2019 fn auto_retry_zero_attempts_send_error() {
2020 let chanmon_cfgs = create_chanmon_cfgs(2);
2021 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2022 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2023 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2025 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2026 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2028 // Marshall data to send the payment
2029 let amt_msat = 20_000;
2030 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2031 #[cfg(feature = "std")]
2032 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2033 #[cfg(not(feature = "std"))]
2034 let payment_expiry_secs = 60 * 60;
2035 let mut invoice_features = InvoiceFeatures::empty();
2036 invoice_features.set_variable_length_onion_required();
2037 invoice_features.set_payment_secret_required();
2038 invoice_features.set_basic_mpp_optional();
2039 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2040 .with_expiry_time(payment_expiry_secs as u64)
2041 .with_bolt11_features(invoice_features).unwrap();
2042 let route_params = RouteParameters {
2044 final_value_msat: amt_msat,
2047 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2048 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2049 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2050 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2051 let events = nodes[0].node.get_and_clear_pending_events();
2052 assert_eq!(events.len(), 3);
2053 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2054 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2055 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2056 check_added_monitors!(nodes[0], 2);
2060 fn fails_paying_after_rejected_by_payee() {
2061 let chanmon_cfgs = create_chanmon_cfgs(2);
2062 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2063 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2064 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2066 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2068 // Marshall data to send the payment
2069 let amt_msat = 20_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_bolt11_features(invoice_features).unwrap();
2082 let route_params = RouteParameters {
2084 final_value_msat: amt_msat,
2087 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2088 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2089 check_added_monitors!(nodes[0], 1);
2090 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2091 assert_eq!(events.len(), 1);
2092 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2093 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2094 check_added_monitors!(nodes[1], 0);
2095 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2096 expect_pending_htlcs_forwardable!(nodes[1]);
2097 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2099 nodes[1].node.fail_htlc_backwards(&payment_hash);
2100 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2101 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2105 fn retry_multi_path_single_failed_payment() {
2106 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2107 let chanmon_cfgs = create_chanmon_cfgs(2);
2108 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2109 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2110 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2112 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2113 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2115 let amt_msat = 100_010_000;
2117 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2118 #[cfg(feature = "std")]
2119 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2120 #[cfg(not(feature = "std"))]
2121 let payment_expiry_secs = 60 * 60;
2122 let mut invoice_features = InvoiceFeatures::empty();
2123 invoice_features.set_variable_length_onion_required();
2124 invoice_features.set_payment_secret_required();
2125 invoice_features.set_basic_mpp_optional();
2126 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2127 .with_expiry_time(payment_expiry_secs as u64)
2128 .with_bolt11_features(invoice_features).unwrap();
2129 let route_params = RouteParameters {
2130 payment_params: payment_params.clone(),
2131 final_value_msat: amt_msat,
2134 let chans = nodes[0].node.list_usable_channels();
2135 let mut route = Route {
2137 Path { hops: vec![RouteHop {
2138 pubkey: nodes[1].node.get_our_node_id(),
2139 node_features: nodes[1].node.node_features(),
2140 short_channel_id: chans[0].short_channel_id.unwrap(),
2141 channel_features: nodes[1].node.channel_features(),
2143 cltv_expiry_delta: 100,
2144 }], blinded_tail: None },
2145 Path { hops: vec![RouteHop {
2146 pubkey: nodes[1].node.get_our_node_id(),
2147 node_features: nodes[1].node.node_features(),
2148 short_channel_id: chans[1].short_channel_id.unwrap(),
2149 channel_features: nodes[1].node.channel_features(),
2150 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2151 cltv_expiry_delta: 100,
2152 }], blinded_tail: None },
2154 payment_params: Some(payment_params),
2156 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2157 // On retry, split the payment across both channels.
2158 route.paths[0].hops[0].fee_msat = 50_000_001;
2159 route.paths[1].hops[0].fee_msat = 50_000_000;
2160 let mut pay_params = route.payment_params.clone().unwrap();
2161 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2162 nodes[0].router.expect_find_route(RouteParameters {
2163 payment_params: pay_params,
2164 // Note that the second request here requests the amount we originally failed to send,
2165 // not the amount remaining on the full payment, which should be changed.
2166 final_value_msat: 100_000_001,
2167 }, Ok(route.clone()));
2170 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2171 // The initial send attempt, 2 paths
2172 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2173 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2174 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2175 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2176 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2179 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2180 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2181 let events = nodes[0].node.get_and_clear_pending_events();
2182 assert_eq!(events.len(), 1);
2184 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2185 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2186 short_channel_id: Some(expected_scid), .. } =>
2188 assert_eq!(payment_hash, ev_payment_hash);
2189 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2191 _ => panic!("Unexpected event"),
2193 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2194 assert_eq!(htlc_msgs.len(), 2);
2195 check_added_monitors!(nodes[0], 2);
2199 fn immediate_retry_on_failure() {
2200 // Tests that we can/will retry immediately after a failure
2201 let chanmon_cfgs = create_chanmon_cfgs(2);
2202 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2203 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2204 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2206 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2207 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2209 let amt_msat = 100_000_001;
2210 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2211 #[cfg(feature = "std")]
2212 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2213 #[cfg(not(feature = "std"))]
2214 let payment_expiry_secs = 60 * 60;
2215 let mut invoice_features = InvoiceFeatures::empty();
2216 invoice_features.set_variable_length_onion_required();
2217 invoice_features.set_payment_secret_required();
2218 invoice_features.set_basic_mpp_optional();
2219 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2220 .with_expiry_time(payment_expiry_secs as u64)
2221 .with_bolt11_features(invoice_features).unwrap();
2222 let route_params = RouteParameters {
2224 final_value_msat: amt_msat,
2227 let chans = nodes[0].node.list_usable_channels();
2228 let mut route = Route {
2230 Path { hops: vec![RouteHop {
2231 pubkey: nodes[1].node.get_our_node_id(),
2232 node_features: nodes[1].node.node_features(),
2233 short_channel_id: chans[0].short_channel_id.unwrap(),
2234 channel_features: nodes[1].node.channel_features(),
2235 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2236 cltv_expiry_delta: 100,
2237 }], blinded_tail: None },
2239 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2241 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2242 // On retry, split the payment across both channels.
2243 route.paths.push(route.paths[0].clone());
2244 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2245 route.paths[0].hops[0].fee_msat = 50_000_000;
2246 route.paths[1].hops[0].fee_msat = 50_000_001;
2247 let mut pay_params = route_params.payment_params.clone();
2248 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2249 nodes[0].router.expect_find_route(RouteParameters {
2250 payment_params: pay_params, final_value_msat: amt_msat,
2251 }, Ok(route.clone()));
2253 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2254 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2255 let events = nodes[0].node.get_and_clear_pending_events();
2256 assert_eq!(events.len(), 1);
2258 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2259 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2260 short_channel_id: Some(expected_scid), .. } =>
2262 assert_eq!(payment_hash, ev_payment_hash);
2263 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2265 _ => panic!("Unexpected event"),
2267 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2268 assert_eq!(htlc_msgs.len(), 2);
2269 check_added_monitors!(nodes[0], 2);
2273 fn no_extra_retries_on_back_to_back_fail() {
2274 // In a previous release, we had a race where we may exceed the payment retry count if we
2275 // get two failures in a row with the second indicating that all paths had failed (this field,
2276 // `all_paths_failed`, has since been removed).
2277 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2278 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2279 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2280 // pending which we will see later. Thus, when we previously removed the retry tracking map
2281 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2282 // retry entry even though more events for the same payment were still pending. This led to
2283 // us retrying a payment again even though we'd already given up on it.
2285 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2286 // is used to remove the payment retry counter entries instead. This tests for the specific
2287 // excess-retry case while also testing `PaymentFailed` generation.
2289 let chanmon_cfgs = create_chanmon_cfgs(3);
2290 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2291 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2292 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2294 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2295 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2297 let amt_msat = 200_000_000;
2298 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2299 #[cfg(feature = "std")]
2300 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2301 #[cfg(not(feature = "std"))]
2302 let payment_expiry_secs = 60 * 60;
2303 let mut invoice_features = InvoiceFeatures::empty();
2304 invoice_features.set_variable_length_onion_required();
2305 invoice_features.set_payment_secret_required();
2306 invoice_features.set_basic_mpp_optional();
2307 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2308 .with_expiry_time(payment_expiry_secs as u64)
2309 .with_bolt11_features(invoice_features).unwrap();
2310 let route_params = RouteParameters {
2312 final_value_msat: amt_msat,
2315 let mut route = Route {
2317 Path { hops: vec![RouteHop {
2318 pubkey: nodes[1].node.get_our_node_id(),
2319 node_features: nodes[1].node.node_features(),
2320 short_channel_id: chan_1_scid,
2321 channel_features: nodes[1].node.channel_features(),
2322 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2323 cltv_expiry_delta: 100,
2325 pubkey: nodes[2].node.get_our_node_id(),
2326 node_features: nodes[2].node.node_features(),
2327 short_channel_id: chan_2_scid,
2328 channel_features: nodes[2].node.channel_features(),
2329 fee_msat: 100_000_000,
2330 cltv_expiry_delta: 100,
2331 }], blinded_tail: None },
2332 Path { hops: vec![RouteHop {
2333 pubkey: nodes[1].node.get_our_node_id(),
2334 node_features: nodes[1].node.node_features(),
2335 short_channel_id: chan_1_scid,
2336 channel_features: nodes[1].node.channel_features(),
2337 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2338 cltv_expiry_delta: 100,
2340 pubkey: nodes[2].node.get_our_node_id(),
2341 node_features: nodes[2].node.node_features(),
2342 short_channel_id: chan_2_scid,
2343 channel_features: nodes[2].node.channel_features(),
2344 fee_msat: 100_000_000,
2345 cltv_expiry_delta: 100,
2346 }], blinded_tail: None }
2348 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2350 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2351 let mut second_payment_params = route_params.payment_params.clone();
2352 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2353 // On retry, we'll only return one path
2354 route.paths.remove(1);
2355 route.paths[0].hops[1].fee_msat = amt_msat;
2356 nodes[0].router.expect_find_route(RouteParameters {
2357 payment_params: second_payment_params,
2358 final_value_msat: amt_msat,
2359 }, Ok(route.clone()));
2361 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2362 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2363 let htlc_updates = SendEvent::from_node(&nodes[0]);
2364 check_added_monitors!(nodes[0], 1);
2365 assert_eq!(htlc_updates.msgs.len(), 1);
2367 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2368 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2369 check_added_monitors!(nodes[1], 1);
2370 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2372 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2373 check_added_monitors!(nodes[0], 1);
2374 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2376 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2377 check_added_monitors!(nodes[0], 1);
2378 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2380 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2381 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2382 check_added_monitors!(nodes[1], 1);
2383 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2385 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2386 check_added_monitors!(nodes[1], 1);
2387 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2389 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2390 check_added_monitors!(nodes[0], 1);
2392 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2393 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2394 check_added_monitors!(nodes[0], 1);
2395 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2397 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2398 check_added_monitors!(nodes[1], 1);
2399 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2401 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2402 check_added_monitors!(nodes[1], 1);
2403 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2405 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2406 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2407 check_added_monitors!(nodes[0], 1);
2409 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2410 check_added_monitors!(nodes[0], 1);
2411 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2413 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2414 check_added_monitors!(nodes[1], 1);
2415 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2416 check_added_monitors!(nodes[1], 1);
2417 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2419 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2420 check_added_monitors!(nodes[0], 1);
2422 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2423 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2426 // Previously, we retried payments in an event consumer, which would retry each
2427 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2428 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2429 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2430 // by adding the `PaymentFailed` event.
2432 // Because we now retry payments as a batch, we simply return a single-path route in the
2433 // second, batched, request, have that fail, ensure the payment was abandoned.
2434 let mut events = nodes[0].node.get_and_clear_pending_events();
2435 assert_eq!(events.len(), 3);
2437 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2438 assert_eq!(payment_hash, ev_payment_hash);
2439 assert_eq!(payment_failed_permanently, false);
2441 _ => panic!("Unexpected event"),
2444 Event::PendingHTLCsForwardable { .. } => {},
2445 _ => panic!("Unexpected event"),
2448 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2449 assert_eq!(payment_hash, ev_payment_hash);
2450 assert_eq!(payment_failed_permanently, false);
2452 _ => panic!("Unexpected event"),
2455 nodes[0].node.process_pending_htlc_forwards();
2456 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2457 check_added_monitors!(nodes[0], 1);
2459 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2460 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2461 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2462 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2463 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2465 let mut events = nodes[0].node.get_and_clear_pending_events();
2466 assert_eq!(events.len(), 2);
2468 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2469 assert_eq!(payment_hash, ev_payment_hash);
2470 assert_eq!(payment_failed_permanently, false);
2472 _ => panic!("Unexpected event"),
2475 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2476 assert_eq!(payment_hash, *ev_payment_hash);
2477 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2478 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2480 _ => panic!("Unexpected event"),
2485 fn test_simple_partial_retry() {
2486 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2487 // full amount of the payment, rather than only the missing amount. Here we simply test for
2488 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2489 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2491 let chanmon_cfgs = create_chanmon_cfgs(3);
2492 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2493 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2494 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2496 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2497 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2499 let amt_msat = 200_000_000;
2500 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2501 #[cfg(feature = "std")]
2502 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2503 #[cfg(not(feature = "std"))]
2504 let payment_expiry_secs = 60 * 60;
2505 let mut invoice_features = InvoiceFeatures::empty();
2506 invoice_features.set_variable_length_onion_required();
2507 invoice_features.set_payment_secret_required();
2508 invoice_features.set_basic_mpp_optional();
2509 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2510 .with_expiry_time(payment_expiry_secs as u64)
2511 .with_bolt11_features(invoice_features).unwrap();
2512 let route_params = RouteParameters {
2514 final_value_msat: amt_msat,
2517 let mut route = Route {
2519 Path { hops: vec![RouteHop {
2520 pubkey: nodes[1].node.get_our_node_id(),
2521 node_features: nodes[1].node.node_features(),
2522 short_channel_id: chan_1_scid,
2523 channel_features: nodes[1].node.channel_features(),
2524 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2525 cltv_expiry_delta: 100,
2527 pubkey: nodes[2].node.get_our_node_id(),
2528 node_features: nodes[2].node.node_features(),
2529 short_channel_id: chan_2_scid,
2530 channel_features: nodes[2].node.channel_features(),
2531 fee_msat: 100_000_000,
2532 cltv_expiry_delta: 100,
2533 }], blinded_tail: None },
2534 Path { hops: vec![RouteHop {
2535 pubkey: nodes[1].node.get_our_node_id(),
2536 node_features: nodes[1].node.node_features(),
2537 short_channel_id: chan_1_scid,
2538 channel_features: nodes[1].node.channel_features(),
2540 cltv_expiry_delta: 100,
2542 pubkey: nodes[2].node.get_our_node_id(),
2543 node_features: nodes[2].node.node_features(),
2544 short_channel_id: chan_2_scid,
2545 channel_features: nodes[2].node.channel_features(),
2546 fee_msat: 100_000_000,
2547 cltv_expiry_delta: 100,
2548 }], blinded_tail: None }
2550 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2552 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2553 let mut second_payment_params = route_params.payment_params.clone();
2554 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2555 // On retry, we'll only be asked for one path (or 100k sats)
2556 route.paths.remove(0);
2557 nodes[0].router.expect_find_route(RouteParameters {
2558 payment_params: second_payment_params,
2559 final_value_msat: amt_msat / 2,
2560 }, Ok(route.clone()));
2562 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2563 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2564 let htlc_updates = SendEvent::from_node(&nodes[0]);
2565 check_added_monitors!(nodes[0], 1);
2566 assert_eq!(htlc_updates.msgs.len(), 1);
2568 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2569 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2570 check_added_monitors!(nodes[1], 1);
2571 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2573 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2574 check_added_monitors!(nodes[0], 1);
2575 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2577 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2578 check_added_monitors!(nodes[0], 1);
2579 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2581 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2582 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2583 check_added_monitors!(nodes[1], 1);
2584 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2586 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2587 check_added_monitors!(nodes[1], 1);
2588 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2590 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2591 check_added_monitors!(nodes[0], 1);
2593 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2594 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2595 check_added_monitors!(nodes[0], 1);
2596 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2598 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2599 check_added_monitors!(nodes[1], 1);
2601 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2602 check_added_monitors!(nodes[1], 1);
2604 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2606 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2607 check_added_monitors!(nodes[0], 1);
2609 let mut events = nodes[0].node.get_and_clear_pending_events();
2610 assert_eq!(events.len(), 2);
2612 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2613 assert_eq!(payment_hash, ev_payment_hash);
2614 assert_eq!(payment_failed_permanently, false);
2616 _ => panic!("Unexpected event"),
2619 Event::PendingHTLCsForwardable { .. } => {},
2620 _ => panic!("Unexpected event"),
2623 nodes[0].node.process_pending_htlc_forwards();
2624 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2625 check_added_monitors!(nodes[0], 1);
2627 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2628 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2630 expect_pending_htlcs_forwardable!(nodes[1]);
2631 check_added_monitors!(nodes[1], 1);
2633 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2634 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2635 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2636 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2638 expect_pending_htlcs_forwardable!(nodes[2]);
2639 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2643 #[cfg(feature = "std")]
2644 fn test_threaded_payment_retries() {
2645 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2646 // a single thread and would happily let multiple threads run retries at the same time. Because
2647 // retries are done by first calculating the amount we need to retry, then dropping the
2648 // relevant lock, then actually sending, we would happily let multiple threads retry the same
2649 // amount at the same time, overpaying our original HTLC!
2650 let chanmon_cfgs = create_chanmon_cfgs(4);
2651 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2652 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2653 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2655 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2656 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2657 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2658 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2660 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2661 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2662 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2663 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2665 let amt_msat = 100_000_000;
2666 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2667 #[cfg(feature = "std")]
2668 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2669 #[cfg(not(feature = "std"))]
2670 let payment_expiry_secs = 60 * 60;
2671 let mut invoice_features = InvoiceFeatures::empty();
2672 invoice_features.set_variable_length_onion_required();
2673 invoice_features.set_payment_secret_required();
2674 invoice_features.set_basic_mpp_optional();
2675 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2676 .with_expiry_time(payment_expiry_secs as u64)
2677 .with_bolt11_features(invoice_features).unwrap();
2678 let mut route_params = RouteParameters {
2680 final_value_msat: amt_msat,
2683 let mut route = Route {
2685 Path { hops: vec![RouteHop {
2686 pubkey: nodes[1].node.get_our_node_id(),
2687 node_features: nodes[1].node.node_features(),
2688 short_channel_id: chan_1_scid,
2689 channel_features: nodes[1].node.channel_features(),
2691 cltv_expiry_delta: 100,
2693 pubkey: nodes[3].node.get_our_node_id(),
2694 node_features: nodes[2].node.node_features(),
2695 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2696 channel_features: nodes[2].node.channel_features(),
2697 fee_msat: amt_msat / 1000,
2698 cltv_expiry_delta: 100,
2699 }], blinded_tail: None },
2700 Path { hops: vec![RouteHop {
2701 pubkey: nodes[2].node.get_our_node_id(),
2702 node_features: nodes[2].node.node_features(),
2703 short_channel_id: chan_3_scid,
2704 channel_features: nodes[2].node.channel_features(),
2706 cltv_expiry_delta: 100,
2708 pubkey: nodes[3].node.get_our_node_id(),
2709 node_features: nodes[3].node.node_features(),
2710 short_channel_id: chan_4_scid,
2711 channel_features: nodes[3].node.channel_features(),
2712 fee_msat: amt_msat - amt_msat / 1000,
2713 cltv_expiry_delta: 100,
2714 }], blinded_tail: None }
2716 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2718 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2720 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2721 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
2722 check_added_monitors!(nodes[0], 2);
2723 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2724 assert_eq!(send_msg_events.len(), 2);
2725 send_msg_events.retain(|msg|
2726 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
2727 // Drop the commitment update for nodes[2], we can just let that one sit pending
2729 *node_id == nodes[1].node.get_our_node_id()
2730 } else { panic!(); }
2733 // from here on out, the retry `RouteParameters` amount will be amt/1000
2734 route_params.final_value_msat /= 1000;
2737 let end_time = Instant::now() + Duration::from_secs(1);
2738 macro_rules! thread_body { () => { {
2739 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
2740 let node_ref = NodePtr::from_node(&nodes[0]);
2742 let node_a = unsafe { &*node_ref.0 };
2743 while Instant::now() < end_time {
2744 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2745 // Ignore if we have any pending events, just always pretend we just got a
2746 // PendingHTLCsForwardable
2747 node_a.node.process_pending_htlc_forwards();
2751 let mut threads = Vec::new();
2752 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
2754 // Back in the main thread, poll pending messages and make sure that we never have more than
2755 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
2756 // there are HTLC messages shoved in while its running. This allows us to test that we never
2757 // generate an additional update_add_htlc until we've fully failed the first.
2758 let mut previously_failed_channels = Vec::new();
2760 assert_eq!(send_msg_events.len(), 1);
2761 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
2762 assert_eq!(send_event.msgs.len(), 1);
2764 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
2765 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
2767 // Note that we only push one route into `expect_find_route` at a time, because that's all
2768 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
2769 // we should still ultimately fail for the same reason - because we're trying to send too
2770 // many HTLCs at once.
2771 let mut new_route_params = route_params.clone();
2772 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
2773 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
2774 route.paths[0].hops[1].short_channel_id += 1;
2775 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
2777 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2778 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
2779 // The "normal" commitment_signed_dance delivers the final RAA and then calls
2780 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
2781 // This races with our other threads which may generate an add-HTLCs commitment update via
2782 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
2783 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
2784 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
2785 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
2787 let cur_time = Instant::now();
2788 if cur_time > end_time {
2789 for thread in threads.drain(..) { thread.join().unwrap(); }
2792 // Make sure we have some events to handle when we go around...
2793 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2794 nodes[0].node.process_pending_htlc_forwards();
2795 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2796 check_added_monitors!(nodes[0], 2);
2798 if cur_time > end_time {
2804 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
2805 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
2806 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
2807 // it was last persisted.
2808 let chanmon_cfgs = create_chanmon_cfgs(2);
2809 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2810 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2811 let (persister_a, persister_b, persister_c);
2812 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
2813 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
2814 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2816 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2818 let mut nodes_0_serialized = Vec::new();
2819 if !persist_manager_with_payment {
2820 nodes_0_serialized = nodes[0].node.encode();
2823 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2825 if persist_manager_with_payment {
2826 nodes_0_serialized = nodes[0].node.encode();
2829 nodes[1].node.claim_funds(our_payment_preimage);
2830 check_added_monitors!(nodes[1], 1);
2831 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
2833 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2834 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2835 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
2836 check_added_monitors!(nodes[0], 1);
2838 // The ChannelMonitor should always be the latest version, as we're required to persist it
2839 // during the commitment signed handling.
2840 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2841 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
2843 let events = nodes[0].node.get_and_clear_pending_events();
2844 assert_eq!(events.len(), 2);
2845 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
2846 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
2847 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
2848 // the double-claim that would otherwise appear at the end of this test.
2849 nodes[0].node.timer_tick_occurred();
2850 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2851 assert_eq!(as_broadcasted_txn.len(), 1);
2853 // Ensure that, even after some time, if we restart we still include *something* in the current
2854 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
2855 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
2856 // A naive implementation of the fix here would wipe the pending payments set, causing a
2857 // failure event when we restart.
2858 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2860 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2861 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);
2862 let events = nodes[0].node.get_and_clear_pending_events();
2863 assert!(events.is_empty());
2865 // Ensure that we don't generate any further events even after the channel-closing commitment
2866 // transaction is confirmed on-chain.
2867 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
2868 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2870 let events = nodes[0].node.get_and_clear_pending_events();
2871 assert!(events.is_empty());
2873 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2874 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);
2875 let events = nodes[0].node.get_and_clear_pending_events();
2876 assert!(events.is_empty());
2877 check_added_monitors(&nodes[0], 1);
2881 fn no_missing_sent_on_midpoint_reload() {
2882 do_no_missing_sent_on_midpoint_reload(false);
2883 do_no_missing_sent_on_midpoint_reload(true);
2886 fn do_claim_from_closed_chan(fail_payment: bool) {
2887 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
2888 // received had been closed between when the HTLC was received and when we went to claim it.
2889 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
2890 // presumably the sender may retry later. Long ago it also reduced total code in the claim
2893 // However, this doesn't make sense if you're trying to do an atomic swap or some other
2894 // protocol that requires atomicity with some other action - if your money got claimed
2895 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
2896 // is an over-optimization - there should be a very, very low likelihood that a channel closes
2897 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
2898 // Since we now have code to handle this anyway we should allow it.
2900 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
2901 // CLTVs on the paths to different value resulting in a different claim deadline.
2902 let chanmon_cfgs = create_chanmon_cfgs(4);
2903 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2904 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2905 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2907 create_announced_chan_between_nodes(&nodes, 0, 1);
2908 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
2909 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
2910 create_announced_chan_between_nodes(&nodes, 2, 3);
2912 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
2913 let mut route_params = RouteParameters {
2914 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
2915 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
2916 final_value_msat: 10_000_000,
2918 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
2919 None, &nodes[0].node.compute_inflight_htlcs()).unwrap();
2920 // Make sure the route is ordered as the B->D path before C->D
2921 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
2922 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
2924 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
2925 // the HTLC is being relayed.
2926 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
2927 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
2928 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
2930 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2931 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2932 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
2933 check_added_monitors(&nodes[0], 2);
2934 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2935 send_msgs.sort_by(|a, _| {
2937 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
2938 let node_b_id = nodes[1].node.get_our_node_id();
2939 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
2942 assert_eq!(send_msgs.len(), 2);
2943 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
2944 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
2945 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
2946 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
2948 match receive_event.unwrap() {
2949 Event::PaymentClaimable { claim_deadline, .. } => {
2950 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
2955 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
2957 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
2958 - if fail_payment { 0 } else { 2 });
2960 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
2961 // and expire both immediately, though, by connecting another 4 blocks.
2962 let reason = HTLCDestination::FailedPayment { payment_hash };
2963 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
2964 connect_blocks(&nodes[3], 4);
2965 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
2966 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2968 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
2969 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false);
2970 check_closed_broadcast(&nodes[1], 1, true);
2971 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2972 assert_eq!(bs_tx.len(), 1);
2974 mine_transaction(&nodes[3], &bs_tx[0]);
2975 check_added_monitors(&nodes[3], 1);
2976 check_closed_broadcast(&nodes[3], 1, true);
2977 check_closed_event(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false);
2979 nodes[3].node.claim_funds(payment_preimage);
2980 check_added_monitors(&nodes[3], 2);
2981 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
2983 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2984 assert_eq!(ds_tx.len(), 1);
2985 check_spends!(&ds_tx[0], &bs_tx[0]);
2987 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
2988 check_added_monitors(&nodes[1], 1);
2989 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
2991 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
2992 check_added_monitors(&nodes[1], 1);
2993 assert_eq!(bs_claims.len(), 1);
2994 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
2995 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2996 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
2997 } else { panic!(); }
2999 expect_payment_sent!(nodes[0], payment_preimage);
3001 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3002 assert_eq!(ds_claim_msgs.len(), 1);
3003 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3004 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3005 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3006 check_added_monitors(&nodes[2], 1);
3007 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3008 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3010 } else { panic!(); };
3012 assert_eq!(cs_claim_msgs.len(), 1);
3013 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3014 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3015 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3016 } else { panic!(); }
3018 expect_payment_path_successful!(nodes[0]);
3023 fn claim_from_closed_chan() {
3024 do_claim_from_closed_chan(true);
3025 do_claim_from_closed_chan(false);
3028 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3029 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3030 // another results in the HTLC being rejected.
3032 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3033 // first of which we'll deliver and the second of which we'll fail and then re-send with
3034 // modified payment metadata, which will in turn result in it being failed by the recipient.
3035 let chanmon_cfgs = create_chanmon_cfgs(4);
3036 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3037 let mut config = test_default_channel_config();
3038 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3039 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3042 let new_chain_monitor;
3043 let nodes_0_deserialized;
3045 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3047 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3048 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3049 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3050 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3052 // Pay more than half of each channel's max, requiring MPP
3053 let amt_msat = 750_000_000;
3054 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3055 let payment_id = PaymentId(payment_hash.0);
3056 let payment_metadata = vec![44, 49, 52, 142];
3058 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3059 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3060 let mut route_params = RouteParameters {
3062 final_value_msat: amt_msat,
3065 // Send the MPP payment, delivering the updated commitment state to nodes[1].
3066 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3067 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata),
3068 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3069 check_added_monitors!(nodes[0], 2);
3071 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3072 assert_eq!(send_events.len(), 2);
3073 let first_send = SendEvent::from_event(send_events.pop().unwrap());
3074 let second_send = SendEvent::from_event(send_events.pop().unwrap());
3076 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3077 (&first_send, &second_send)
3079 (&second_send, &first_send)
3081 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3082 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3084 expect_pending_htlcs_forwardable!(nodes[1]);
3085 check_added_monitors(&nodes[1], 1);
3086 let b_forward_ev = SendEvent::from_node(&nodes[1]);
3087 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3088 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3090 expect_pending_htlcs_forwardable!(nodes[3]);
3092 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3093 // will result in nodes[2] failing the HTLC back.
3094 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3095 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3097 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3098 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3100 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3101 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3102 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3104 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3105 assert_eq!(payment_fail_retryable_evs.len(), 2);
3106 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3107 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3109 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3110 // stored for our payment.
3112 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3115 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3116 // the payment state.
3118 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3119 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3120 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3121 persister, new_chain_monitor, nodes_0_deserialized);
3122 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3123 reconnect_nodes(&nodes[1], &nodes[3], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3125 reconnect_nodes(&nodes[2], &nodes[3], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3127 // Create a new channel between C and D as A will refuse to retry on the existing one because
3129 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3131 // Now retry the failed HTLC.
3132 nodes[0].node.process_pending_htlc_forwards();
3133 check_added_monitors(&nodes[0], 1);
3134 let as_resend = SendEvent::from_node(&nodes[0]);
3135 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3136 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3138 expect_pending_htlcs_forwardable!(nodes[2]);
3139 check_added_monitors(&nodes[2], 1);
3140 let cs_forward = SendEvent::from_node(&nodes[2]);
3141 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3142 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3144 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3145 // the payment metadata was modified, failing only the one modified HTLC and retaining the
3148 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3149 nodes[3].node.process_pending_htlc_forwards();
3150 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3151 &[HTLCDestination::FailedPayment {payment_hash}]);
3152 nodes[3].node.process_pending_htlc_forwards();
3154 check_added_monitors(&nodes[3], 1);
3155 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3157 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3158 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3159 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3160 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3162 expect_pending_htlcs_forwardable!(nodes[3]);
3163 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3164 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3169 fn test_payment_metadata_consistency() {
3170 do_test_payment_metadata_consistency(true, true);
3171 do_test_payment_metadata_consistency(true, false);
3172 do_test_payment_metadata_consistency(false, true);
3173 do_test_payment_metadata_consistency(false, false);