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 { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
352 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
354 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
355 // error, as the channel has hit the chain.
356 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
357 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
358 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
359 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
360 assert_eq!(as_err.len(), 1);
362 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
363 assert_eq!(node_id, nodes[1].node.get_our_node_id());
364 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
365 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())) });
366 check_added_monitors!(nodes[1], 1);
367 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
369 _ => panic!("Unexpected event"),
371 check_closed_broadcast!(nodes[1], false);
373 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
374 // we close in a moment.
375 nodes[2].node.claim_funds(payment_preimage_1);
376 check_added_monitors!(nodes[2], 1);
377 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
379 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
380 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
381 check_added_monitors!(nodes[1], 1);
382 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
383 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
385 if confirm_before_reload {
386 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
387 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
390 // Create a new channel on which to retry the payment before we fail the payment via the
391 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
392 // connecting several blocks while creating the channel (implying time has passed).
393 create_announced_chan_between_nodes(&nodes, 0, 1);
394 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
396 mine_transaction(&nodes[1], &as_commitment_tx);
397 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
398 assert_eq!(bs_htlc_claim_txn.len(), 1);
399 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
401 if !confirm_before_reload {
402 mine_transaction(&nodes[0], &as_commitment_tx);
404 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
405 expect_payment_sent!(nodes[0], payment_preimage_1);
406 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
407 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
408 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
409 assert_eq!(txn.len(), 2);
410 (txn.remove(0), txn.remove(0))
412 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
413 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
414 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
415 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
417 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
419 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
420 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
422 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
423 // reloaded) via a route over the new channel, which work without issue and eventually be
424 // received and claimed at the recipient just like any other payment.
425 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
427 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
428 // and not the original fee. We also update node[1]'s relevant config as
429 // do_claim_payment_along_route expects us to never overpay.
431 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
432 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
433 .unwrap().lock().unwrap();
434 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
435 let mut new_config = channel.config();
436 new_config.forwarding_fee_base_msat += 100_000;
437 channel.update_config(&new_config);
438 new_route.paths[0].hops[0].fee_msat += 100_000;
441 // Force expiration of the channel's previous config.
442 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
443 nodes[1].node.timer_tick_occurred();
446 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
447 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
448 nodes[0].node.send_payment_with_route(&new_route, payment_hash,
449 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
450 check_added_monitors!(nodes[0], 1);
451 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
452 assert_eq!(events.len(), 1);
453 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
454 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
455 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
459 fn retry_with_no_persist() {
460 do_retry_with_no_persist(true);
461 do_retry_with_no_persist(false);
464 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
465 // Test that an off-chain completed payment is not retryable on restart. This was previously
466 // broken for dust payments, but we test for both dust and non-dust payments.
468 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
470 let chanmon_cfgs = create_chanmon_cfgs(3);
471 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
473 let mut manually_accept_config = test_default_channel_config();
474 manually_accept_config.manually_accept_inbound_channels = true;
476 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
478 let first_persister: test_utils::TestPersister;
479 let first_new_chain_monitor: test_utils::TestChainMonitor;
480 let first_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
481 let second_persister: test_utils::TestPersister;
482 let second_new_chain_monitor: test_utils::TestChainMonitor;
483 let second_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
484 let third_persister: test_utils::TestPersister;
485 let third_new_chain_monitor: test_utils::TestChainMonitor;
486 let third_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
488 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
490 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
491 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
492 confirm_transaction(&nodes[0], &funding_tx);
493 confirm_transaction(&nodes[1], &funding_tx);
494 // Ignore the announcement_signatures messages
495 nodes[0].node.get_and_clear_pending_msg_events();
496 nodes[1].node.get_and_clear_pending_msg_events();
497 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
499 // Serialize the ChannelManager prior to sending payments
500 let mut nodes_0_serialized = nodes[0].node.encode();
502 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
503 let (payment_preimage, payment_hash, payment_secret, payment_id) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], if use_dust { 1_000 } else { 1_000_000 });
505 // The ChannelMonitor should always be the latest version, as we're required to persist it
506 // during the `commitment_signed_dance!()`.
507 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
509 reload_node!(nodes[0], test_default_channel_config(), nodes_0_serialized, &[&chan_0_monitor_serialized], first_persister, first_new_chain_monitor, first_nodes_0_deserialized);
510 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
512 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
513 // force-close the channel.
514 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
515 nodes[0].node.timer_tick_occurred();
516 assert!(nodes[0].node.list_channels().is_empty());
517 assert!(nodes[0].node.has_pending_payments());
518 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
519 check_added_monitors!(nodes[0], 1);
521 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
522 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
524 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
525 // error, as the channel has hit the chain.
526 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
527 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
528 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
529 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
530 assert_eq!(as_err.len(), 1);
531 let bs_commitment_tx;
533 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
534 assert_eq!(node_id, nodes[1].node.get_our_node_id());
535 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
536 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", &nodes[1].node.get_our_node_id())) });
537 check_added_monitors!(nodes[1], 1);
538 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
540 _ => panic!("Unexpected event"),
542 check_closed_broadcast!(nodes[1], false);
544 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
545 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
546 // incoming HTLCs with the same payment hash later.
547 nodes[2].node.fail_htlc_backwards(&payment_hash);
548 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
549 check_added_monitors!(nodes[2], 1);
551 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
552 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
553 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
554 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
555 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
557 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
558 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
559 // after the commitment transaction, so always connect the commitment transaction.
560 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
561 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
563 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
564 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
565 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
566 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
567 assert_eq!(as_htlc_timeout.len(), 1);
569 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
570 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
571 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
572 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
575 // Create a new channel on which to retry the payment before we fail the payment via the
576 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
577 // connecting several blocks while creating the channel (implying time has passed).
578 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
579 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
580 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
582 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
583 // confirming, we will fail as it's considered still-pending...
584 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
585 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
586 Err(PaymentSendFailure::DuplicatePayment) => {},
587 _ => panic!("Unexpected error")
589 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
591 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
592 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
593 // (which should also still work).
594 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
595 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
596 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
598 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
599 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
600 nodes_0_serialized = nodes[0].node.encode();
602 // After the payment failed, we're free to send it again.
603 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
604 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
605 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
607 reload_node!(nodes[0], test_default_channel_config(), nodes_0_serialized, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], second_persister, second_new_chain_monitor, second_nodes_0_deserialized);
608 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
610 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
612 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
613 // the payment is not (spuriously) listed as still pending.
614 assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
615 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
616 check_added_monitors!(nodes[0], 1);
617 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
618 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
620 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
621 Err(PaymentSendFailure::DuplicatePayment) => {},
622 _ => panic!("Unexpected error")
624 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
626 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
627 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
628 nodes_0_serialized = nodes[0].node.encode();
630 // Check that after reload we can send the payment again (though we shouldn't, since it was
631 // claimed previously).
632 reload_node!(nodes[0], test_default_channel_config(), nodes_0_serialized, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], third_persister, third_new_chain_monitor, third_nodes_0_deserialized);
633 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
635 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
637 match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
638 Err(PaymentSendFailure::DuplicatePayment) => {},
639 _ => panic!("Unexpected error")
641 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
645 fn test_completed_payment_not_retryable_on_reload() {
646 do_test_completed_payment_not_retryable_on_reload(true);
647 do_test_completed_payment_not_retryable_on_reload(false);
651 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
652 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
653 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
654 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
655 // the ChannelMonitor tells it to.
657 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
658 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
659 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
660 let chanmon_cfgs = create_chanmon_cfgs(2);
661 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
662 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
663 let persister: test_utils::TestPersister;
664 let new_chain_monitor: test_utils::TestChainMonitor;
665 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
666 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
668 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
670 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
672 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
673 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
674 check_closed_broadcast!(nodes[0], true);
675 check_added_monitors!(nodes[0], 1);
676 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
678 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
679 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
681 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
682 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
683 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
684 assert_eq!(node_txn.len(), 3);
685 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
686 check_spends!(node_txn[1], funding_tx);
687 check_spends!(node_txn[2], node_txn[1]);
688 let timeout_txn = vec![node_txn[2].clone()];
690 nodes[1].node.claim_funds(payment_preimage);
691 check_added_monitors!(nodes[1], 1);
692 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
694 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[1].clone()]));
695 check_closed_broadcast!(nodes[1], true);
696 check_added_monitors!(nodes[1], 1);
697 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
698 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
699 assert_eq!(claim_txn.len(), 1);
700 check_spends!(claim_txn[0], node_txn[1]);
702 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[1].clone()]));
704 if confirm_commitment_tx {
705 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
708 let claim_block = create_dummy_block(nodes[0].best_block_hash(), 42, if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] });
711 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
712 connect_block(&nodes[0], &claim_block);
713 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
716 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
717 // returning InProgress. This should cause the claim event to never make its way to the
719 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
720 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
723 connect_blocks(&nodes[0], 1);
725 connect_block(&nodes[0], &claim_block);
728 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
729 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
730 .get_mut(&funding_txo).unwrap().drain().collect();
731 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
732 // If we're testing connection idempotency we may get substantially more.
733 assert!(mon_updates.len() >= 1);
734 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
735 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
737 // If we persist the ChannelManager here, we should get the PaymentSent event after
739 let mut chan_manager_serialized = Vec::new();
740 if !persist_manager_post_event {
741 chan_manager_serialized = nodes[0].node.encode();
744 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
745 // payment sent event.
746 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
747 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
748 for update in mon_updates {
749 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
752 expect_payment_failed!(nodes[0], payment_hash, false);
754 expect_payment_sent!(nodes[0], payment_preimage);
757 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
759 if persist_manager_post_event {
760 chan_manager_serialized = nodes[0].node.encode();
763 // Now reload nodes[0]...
764 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
766 if persist_manager_post_event {
767 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
768 } else if payment_timeout {
769 expect_payment_failed!(nodes[0], payment_hash, false);
771 expect_payment_sent!(nodes[0], payment_preimage);
774 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
775 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
776 // payment events should kick in, leaving us with no pending events here.
777 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
778 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
779 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
783 fn test_dup_htlc_onchain_fails_on_reload() {
784 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
785 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
786 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
787 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
788 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
789 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
793 fn test_fulfill_restart_failure() {
794 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
795 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
796 // again, or fail it, giving us free money.
798 // Of course probably they won't fail it and give us free money, but because we have code to
799 // handle it, we should test the logic for it anyway. We do that here.
800 let chanmon_cfgs = create_chanmon_cfgs(2);
801 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
802 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
803 let persister: test_utils::TestPersister;
804 let new_chain_monitor: test_utils::TestChainMonitor;
805 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>;
806 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
808 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
809 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
811 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
812 // pre-fulfill, which we do by serializing it here.
813 let chan_manager_serialized = nodes[1].node.encode();
814 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
816 nodes[1].node.claim_funds(payment_preimage);
817 check_added_monitors!(nodes[1], 1);
818 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
820 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
821 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
822 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
824 // Now reload nodes[1]...
825 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
827 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
828 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
830 nodes[1].node.fail_htlc_backwards(&payment_hash);
831 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
832 check_added_monitors!(nodes[1], 1);
833 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
834 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
835 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
836 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
837 // it had already considered the payment fulfilled, and now they just got free money.
838 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
842 fn get_ldk_payment_preimage() {
843 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
844 let chanmon_cfgs = create_chanmon_cfgs(2);
845 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
846 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
847 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
848 create_announced_chan_between_nodes(&nodes, 0, 1);
850 let amt_msat = 60_000;
851 let expiry_secs = 60 * 60;
852 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
854 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
855 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
856 let scorer = test_utils::TestScorer::new();
857 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
858 let random_seed_bytes = keys_manager.get_secure_random_bytes();
859 let route = get_route(
860 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
861 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
862 amt_msat, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
863 nodes[0].node.send_payment_with_route(&route, payment_hash,
864 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
865 check_added_monitors!(nodes[0], 1);
867 // Make sure to use `get_payment_preimage`
868 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
869 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
870 assert_eq!(events.len(), 1);
871 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
872 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
876 fn sent_probe_is_probe_of_sending_node() {
877 let chanmon_cfgs = create_chanmon_cfgs(3);
878 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
879 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
880 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
882 create_announced_chan_between_nodes(&nodes, 0, 1);
883 create_announced_chan_between_nodes(&nodes, 1, 2);
885 // First check we refuse to build a single-hop probe
886 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
887 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
889 // Then build an actual two-hop probing path
890 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
892 match nodes[0].node.send_probe(route.paths[0].clone()) {
893 Ok((payment_hash, payment_id)) => {
894 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
895 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
896 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
901 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
902 check_added_monitors!(nodes[0], 1);
906 fn successful_probe_yields_event() {
907 let chanmon_cfgs = create_chanmon_cfgs(3);
908 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
909 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
910 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
912 create_announced_chan_between_nodes(&nodes, 0, 1);
913 create_announced_chan_between_nodes(&nodes, 1, 2);
915 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
917 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
919 // node[0] -- update_add_htlcs -> node[1]
920 check_added_monitors!(nodes[0], 1);
921 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
922 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
923 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
924 check_added_monitors!(nodes[1], 0);
925 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
926 expect_pending_htlcs_forwardable!(nodes[1]);
928 // node[1] -- update_add_htlcs -> node[2]
929 check_added_monitors!(nodes[1], 1);
930 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
931 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
932 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
933 check_added_monitors!(nodes[2], 0);
934 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
936 // node[1] <- update_fail_htlcs -- node[2]
937 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
938 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
939 check_added_monitors!(nodes[1], 0);
940 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
942 // node[0] <- update_fail_htlcs -- node[1]
943 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
944 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
945 check_added_monitors!(nodes[0], 0);
946 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
948 let mut events = nodes[0].node.get_and_clear_pending_events();
949 assert_eq!(events.len(), 1);
950 match events.drain(..).next().unwrap() {
951 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
952 assert_eq!(payment_id, ev_pid);
953 assert_eq!(payment_hash, ev_ph);
957 assert!(!nodes[0].node.has_pending_payments());
961 fn failed_probe_yields_event() {
962 let chanmon_cfgs = create_chanmon_cfgs(3);
963 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
964 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
965 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
967 create_announced_chan_between_nodes(&nodes, 0, 1);
968 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
970 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
972 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000);
974 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
976 // node[0] -- update_add_htlcs -> node[1]
977 check_added_monitors!(nodes[0], 1);
978 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
979 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
980 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
981 check_added_monitors!(nodes[1], 0);
982 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
983 expect_pending_htlcs_forwardable!(nodes[1]);
985 // node[0] <- update_fail_htlcs -- node[1]
986 check_added_monitors!(nodes[1], 1);
987 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
988 // Skip the PendingHTLCsForwardable event
989 let _events = nodes[1].node.get_and_clear_pending_events();
990 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
991 check_added_monitors!(nodes[0], 0);
992 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
994 let mut events = nodes[0].node.get_and_clear_pending_events();
995 assert_eq!(events.len(), 1);
996 match events.drain(..).next().unwrap() {
997 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
998 assert_eq!(payment_id, ev_pid);
999 assert_eq!(payment_hash, ev_ph);
1003 assert!(!nodes[0].node.has_pending_payments());
1007 fn onchain_failed_probe_yields_event() {
1008 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1010 let chanmon_cfgs = create_chanmon_cfgs(3);
1011 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1012 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1013 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1015 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1016 create_announced_chan_between_nodes(&nodes, 1, 2);
1018 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1020 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1021 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000);
1022 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1024 // node[0] -- update_add_htlcs -> node[1]
1025 check_added_monitors!(nodes[0], 1);
1026 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1027 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1028 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1029 check_added_monitors!(nodes[1], 0);
1030 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1031 expect_pending_htlcs_forwardable!(nodes[1]);
1033 check_added_monitors!(nodes[1], 1);
1034 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1036 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1037 // Node A, which after 6 confirmations should result in a probe failure event.
1038 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1039 confirm_transaction(&nodes[0], &bs_txn[0]);
1040 check_closed_broadcast!(&nodes[0], true);
1041 check_added_monitors!(nodes[0], 1);
1043 let mut events = nodes[0].node.get_and_clear_pending_events();
1044 assert_eq!(events.len(), 2);
1045 let mut found_probe_failed = false;
1046 for event in events.drain(..) {
1048 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1049 assert_eq!(payment_id, ev_pid);
1050 assert_eq!(payment_hash, ev_ph);
1051 found_probe_failed = true;
1053 Event::ChannelClosed { .. } => {},
1057 assert!(found_probe_failed);
1058 assert!(!nodes[0].node.has_pending_payments());
1062 fn claimed_send_payment_idempotent() {
1063 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1064 let chanmon_cfgs = create_chanmon_cfgs(2);
1065 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1066 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1067 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1069 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1071 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1072 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1074 macro_rules! check_send_rejected {
1076 // If we try to resend a new payment with a different payment_hash but with the same
1077 // payment_id, it should be rejected.
1078 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1079 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1081 Err(PaymentSendFailure::DuplicatePayment) => {},
1082 _ => panic!("Unexpected send result: {:?}", send_result),
1085 // Further, if we try to send a spontaneous payment with the same payment_id it should
1086 // also be rejected.
1087 let send_result = nodes[0].node.send_spontaneous_payment(
1088 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1090 Err(PaymentSendFailure::DuplicatePayment) => {},
1091 _ => panic!("Unexpected send result: {:?}", send_result),
1096 check_send_rejected!();
1098 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1099 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1100 // we must remain just as idempotent as we were before.
1101 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1103 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1104 nodes[0].node.timer_tick_occurred();
1107 check_send_rejected!();
1109 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1110 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1111 // the payment complete. However, they could have called `send_payment` while the event was
1112 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1113 // after the event is handled a duplicate payment should sitll be rejected.
1114 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1115 check_send_rejected!();
1117 // If relatively little time has passed, a duplicate payment should still fail.
1118 nodes[0].node.timer_tick_occurred();
1119 check_send_rejected!();
1121 // However, after some time has passed (at least more than the one timer tick above), a
1122 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1123 // references to the old payment data.
1124 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1125 nodes[0].node.timer_tick_occurred();
1128 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1129 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1130 check_added_monitors!(nodes[0], 1);
1131 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1132 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1136 fn abandoned_send_payment_idempotent() {
1137 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1139 let chanmon_cfgs = create_chanmon_cfgs(2);
1140 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1141 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1142 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1144 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1146 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1147 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1149 macro_rules! check_send_rejected {
1151 // If we try to resend a new payment with a different payment_hash but with the same
1152 // payment_id, it should be rejected.
1153 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1154 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1156 Err(PaymentSendFailure::DuplicatePayment) => {},
1157 _ => panic!("Unexpected send result: {:?}", send_result),
1160 // Further, if we try to send a spontaneous payment with the same payment_id it should
1161 // also be rejected.
1162 let send_result = nodes[0].node.send_spontaneous_payment(
1163 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1165 Err(PaymentSendFailure::DuplicatePayment) => {},
1166 _ => panic!("Unexpected send result: {:?}", send_result),
1171 check_send_rejected!();
1173 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1174 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1176 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1178 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1179 nodes[0].node.timer_tick_occurred();
1181 check_send_rejected!();
1183 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1185 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1186 // failed payment back.
1187 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1188 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1189 check_added_monitors!(nodes[0], 1);
1190 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1191 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1194 #[derive(PartialEq)]
1195 enum InterceptTest {
1202 fn test_trivial_inflight_htlc_tracking(){
1203 // In this test, we test three scenarios:
1204 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1205 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1206 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1207 let chanmon_cfgs = create_chanmon_cfgs(3);
1208 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1209 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1210 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1212 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1213 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1215 // Send and claim the payment. Inflight HTLCs should be empty.
1216 let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1217 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1219 let mut node_0_per_peer_lock;
1220 let mut node_0_peer_state_lock;
1221 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1223 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1224 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1225 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1226 channel_1.get_short_channel_id().unwrap()
1228 assert_eq!(chan_1_used_liquidity, None);
1231 let mut node_1_per_peer_lock;
1232 let mut node_1_peer_state_lock;
1233 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1235 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1236 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1237 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1238 channel_2.get_short_channel_id().unwrap()
1241 assert_eq!(chan_2_used_liquidity, None);
1243 let pending_payments = nodes[0].node.list_recent_payments();
1244 assert_eq!(pending_payments.len(), 1);
1245 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1247 // Remove fulfilled payment
1248 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1249 nodes[0].node.timer_tick_occurred();
1252 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1253 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1254 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1256 let mut node_0_per_peer_lock;
1257 let mut node_0_peer_state_lock;
1258 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1260 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1261 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1262 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1263 channel_1.get_short_channel_id().unwrap()
1265 // First hop accounts for expected 1000 msat fee
1266 assert_eq!(chan_1_used_liquidity, Some(501000));
1269 let mut node_1_per_peer_lock;
1270 let mut node_1_peer_state_lock;
1271 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1273 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1274 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1275 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1276 channel_2.get_short_channel_id().unwrap()
1279 assert_eq!(chan_2_used_liquidity, Some(500000));
1281 let pending_payments = nodes[0].node.list_recent_payments();
1282 assert_eq!(pending_payments.len(), 1);
1283 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1285 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1286 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1288 // Remove fulfilled payment
1289 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1290 nodes[0].node.timer_tick_occurred();
1293 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1295 let mut node_0_per_peer_lock;
1296 let mut node_0_peer_state_lock;
1297 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1299 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1300 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1301 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1302 channel_1.get_short_channel_id().unwrap()
1304 assert_eq!(chan_1_used_liquidity, None);
1307 let mut node_1_per_peer_lock;
1308 let mut node_1_peer_state_lock;
1309 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1311 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1312 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1313 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1314 channel_2.get_short_channel_id().unwrap()
1316 assert_eq!(chan_2_used_liquidity, None);
1319 let pending_payments = nodes[0].node.list_recent_payments();
1320 assert_eq!(pending_payments.len(), 0);
1324 fn test_holding_cell_inflight_htlcs() {
1325 let chanmon_cfgs = create_chanmon_cfgs(2);
1326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1328 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1329 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1331 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1332 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1334 // Queue up two payments - one will be delivered right away, one immediately goes into the
1335 // holding cell as nodes[0] is AwaitingRAA.
1337 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1338 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1339 check_added_monitors!(nodes[0], 1);
1340 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1341 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1342 check_added_monitors!(nodes[0], 0);
1345 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1348 let mut node_0_per_peer_lock;
1349 let mut node_0_peer_state_lock;
1350 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1352 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1353 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1354 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1355 channel.get_short_channel_id().unwrap()
1358 assert_eq!(used_liquidity, Some(2000000));
1361 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1362 nodes[0].node.get_and_clear_pending_msg_events();
1366 fn intercepted_payment() {
1367 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1368 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1369 // payment or (b) fail the payment.
1370 do_test_intercepted_payment(InterceptTest::Forward);
1371 do_test_intercepted_payment(InterceptTest::Fail);
1372 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1373 do_test_intercepted_payment(InterceptTest::Timeout);
1376 fn do_test_intercepted_payment(test: InterceptTest) {
1377 let chanmon_cfgs = create_chanmon_cfgs(3);
1378 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1380 let mut zero_conf_chan_config = test_default_channel_config();
1381 zero_conf_chan_config.manually_accept_inbound_channels = true;
1382 let mut intercept_forwards_config = test_default_channel_config();
1383 intercept_forwards_config.accept_intercept_htlcs = true;
1384 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1386 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1387 let scorer = test_utils::TestScorer::new();
1388 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1390 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1392 let amt_msat = 100_000;
1393 let intercept_scid = nodes[1].node.get_intercept_scid();
1394 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1395 .with_route_hints(vec![
1396 RouteHint(vec![RouteHintHop {
1397 src_node_id: nodes[1].node.get_our_node_id(),
1398 short_channel_id: intercept_scid,
1401 proportional_millionths: 0,
1403 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1404 htlc_minimum_msat: None,
1405 htlc_maximum_msat: None,
1408 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1409 let route_params = RouteParameters {
1411 final_value_msat: amt_msat,
1413 let route = get_route(
1414 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1415 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1416 nodes[0].logger, &scorer, &(), &random_seed_bytes,
1419 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1420 nodes[0].node.send_payment_with_route(&route, payment_hash,
1421 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1422 let payment_event = {
1424 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1425 assert_eq!(added_monitors.len(), 1);
1426 added_monitors.clear();
1428 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1429 assert_eq!(events.len(), 1);
1430 SendEvent::from_event(events.remove(0))
1432 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1433 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1435 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1436 let events = nodes[1].node.get_and_clear_pending_events();
1437 assert_eq!(events.len(), 1);
1438 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1439 crate::events::Event::HTLCIntercepted {
1440 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1442 assert_eq!(pmt_hash, payment_hash);
1443 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1444 assert_eq!(short_channel_id, intercept_scid);
1445 (intercept_id, expected_outbound_amount_msat)
1450 // Check for unknown channel id error.
1451 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();
1452 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()) });
1454 if test == InterceptTest::Fail {
1455 // Ensure we can fail the intercepted payment back.
1456 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1457 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1458 nodes[1].node.process_pending_htlc_forwards();
1459 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1460 check_added_monitors!(&nodes[1], 1);
1461 assert!(update_fail.update_fail_htlcs.len() == 1);
1462 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1463 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1464 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1466 // Ensure the payment fails with the expected error.
1467 let fail_conditions = PaymentFailedConditions::new()
1468 .blamed_scid(intercept_scid)
1469 .blamed_chan_closed(true)
1470 .expected_htlc_error_data(0x4000 | 10, &[]);
1471 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1472 } else if test == InterceptTest::Forward {
1473 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1474 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1475 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();
1476 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1477 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1479 // Open the just-in-time channel so the payment can then be forwarded.
1480 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1482 // Finally, forward the intercepted payment through and claim it.
1483 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1484 expect_pending_htlcs_forwardable!(nodes[1]);
1486 let payment_event = {
1488 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1489 assert_eq!(added_monitors.len(), 1);
1490 added_monitors.clear();
1492 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1493 assert_eq!(events.len(), 1);
1494 SendEvent::from_event(events.remove(0))
1496 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1497 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1498 expect_pending_htlcs_forwardable!(nodes[2]);
1500 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1501 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1502 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1503 let events = nodes[0].node.get_and_clear_pending_events();
1504 assert_eq!(events.len(), 2);
1506 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1507 assert_eq!(payment_preimage, *ev_preimage);
1508 assert_eq!(payment_hash, *ev_hash);
1509 assert_eq!(fee_paid_msat, &Some(1000));
1511 _ => panic!("Unexpected event")
1514 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1515 assert_eq!(hash, Some(payment_hash));
1517 _ => panic!("Unexpected event")
1519 } else if test == InterceptTest::Timeout {
1520 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
1521 connect_block(&nodes[0], &block);
1522 connect_block(&nodes[1], &block);
1523 for _ in 0..TEST_FINAL_CLTV {
1524 block.header.prev_blockhash = block.block_hash();
1525 connect_block(&nodes[0], &block);
1526 connect_block(&nodes[1], &block);
1528 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1529 check_added_monitors!(nodes[1], 1);
1530 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1531 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1532 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1533 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1534 assert!(htlc_timeout_updates.update_fee.is_none());
1536 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1537 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1538 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1540 // Check for unknown intercept id error.
1541 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1542 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();
1543 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1544 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1545 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1549 #[derive(PartialEq)]
1560 fn automatic_retries() {
1561 do_automatic_retries(AutoRetry::Success);
1562 do_automatic_retries(AutoRetry::Spontaneous);
1563 do_automatic_retries(AutoRetry::FailAttempts);
1564 do_automatic_retries(AutoRetry::FailTimeout);
1565 do_automatic_retries(AutoRetry::FailOnRestart);
1566 do_automatic_retries(AutoRetry::FailOnRetry);
1568 fn do_automatic_retries(test: AutoRetry) {
1569 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1571 let chanmon_cfgs = create_chanmon_cfgs(3);
1572 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1573 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1576 let new_chain_monitor;
1577 let node_0_deserialized;
1579 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1580 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1581 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1583 // Marshall data to send the payment
1584 #[cfg(feature = "std")]
1585 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1586 #[cfg(not(feature = "std"))]
1587 let payment_expiry_secs = 60 * 60;
1588 let amt_msat = 1000;
1589 let mut invoice_features = InvoiceFeatures::empty();
1590 invoice_features.set_variable_length_onion_required();
1591 invoice_features.set_payment_secret_required();
1592 invoice_features.set_basic_mpp_optional();
1593 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1594 .with_expiry_time(payment_expiry_secs as u64)
1595 .with_bolt11_features(invoice_features).unwrap();
1596 let route_params = RouteParameters {
1598 final_value_msat: amt_msat,
1600 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1602 macro_rules! pass_failed_attempt_with_retry_along_path {
1603 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1604 // Send a payment attempt that fails due to lack of liquidity on the second hop
1605 check_added_monitors!(nodes[0], 1);
1606 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1607 let mut update_add = update_0.update_add_htlcs[0].clone();
1608 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1609 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1610 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1611 nodes[1].node.process_pending_htlc_forwards();
1612 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1613 vec![HTLCDestination::NextHopChannel {
1614 node_id: Some(nodes[2].node.get_our_node_id()),
1615 channel_id: $failing_channel_id,
1617 nodes[1].node.process_pending_htlc_forwards();
1618 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1619 check_added_monitors!(&nodes[1], 1);
1620 assert!(update_1.update_fail_htlcs.len() == 1);
1621 let fail_msg = update_1.update_fail_htlcs[0].clone();
1622 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1623 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1625 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1626 let mut events = nodes[0].node.get_and_clear_pending_events();
1627 assert_eq!(events.len(), 2);
1629 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1630 assert_eq!(payment_hash, ev_payment_hash);
1631 assert_eq!(payment_failed_permanently, false);
1633 _ => panic!("Unexpected event"),
1635 if $expect_pending_htlcs_forwardable {
1637 Event::PendingHTLCsForwardable { .. } => {},
1638 _ => panic!("Unexpected event"),
1642 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1643 assert_eq!(payment_hash, ev_payment_hash);
1645 _ => panic!("Unexpected event"),
1651 if test == AutoRetry::Success {
1652 // Test that we can succeed on the first retry.
1653 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1654 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1655 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1657 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1658 // attempt, since the initial second hop channel will be excluded from pathfinding
1659 create_announced_chan_between_nodes(&nodes, 1, 2);
1661 // We retry payments in `process_pending_htlc_forwards`
1662 nodes[0].node.process_pending_htlc_forwards();
1663 check_added_monitors!(nodes[0], 1);
1664 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1665 assert_eq!(msg_events.len(), 1);
1666 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1667 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1668 } else if test == AutoRetry::Spontaneous {
1669 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
1670 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
1671 Retry::Attempts(1)).unwrap();
1672 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1674 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1675 // attempt, since the initial second hop channel will be excluded from pathfinding
1676 create_announced_chan_between_nodes(&nodes, 1, 2);
1678 // We retry payments in `process_pending_htlc_forwards`
1679 nodes[0].node.process_pending_htlc_forwards();
1680 check_added_monitors!(nodes[0], 1);
1681 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1682 assert_eq!(msg_events.len(), 1);
1683 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1684 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1685 } else if test == AutoRetry::FailAttempts {
1686 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1687 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1688 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1689 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1691 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1692 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1693 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1695 // We retry payments in `process_pending_htlc_forwards`
1696 nodes[0].node.process_pending_htlc_forwards();
1697 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1699 // Ensure we won't retry a second time.
1700 nodes[0].node.process_pending_htlc_forwards();
1701 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1702 assert_eq!(msg_events.len(), 0);
1703 } else if test == AutoRetry::FailTimeout {
1704 #[cfg(not(feature = "no-std"))] {
1705 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1706 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1707 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
1708 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1710 // Advance the time so the second attempt fails due to timeout.
1711 SinceEpoch::advance(Duration::from_secs(61));
1713 // Make sure we don't retry again.
1714 nodes[0].node.process_pending_htlc_forwards();
1715 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1716 assert_eq!(msg_events.len(), 0);
1718 let mut events = nodes[0].node.get_and_clear_pending_events();
1719 assert_eq!(events.len(), 1);
1721 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1722 assert_eq!(payment_hash, *ev_payment_hash);
1723 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1724 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
1726 _ => panic!("Unexpected event"),
1729 } else if test == AutoRetry::FailOnRestart {
1730 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1731 // attempts remaining prior to restart.
1732 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1733 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1734 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1736 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1737 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1738 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1740 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1741 nodes[0].node.process_pending_htlc_forwards();
1742 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1744 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1745 let node_encoded = nodes[0].node.encode();
1746 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1747 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1749 let mut events = nodes[0].node.get_and_clear_pending_events();
1750 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
1751 // Make sure we don't retry again.
1752 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1753 assert_eq!(msg_events.len(), 0);
1755 let mut events = nodes[0].node.get_and_clear_pending_events();
1756 assert_eq!(events.len(), 1);
1758 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1759 assert_eq!(payment_hash, *ev_payment_hash);
1760 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1761 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
1763 _ => panic!("Unexpected event"),
1765 } else if test == AutoRetry::FailOnRetry {
1766 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1767 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1768 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1770 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1771 // fail to find a route.
1772 nodes[0].node.process_pending_htlc_forwards();
1773 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1774 assert_eq!(msg_events.len(), 0);
1776 let mut events = nodes[0].node.get_and_clear_pending_events();
1777 assert_eq!(events.len(), 1);
1779 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1780 assert_eq!(payment_hash, *ev_payment_hash);
1781 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1782 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
1784 _ => panic!("Unexpected event"),
1790 fn auto_retry_partial_failure() {
1791 // Test that we'll retry appropriately on send partial failure and retry partial failure.
1792 let chanmon_cfgs = create_chanmon_cfgs(2);
1793 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1794 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1795 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1797 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1798 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1799 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1801 // Marshall data to send the payment
1802 let amt_msat = 20_000;
1803 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1804 #[cfg(feature = "std")]
1805 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1806 #[cfg(not(feature = "std"))]
1807 let payment_expiry_secs = 60 * 60;
1808 let mut invoice_features = InvoiceFeatures::empty();
1809 invoice_features.set_variable_length_onion_required();
1810 invoice_features.set_payment_secret_required();
1811 invoice_features.set_basic_mpp_optional();
1812 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1813 .with_expiry_time(payment_expiry_secs as u64)
1814 .with_bolt11_features(invoice_features).unwrap();
1815 let route_params = RouteParameters {
1817 final_value_msat: amt_msat,
1820 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1821 // second (for the initial send path2 over chan_2) fails.
1822 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1823 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1824 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1825 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1826 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1827 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1828 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1830 // Configure the initial send, retry1 and retry2's paths.
1831 let send_route = Route {
1833 Path { hops: vec![RouteHop {
1834 pubkey: nodes[1].node.get_our_node_id(),
1835 node_features: nodes[1].node.node_features(),
1836 short_channel_id: chan_1_id,
1837 channel_features: nodes[1].node.channel_features(),
1838 fee_msat: amt_msat / 2,
1839 cltv_expiry_delta: 100,
1840 }], blinded_tail: None },
1841 Path { hops: vec![RouteHop {
1842 pubkey: nodes[1].node.get_our_node_id(),
1843 node_features: nodes[1].node.node_features(),
1844 short_channel_id: chan_2_id,
1845 channel_features: nodes[1].node.channel_features(),
1846 fee_msat: amt_msat / 2,
1847 cltv_expiry_delta: 100,
1848 }], blinded_tail: None },
1850 payment_params: Some(route_params.payment_params.clone()),
1852 let retry_1_route = Route {
1854 Path { hops: vec![RouteHop {
1855 pubkey: nodes[1].node.get_our_node_id(),
1856 node_features: nodes[1].node.node_features(),
1857 short_channel_id: chan_1_id,
1858 channel_features: nodes[1].node.channel_features(),
1859 fee_msat: amt_msat / 4,
1860 cltv_expiry_delta: 100,
1861 }], blinded_tail: None },
1862 Path { hops: vec![RouteHop {
1863 pubkey: nodes[1].node.get_our_node_id(),
1864 node_features: nodes[1].node.node_features(),
1865 short_channel_id: chan_3_id,
1866 channel_features: nodes[1].node.channel_features(),
1867 fee_msat: amt_msat / 4,
1868 cltv_expiry_delta: 100,
1869 }], blinded_tail: None },
1871 payment_params: Some(route_params.payment_params.clone()),
1873 let retry_2_route = Route {
1875 Path { hops: vec![RouteHop {
1876 pubkey: nodes[1].node.get_our_node_id(),
1877 node_features: nodes[1].node.node_features(),
1878 short_channel_id: chan_1_id,
1879 channel_features: nodes[1].node.channel_features(),
1880 fee_msat: amt_msat / 4,
1881 cltv_expiry_delta: 100,
1882 }], blinded_tail: None },
1884 payment_params: Some(route_params.payment_params.clone()),
1886 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1887 let mut payment_params = route_params.payment_params.clone();
1888 payment_params.previously_failed_channels.push(chan_2_id);
1889 nodes[0].router.expect_find_route(RouteParameters {
1890 payment_params, final_value_msat: amt_msat / 2,
1891 }, Ok(retry_1_route));
1892 let mut payment_params = route_params.payment_params.clone();
1893 payment_params.previously_failed_channels.push(chan_3_id);
1894 nodes[0].router.expect_find_route(RouteParameters {
1895 payment_params, final_value_msat: amt_msat / 4,
1896 }, Ok(retry_2_route));
1898 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1899 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1900 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1901 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1902 assert_eq!(closed_chan_events.len(), 4);
1903 match closed_chan_events[0] {
1904 Event::ChannelClosed { .. } => {},
1905 _ => panic!("Unexpected event"),
1907 match closed_chan_events[1] {
1908 Event::PaymentPathFailed { .. } => {},
1909 _ => panic!("Unexpected event"),
1911 match closed_chan_events[2] {
1912 Event::ChannelClosed { .. } => {},
1913 _ => panic!("Unexpected event"),
1915 match closed_chan_events[3] {
1916 Event::PaymentPathFailed { .. } => {},
1917 _ => panic!("Unexpected event"),
1920 // Pass the first part of the payment along the path.
1921 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1922 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1924 // First message is the first update_add, remaining messages are broadcasting channel updates and
1925 // errors for the permfailed channels
1926 assert_eq!(msg_events.len(), 5);
1927 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1929 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1930 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1931 check_added_monitors!(nodes[1], 1);
1932 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1934 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1935 check_added_monitors!(nodes[0], 1);
1936 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1938 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1939 check_added_monitors!(nodes[0], 1);
1940 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1942 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1943 check_added_monitors!(nodes[1], 1);
1945 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1946 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1947 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1948 check_added_monitors!(nodes[1], 1);
1949 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1951 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1952 check_added_monitors!(nodes[0], 1);
1954 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
1955 check_added_monitors!(nodes[0], 1);
1956 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1958 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1959 check_added_monitors!(nodes[1], 1);
1961 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1962 nodes[1].node.process_pending_htlc_forwards();
1963 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
1964 nodes[1].node.claim_funds(payment_preimage);
1965 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
1966 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1967 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
1969 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
1970 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
1971 check_added_monitors!(nodes[0], 1);
1972 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1974 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1975 check_added_monitors!(nodes[1], 4);
1976 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1978 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1979 check_added_monitors!(nodes[1], 1);
1980 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1982 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1983 check_added_monitors!(nodes[0], 1);
1985 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
1986 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
1987 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
1988 check_added_monitors!(nodes[0], 1);
1989 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1991 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
1992 check_added_monitors!(nodes[1], 1);
1994 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1995 check_added_monitors!(nodes[1], 1);
1996 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1998 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1999 check_added_monitors!(nodes[0], 1);
2000 expect_payment_sent!(nodes[0], payment_preimage);
2004 fn auto_retry_zero_attempts_send_error() {
2005 let chanmon_cfgs = create_chanmon_cfgs(2);
2006 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2007 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2008 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2010 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2011 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2013 // Marshall data to send the payment
2014 let amt_msat = 20_000;
2015 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2016 #[cfg(feature = "std")]
2017 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2018 #[cfg(not(feature = "std"))]
2019 let payment_expiry_secs = 60 * 60;
2020 let mut invoice_features = InvoiceFeatures::empty();
2021 invoice_features.set_variable_length_onion_required();
2022 invoice_features.set_payment_secret_required();
2023 invoice_features.set_basic_mpp_optional();
2024 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2025 .with_expiry_time(payment_expiry_secs as u64)
2026 .with_bolt11_features(invoice_features).unwrap();
2027 let route_params = RouteParameters {
2029 final_value_msat: amt_msat,
2032 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2033 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2034 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2035 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2036 let events = nodes[0].node.get_and_clear_pending_events();
2037 assert_eq!(events.len(), 3);
2038 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2039 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2040 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2041 check_added_monitors!(nodes[0], 2);
2045 fn fails_paying_after_rejected_by_payee() {
2046 let chanmon_cfgs = create_chanmon_cfgs(2);
2047 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2048 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2049 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2051 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2053 // Marshall data to send the payment
2054 let amt_msat = 20_000;
2055 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2056 #[cfg(feature = "std")]
2057 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2058 #[cfg(not(feature = "std"))]
2059 let payment_expiry_secs = 60 * 60;
2060 let mut invoice_features = InvoiceFeatures::empty();
2061 invoice_features.set_variable_length_onion_required();
2062 invoice_features.set_payment_secret_required();
2063 invoice_features.set_basic_mpp_optional();
2064 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2065 .with_expiry_time(payment_expiry_secs as u64)
2066 .with_bolt11_features(invoice_features).unwrap();
2067 let route_params = RouteParameters {
2069 final_value_msat: amt_msat,
2072 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2073 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2074 check_added_monitors!(nodes[0], 1);
2075 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2076 assert_eq!(events.len(), 1);
2077 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2078 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2079 check_added_monitors!(nodes[1], 0);
2080 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2081 expect_pending_htlcs_forwardable!(nodes[1]);
2082 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2084 nodes[1].node.fail_htlc_backwards(&payment_hash);
2085 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2086 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2090 fn retry_multi_path_single_failed_payment() {
2091 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2092 let chanmon_cfgs = create_chanmon_cfgs(2);
2093 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2094 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2095 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2097 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2098 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2100 let amt_msat = 100_010_000;
2102 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2103 #[cfg(feature = "std")]
2104 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2105 #[cfg(not(feature = "std"))]
2106 let payment_expiry_secs = 60 * 60;
2107 let mut invoice_features = InvoiceFeatures::empty();
2108 invoice_features.set_variable_length_onion_required();
2109 invoice_features.set_payment_secret_required();
2110 invoice_features.set_basic_mpp_optional();
2111 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2112 .with_expiry_time(payment_expiry_secs as u64)
2113 .with_bolt11_features(invoice_features).unwrap();
2114 let route_params = RouteParameters {
2115 payment_params: payment_params.clone(),
2116 final_value_msat: amt_msat,
2119 let chans = nodes[0].node.list_usable_channels();
2120 let mut route = Route {
2122 Path { hops: vec![RouteHop {
2123 pubkey: nodes[1].node.get_our_node_id(),
2124 node_features: nodes[1].node.node_features(),
2125 short_channel_id: chans[0].short_channel_id.unwrap(),
2126 channel_features: nodes[1].node.channel_features(),
2128 cltv_expiry_delta: 100,
2129 }], blinded_tail: None },
2130 Path { hops: vec![RouteHop {
2131 pubkey: nodes[1].node.get_our_node_id(),
2132 node_features: nodes[1].node.node_features(),
2133 short_channel_id: chans[1].short_channel_id.unwrap(),
2134 channel_features: nodes[1].node.channel_features(),
2135 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2136 cltv_expiry_delta: 100,
2137 }], blinded_tail: None },
2139 payment_params: Some(payment_params),
2141 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2142 // On retry, split the payment across both channels.
2143 route.paths[0].hops[0].fee_msat = 50_000_001;
2144 route.paths[1].hops[0].fee_msat = 50_000_000;
2145 let mut pay_params = route.payment_params.clone().unwrap();
2146 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2147 nodes[0].router.expect_find_route(RouteParameters {
2148 payment_params: pay_params,
2149 // Note that the second request here requests the amount we originally failed to send,
2150 // not the amount remaining on the full payment, which should be changed.
2151 final_value_msat: 100_000_001,
2152 }, Ok(route.clone()));
2155 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2156 // The initial send attempt, 2 paths
2157 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2158 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2159 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2160 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2161 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2164 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2165 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2166 let events = nodes[0].node.get_and_clear_pending_events();
2167 assert_eq!(events.len(), 1);
2169 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2170 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2171 short_channel_id: Some(expected_scid), .. } =>
2173 assert_eq!(payment_hash, ev_payment_hash);
2174 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2176 _ => panic!("Unexpected event"),
2178 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2179 assert_eq!(htlc_msgs.len(), 2);
2180 check_added_monitors!(nodes[0], 2);
2184 fn immediate_retry_on_failure() {
2185 // Tests that we can/will retry immediately after a failure
2186 let chanmon_cfgs = create_chanmon_cfgs(2);
2187 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2188 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2189 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2191 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2192 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2194 let amt_msat = 100_000_001;
2195 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2196 #[cfg(feature = "std")]
2197 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2198 #[cfg(not(feature = "std"))]
2199 let payment_expiry_secs = 60 * 60;
2200 let mut invoice_features = InvoiceFeatures::empty();
2201 invoice_features.set_variable_length_onion_required();
2202 invoice_features.set_payment_secret_required();
2203 invoice_features.set_basic_mpp_optional();
2204 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2205 .with_expiry_time(payment_expiry_secs as u64)
2206 .with_bolt11_features(invoice_features).unwrap();
2207 let route_params = RouteParameters {
2209 final_value_msat: amt_msat,
2212 let chans = nodes[0].node.list_usable_channels();
2213 let mut route = Route {
2215 Path { hops: vec![RouteHop {
2216 pubkey: nodes[1].node.get_our_node_id(),
2217 node_features: nodes[1].node.node_features(),
2218 short_channel_id: chans[0].short_channel_id.unwrap(),
2219 channel_features: nodes[1].node.channel_features(),
2220 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2221 cltv_expiry_delta: 100,
2222 }], blinded_tail: None },
2224 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2226 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2227 // On retry, split the payment across both channels.
2228 route.paths.push(route.paths[0].clone());
2229 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2230 route.paths[0].hops[0].fee_msat = 50_000_000;
2231 route.paths[1].hops[0].fee_msat = 50_000_001;
2232 let mut pay_params = route_params.payment_params.clone();
2233 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2234 nodes[0].router.expect_find_route(RouteParameters {
2235 payment_params: pay_params, final_value_msat: amt_msat,
2236 }, Ok(route.clone()));
2238 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2239 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2240 let events = nodes[0].node.get_and_clear_pending_events();
2241 assert_eq!(events.len(), 1);
2243 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2244 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }},
2245 short_channel_id: Some(expected_scid), .. } =>
2247 assert_eq!(payment_hash, ev_payment_hash);
2248 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2250 _ => panic!("Unexpected event"),
2252 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2253 assert_eq!(htlc_msgs.len(), 2);
2254 check_added_monitors!(nodes[0], 2);
2258 fn no_extra_retries_on_back_to_back_fail() {
2259 // In a previous release, we had a race where we may exceed the payment retry count if we
2260 // get two failures in a row with the second indicating that all paths had failed (this field,
2261 // `all_paths_failed`, has since been removed).
2262 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2263 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2264 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2265 // pending which we will see later. Thus, when we previously removed the retry tracking map
2266 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2267 // retry entry even though more events for the same payment were still pending. This led to
2268 // us retrying a payment again even though we'd already given up on it.
2270 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2271 // is used to remove the payment retry counter entries instead. This tests for the specific
2272 // excess-retry case while also testing `PaymentFailed` generation.
2274 let chanmon_cfgs = create_chanmon_cfgs(3);
2275 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2276 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2277 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2279 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2280 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2282 let amt_msat = 200_000_000;
2283 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2284 #[cfg(feature = "std")]
2285 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2286 #[cfg(not(feature = "std"))]
2287 let payment_expiry_secs = 60 * 60;
2288 let mut invoice_features = InvoiceFeatures::empty();
2289 invoice_features.set_variable_length_onion_required();
2290 invoice_features.set_payment_secret_required();
2291 invoice_features.set_basic_mpp_optional();
2292 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2293 .with_expiry_time(payment_expiry_secs as u64)
2294 .with_bolt11_features(invoice_features).unwrap();
2295 let route_params = RouteParameters {
2297 final_value_msat: amt_msat,
2300 let mut route = Route {
2302 Path { hops: vec![RouteHop {
2303 pubkey: nodes[1].node.get_our_node_id(),
2304 node_features: nodes[1].node.node_features(),
2305 short_channel_id: chan_1_scid,
2306 channel_features: nodes[1].node.channel_features(),
2307 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2308 cltv_expiry_delta: 100,
2310 pubkey: nodes[2].node.get_our_node_id(),
2311 node_features: nodes[2].node.node_features(),
2312 short_channel_id: chan_2_scid,
2313 channel_features: nodes[2].node.channel_features(),
2314 fee_msat: 100_000_000,
2315 cltv_expiry_delta: 100,
2316 }], blinded_tail: None },
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 }
2333 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2335 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2336 let mut second_payment_params = route_params.payment_params.clone();
2337 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2338 // On retry, we'll only return one path
2339 route.paths.remove(1);
2340 route.paths[0].hops[1].fee_msat = amt_msat;
2341 nodes[0].router.expect_find_route(RouteParameters {
2342 payment_params: second_payment_params,
2343 final_value_msat: amt_msat,
2344 }, Ok(route.clone()));
2346 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2347 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2348 let htlc_updates = SendEvent::from_node(&nodes[0]);
2349 check_added_monitors!(nodes[0], 1);
2350 assert_eq!(htlc_updates.msgs.len(), 1);
2352 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2353 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2354 check_added_monitors!(nodes[1], 1);
2355 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2357 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2358 check_added_monitors!(nodes[0], 1);
2359 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2361 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2362 check_added_monitors!(nodes[0], 1);
2363 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2365 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2366 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2367 check_added_monitors!(nodes[1], 1);
2368 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2370 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2371 check_added_monitors!(nodes[1], 1);
2372 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2374 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2375 check_added_monitors!(nodes[0], 1);
2377 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2378 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2379 check_added_monitors!(nodes[0], 1);
2380 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2382 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2383 check_added_monitors!(nodes[1], 1);
2384 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2386 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2387 check_added_monitors!(nodes[1], 1);
2388 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2390 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2391 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2392 check_added_monitors!(nodes[0], 1);
2394 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2395 check_added_monitors!(nodes[0], 1);
2396 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2398 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2399 check_added_monitors!(nodes[1], 1);
2400 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2401 check_added_monitors!(nodes[1], 1);
2402 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2404 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2405 check_added_monitors!(nodes[0], 1);
2407 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2408 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2411 // Previously, we retried payments in an event consumer, which would retry each
2412 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2413 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2414 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2415 // by adding the `PaymentFailed` event.
2417 // Because we now retry payments as a batch, we simply return a single-path route in the
2418 // second, batched, request, have that fail, ensure the payment was abandoned.
2419 let mut events = nodes[0].node.get_and_clear_pending_events();
2420 assert_eq!(events.len(), 3);
2422 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2423 assert_eq!(payment_hash, ev_payment_hash);
2424 assert_eq!(payment_failed_permanently, false);
2426 _ => panic!("Unexpected event"),
2429 Event::PendingHTLCsForwardable { .. } => {},
2430 _ => panic!("Unexpected event"),
2433 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2434 assert_eq!(payment_hash, ev_payment_hash);
2435 assert_eq!(payment_failed_permanently, false);
2437 _ => panic!("Unexpected event"),
2440 nodes[0].node.process_pending_htlc_forwards();
2441 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2442 check_added_monitors!(nodes[0], 1);
2444 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2445 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2446 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2447 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2448 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2450 let mut events = nodes[0].node.get_and_clear_pending_events();
2451 assert_eq!(events.len(), 2);
2453 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2454 assert_eq!(payment_hash, ev_payment_hash);
2455 assert_eq!(payment_failed_permanently, false);
2457 _ => panic!("Unexpected event"),
2460 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2461 assert_eq!(payment_hash, *ev_payment_hash);
2462 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2463 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2465 _ => panic!("Unexpected event"),
2470 fn test_simple_partial_retry() {
2471 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2472 // full amount of the payment, rather than only the missing amount. Here we simply test for
2473 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2474 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2476 let chanmon_cfgs = create_chanmon_cfgs(3);
2477 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2478 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2479 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2481 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2482 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2484 let amt_msat = 200_000_000;
2485 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2486 #[cfg(feature = "std")]
2487 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2488 #[cfg(not(feature = "std"))]
2489 let payment_expiry_secs = 60 * 60;
2490 let mut invoice_features = InvoiceFeatures::empty();
2491 invoice_features.set_variable_length_onion_required();
2492 invoice_features.set_payment_secret_required();
2493 invoice_features.set_basic_mpp_optional();
2494 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2495 .with_expiry_time(payment_expiry_secs as u64)
2496 .with_bolt11_features(invoice_features).unwrap();
2497 let route_params = RouteParameters {
2499 final_value_msat: amt_msat,
2502 let mut route = Route {
2504 Path { hops: vec![RouteHop {
2505 pubkey: nodes[1].node.get_our_node_id(),
2506 node_features: nodes[1].node.node_features(),
2507 short_channel_id: chan_1_scid,
2508 channel_features: nodes[1].node.channel_features(),
2509 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2510 cltv_expiry_delta: 100,
2512 pubkey: nodes[2].node.get_our_node_id(),
2513 node_features: nodes[2].node.node_features(),
2514 short_channel_id: chan_2_scid,
2515 channel_features: nodes[2].node.channel_features(),
2516 fee_msat: 100_000_000,
2517 cltv_expiry_delta: 100,
2518 }], blinded_tail: None },
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(),
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 }
2535 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2537 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2538 let mut second_payment_params = route_params.payment_params.clone();
2539 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2540 // On retry, we'll only be asked for one path (or 100k sats)
2541 route.paths.remove(0);
2542 nodes[0].router.expect_find_route(RouteParameters {
2543 payment_params: second_payment_params,
2544 final_value_msat: amt_msat / 2,
2545 }, Ok(route.clone()));
2547 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2548 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2549 let htlc_updates = SendEvent::from_node(&nodes[0]);
2550 check_added_monitors!(nodes[0], 1);
2551 assert_eq!(htlc_updates.msgs.len(), 1);
2553 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2554 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2555 check_added_monitors!(nodes[1], 1);
2556 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2558 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2559 check_added_monitors!(nodes[0], 1);
2560 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2562 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2563 check_added_monitors!(nodes[0], 1);
2564 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2566 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2567 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2568 check_added_monitors!(nodes[1], 1);
2569 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2571 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2572 check_added_monitors!(nodes[1], 1);
2573 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2575 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2576 check_added_monitors!(nodes[0], 1);
2578 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2579 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2580 check_added_monitors!(nodes[0], 1);
2581 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2583 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2584 check_added_monitors!(nodes[1], 1);
2586 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2587 check_added_monitors!(nodes[1], 1);
2589 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2591 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2592 check_added_monitors!(nodes[0], 1);
2594 let mut events = nodes[0].node.get_and_clear_pending_events();
2595 assert_eq!(events.len(), 2);
2597 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2598 assert_eq!(payment_hash, ev_payment_hash);
2599 assert_eq!(payment_failed_permanently, false);
2601 _ => panic!("Unexpected event"),
2604 Event::PendingHTLCsForwardable { .. } => {},
2605 _ => panic!("Unexpected event"),
2608 nodes[0].node.process_pending_htlc_forwards();
2609 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2610 check_added_monitors!(nodes[0], 1);
2612 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2613 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2615 expect_pending_htlcs_forwardable!(nodes[1]);
2616 check_added_monitors!(nodes[1], 1);
2618 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2619 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2620 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2621 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2623 expect_pending_htlcs_forwardable!(nodes[2]);
2624 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2628 #[cfg(feature = "std")]
2629 fn test_threaded_payment_retries() {
2630 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2631 // a single thread and would happily let multiple threads run retries at the same time. Because
2632 // retries are done by first calculating the amount we need to retry, then dropping the
2633 // relevant lock, then actually sending, we would happily let multiple threads retry the same
2634 // amount at the same time, overpaying our original HTLC!
2635 let chanmon_cfgs = create_chanmon_cfgs(4);
2636 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2637 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2638 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2640 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2641 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2642 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2643 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2645 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2646 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2647 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2648 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2650 let amt_msat = 100_000_000;
2651 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2652 #[cfg(feature = "std")]
2653 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2654 #[cfg(not(feature = "std"))]
2655 let payment_expiry_secs = 60 * 60;
2656 let mut invoice_features = InvoiceFeatures::empty();
2657 invoice_features.set_variable_length_onion_required();
2658 invoice_features.set_payment_secret_required();
2659 invoice_features.set_basic_mpp_optional();
2660 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2661 .with_expiry_time(payment_expiry_secs as u64)
2662 .with_bolt11_features(invoice_features).unwrap();
2663 let mut route_params = RouteParameters {
2665 final_value_msat: amt_msat,
2668 let mut route = Route {
2670 Path { hops: vec![RouteHop {
2671 pubkey: nodes[1].node.get_our_node_id(),
2672 node_features: nodes[1].node.node_features(),
2673 short_channel_id: chan_1_scid,
2674 channel_features: nodes[1].node.channel_features(),
2676 cltv_expiry_delta: 100,
2678 pubkey: nodes[3].node.get_our_node_id(),
2679 node_features: nodes[2].node.node_features(),
2680 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2681 channel_features: nodes[2].node.channel_features(),
2682 fee_msat: amt_msat / 1000,
2683 cltv_expiry_delta: 100,
2684 }], blinded_tail: None },
2685 Path { hops: vec![RouteHop {
2686 pubkey: nodes[2].node.get_our_node_id(),
2687 node_features: nodes[2].node.node_features(),
2688 short_channel_id: chan_3_scid,
2689 channel_features: nodes[2].node.channel_features(),
2691 cltv_expiry_delta: 100,
2693 pubkey: nodes[3].node.get_our_node_id(),
2694 node_features: nodes[3].node.node_features(),
2695 short_channel_id: chan_4_scid,
2696 channel_features: nodes[3].node.channel_features(),
2697 fee_msat: amt_msat - amt_msat / 1000,
2698 cltv_expiry_delta: 100,
2699 }], blinded_tail: None }
2701 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2703 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2705 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2706 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
2707 check_added_monitors!(nodes[0], 2);
2708 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2709 assert_eq!(send_msg_events.len(), 2);
2710 send_msg_events.retain(|msg|
2711 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
2712 // Drop the commitment update for nodes[2], we can just let that one sit pending
2714 *node_id == nodes[1].node.get_our_node_id()
2715 } else { panic!(); }
2718 // from here on out, the retry `RouteParameters` amount will be amt/1000
2719 route_params.final_value_msat /= 1000;
2722 let end_time = Instant::now() + Duration::from_secs(1);
2723 macro_rules! thread_body { () => { {
2724 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
2725 let node_ref = NodePtr::from_node(&nodes[0]);
2727 let node_a = unsafe { &*node_ref.0 };
2728 while Instant::now() < end_time {
2729 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2730 // Ignore if we have any pending events, just always pretend we just got a
2731 // PendingHTLCsForwardable
2732 node_a.node.process_pending_htlc_forwards();
2736 let mut threads = Vec::new();
2737 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
2739 // Back in the main thread, poll pending messages and make sure that we never have more than
2740 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
2741 // there are HTLC messages shoved in while its running. This allows us to test that we never
2742 // generate an additional update_add_htlc until we've fully failed the first.
2743 let mut previously_failed_channels = Vec::new();
2745 assert_eq!(send_msg_events.len(), 1);
2746 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
2747 assert_eq!(send_event.msgs.len(), 1);
2749 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
2750 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
2752 // Note that we only push one route into `expect_find_route` at a time, because that's all
2753 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
2754 // we should still ultimately fail for the same reason - because we're trying to send too
2755 // many HTLCs at once.
2756 let mut new_route_params = route_params.clone();
2757 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
2758 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
2759 route.paths[0].hops[1].short_channel_id += 1;
2760 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
2762 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2763 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
2764 // The "normal" commitment_signed_dance delivers the final RAA and then calls
2765 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
2766 // This races with our other threads which may generate an add-HTLCs commitment update via
2767 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
2768 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
2769 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
2770 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
2772 let cur_time = Instant::now();
2773 if cur_time > end_time {
2774 for thread in threads.drain(..) { thread.join().unwrap(); }
2777 // Make sure we have some events to handle when we go around...
2778 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2779 nodes[0].node.process_pending_htlc_forwards();
2780 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2781 check_added_monitors!(nodes[0], 2);
2783 if cur_time > end_time {
2789 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
2790 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
2791 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
2792 // it was last persisted.
2793 let chanmon_cfgs = create_chanmon_cfgs(2);
2794 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2795 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2796 let (persister_a, persister_b, persister_c);
2797 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
2798 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
2799 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2801 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2803 let mut nodes_0_serialized = Vec::new();
2804 if !persist_manager_with_payment {
2805 nodes_0_serialized = nodes[0].node.encode();
2808 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2810 if persist_manager_with_payment {
2811 nodes_0_serialized = nodes[0].node.encode();
2814 nodes[1].node.claim_funds(our_payment_preimage);
2815 check_added_monitors!(nodes[1], 1);
2816 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
2818 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2819 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2820 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
2821 check_added_monitors!(nodes[0], 1);
2823 // The ChannelMonitor should always be the latest version, as we're required to persist it
2824 // during the commitment signed handling.
2825 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2826 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
2828 let events = nodes[0].node.get_and_clear_pending_events();
2829 assert_eq!(events.len(), 2);
2830 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
2831 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
2832 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
2833 // the double-claim that would otherwise appear at the end of this test.
2834 nodes[0].node.timer_tick_occurred();
2835 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2836 assert_eq!(as_broadcasted_txn.len(), 1);
2838 // Ensure that, even after some time, if we restart we still include *something* in the current
2839 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
2840 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
2841 // A naive implementation of the fix here would wipe the pending payments set, causing a
2842 // failure event when we restart.
2843 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2845 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2846 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);
2847 let events = nodes[0].node.get_and_clear_pending_events();
2848 assert!(events.is_empty());
2850 // Ensure that we don't generate any further events even after the channel-closing commitment
2851 // transaction is confirmed on-chain.
2852 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
2853 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2855 let events = nodes[0].node.get_and_clear_pending_events();
2856 assert!(events.is_empty());
2858 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2859 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);
2860 let events = nodes[0].node.get_and_clear_pending_events();
2861 assert!(events.is_empty());
2865 fn no_missing_sent_on_midpoint_reload() {
2866 do_no_missing_sent_on_midpoint_reload(false);
2867 do_no_missing_sent_on_midpoint_reload(true);
2870 fn do_claim_from_closed_chan(fail_payment: bool) {
2871 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
2872 // received had been closed between when the HTLC was received and when we went to claim it.
2873 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
2874 // presumably the sender may retry later. Long ago it also reduced total code in the claim
2877 // However, this doesn't make sense if you're trying to do an atomic swap or some other
2878 // protocol that requires atomicity with some other action - if your money got claimed
2879 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
2880 // is an over-optimization - there should be a very, very low likelihood that a channel closes
2881 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
2882 // Since we now have code to handle this anyway we should allow it.
2884 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
2885 // CLTVs on the paths to different value resulting in a different claim deadline.
2886 let chanmon_cfgs = create_chanmon_cfgs(4);
2887 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2888 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2889 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2891 create_announced_chan_between_nodes(&nodes, 0, 1);
2892 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
2893 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
2894 create_announced_chan_between_nodes(&nodes, 2, 3);
2896 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
2897 let mut route_params = RouteParameters {
2898 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
2899 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
2900 final_value_msat: 10_000_000,
2902 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
2903 None, &nodes[0].node.compute_inflight_htlcs()).unwrap();
2904 // Make sure the route is ordered as the B->D path before C->D
2905 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
2906 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
2908 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
2909 // the HTLC is being relayed.
2910 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
2911 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
2912 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
2914 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2915 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2916 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
2917 check_added_monitors(&nodes[0], 2);
2918 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2919 send_msgs.sort_by(|a, _| {
2921 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
2922 let node_b_id = nodes[1].node.get_our_node_id();
2923 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
2926 assert_eq!(send_msgs.len(), 2);
2927 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
2928 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
2929 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
2930 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
2932 match receive_event.unwrap() {
2933 Event::PaymentClaimable { claim_deadline, .. } => {
2934 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
2939 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
2941 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
2942 - if fail_payment { 0 } else { 2 });
2944 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
2945 // and expire both immediately, though, by connecting another 4 blocks.
2946 let reason = HTLCDestination::FailedPayment { payment_hash };
2947 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
2948 connect_blocks(&nodes[3], 4);
2949 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
2950 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2952 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
2953 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false);
2954 check_closed_broadcast(&nodes[1], 1, true);
2955 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2956 assert_eq!(bs_tx.len(), 1);
2958 mine_transaction(&nodes[3], &bs_tx[0]);
2959 check_added_monitors(&nodes[3], 1);
2960 check_closed_broadcast(&nodes[3], 1, true);
2961 check_closed_event(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false);
2963 nodes[3].node.claim_funds(payment_preimage);
2964 check_added_monitors(&nodes[3], 2);
2965 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
2967 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2968 assert_eq!(ds_tx.len(), 1);
2969 check_spends!(&ds_tx[0], &bs_tx[0]);
2971 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
2972 check_added_monitors(&nodes[1], 1);
2973 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
2975 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
2976 check_added_monitors(&nodes[1], 1);
2977 assert_eq!(bs_claims.len(), 1);
2978 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
2979 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2980 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
2981 } else { panic!(); }
2983 expect_payment_sent!(nodes[0], payment_preimage);
2985 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
2986 assert_eq!(ds_claim_msgs.len(), 1);
2987 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
2988 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2989 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
2990 check_added_monitors(&nodes[2], 1);
2991 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
2992 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
2994 } else { panic!(); };
2996 assert_eq!(cs_claim_msgs.len(), 1);
2997 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
2998 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2999 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3000 } else { panic!(); }
3002 expect_payment_path_successful!(nodes[0]);
3007 fn claim_from_closed_chan() {
3008 do_claim_from_closed_chan(true);
3009 do_claim_from_closed_chan(false);
3012 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3013 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3014 // another results in the HTLC being rejected.
3016 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3017 // first of which we'll deliver and the second of which we'll fail and then re-send with
3018 // modified payment metadata, which will in turn result in it being failed by the recipient.
3019 let chanmon_cfgs = create_chanmon_cfgs(4);
3020 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3021 let mut config = test_default_channel_config();
3022 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3023 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3026 let new_chain_monitor;
3027 let nodes_0_deserialized;
3029 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3031 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3032 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3033 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3034 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3036 // Pay more than half of each channel's max, requiring MPP
3037 let amt_msat = 750_000_000;
3038 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3039 let payment_id = PaymentId(payment_hash.0);
3040 let payment_metadata = vec![44, 49, 52, 142];
3042 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3043 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3044 let mut route_params = RouteParameters {
3046 final_value_msat: amt_msat,
3049 // Send the MPP payment, delivering the updated commitment state to nodes[1].
3050 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3051 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata),
3052 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3053 check_added_monitors!(nodes[0], 2);
3055 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3056 assert_eq!(send_events.len(), 2);
3057 let first_send = SendEvent::from_event(send_events.pop().unwrap());
3058 let second_send = SendEvent::from_event(send_events.pop().unwrap());
3060 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3061 (&first_send, &second_send)
3063 (&second_send, &first_send)
3065 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3066 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3068 expect_pending_htlcs_forwardable!(nodes[1]);
3069 check_added_monitors(&nodes[1], 1);
3070 let b_forward_ev = SendEvent::from_node(&nodes[1]);
3071 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3072 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3074 expect_pending_htlcs_forwardable!(nodes[3]);
3076 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3077 // will result in nodes[2] failing the HTLC back.
3078 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3079 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3081 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3082 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3084 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3085 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3086 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3088 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3089 assert_eq!(payment_fail_retryable_evs.len(), 2);
3090 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3091 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3093 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3094 // stored for our payment.
3096 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3099 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3100 // the payment state.
3102 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3103 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3104 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3105 persister, new_chain_monitor, nodes_0_deserialized);
3106 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3107 reconnect_nodes(&nodes[1], &nodes[3], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3109 reconnect_nodes(&nodes[2], &nodes[3], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3111 // Create a new channel between C and D as A will refuse to retry on the existing one because
3113 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3115 // Now retry the failed HTLC.
3116 nodes[0].node.process_pending_htlc_forwards();
3117 check_added_monitors(&nodes[0], 1);
3118 let as_resend = SendEvent::from_node(&nodes[0]);
3119 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3120 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3122 expect_pending_htlcs_forwardable!(nodes[2]);
3123 check_added_monitors(&nodes[2], 1);
3124 let cs_forward = SendEvent::from_node(&nodes[2]);
3125 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3126 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3128 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3129 // the payment metadata was modified, failing only the one modified HTLC and retaining the
3132 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3133 nodes[3].node.process_pending_htlc_forwards();
3134 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3135 &[HTLCDestination::FailedPayment {payment_hash}]);
3136 nodes[3].node.process_pending_htlc_forwards();
3138 check_added_monitors(&nodes[3], 1);
3139 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3141 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3142 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3143 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3144 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3146 expect_pending_htlcs_forwardable!(nodes[3]);
3147 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3148 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3153 fn test_payment_metadata_consistency() {
3154 do_test_payment_metadata_consistency(true, true);
3155 do_test_payment_metadata_consistency(true, false);
3156 do_test_payment_metadata_consistency(false, true);
3157 do_test_payment_metadata_consistency(false, false);