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 { err: ref err_msg }},
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);
2175 assert!(err_msg.contains("max HTLC"));
2177 _ => panic!("Unexpected event"),
2179 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2180 assert_eq!(htlc_msgs.len(), 2);
2181 check_added_monitors!(nodes[0], 2);
2185 fn immediate_retry_on_failure() {
2186 // Tests that we can/will retry immediately after a failure
2187 let chanmon_cfgs = create_chanmon_cfgs(2);
2188 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2189 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2190 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2192 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2193 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2195 let amt_msat = 100_000_001;
2196 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2197 #[cfg(feature = "std")]
2198 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2199 #[cfg(not(feature = "std"))]
2200 let payment_expiry_secs = 60 * 60;
2201 let mut invoice_features = InvoiceFeatures::empty();
2202 invoice_features.set_variable_length_onion_required();
2203 invoice_features.set_payment_secret_required();
2204 invoice_features.set_basic_mpp_optional();
2205 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2206 .with_expiry_time(payment_expiry_secs as u64)
2207 .with_bolt11_features(invoice_features).unwrap();
2208 let route_params = RouteParameters {
2210 final_value_msat: amt_msat,
2213 let chans = nodes[0].node.list_usable_channels();
2214 let mut route = Route {
2216 Path { hops: vec![RouteHop {
2217 pubkey: nodes[1].node.get_our_node_id(),
2218 node_features: nodes[1].node.node_features(),
2219 short_channel_id: chans[0].short_channel_id.unwrap(),
2220 channel_features: nodes[1].node.channel_features(),
2221 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2222 cltv_expiry_delta: 100,
2223 }], blinded_tail: None },
2225 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2227 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2228 // On retry, split the payment across both channels.
2229 route.paths.push(route.paths[0].clone());
2230 route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2231 route.paths[0].hops[0].fee_msat = 50_000_000;
2232 route.paths[1].hops[0].fee_msat = 50_000_001;
2233 let mut pay_params = route_params.payment_params.clone();
2234 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2235 nodes[0].router.expect_find_route(RouteParameters {
2236 payment_params: pay_params, final_value_msat: amt_msat,
2237 }, Ok(route.clone()));
2239 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2240 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2241 let events = nodes[0].node.get_and_clear_pending_events();
2242 assert_eq!(events.len(), 1);
2244 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2245 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2246 short_channel_id: Some(expected_scid), .. } =>
2248 assert_eq!(payment_hash, ev_payment_hash);
2249 assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2250 assert!(err_msg.contains("max HTLC"));
2252 _ => panic!("Unexpected event"),
2254 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2255 assert_eq!(htlc_msgs.len(), 2);
2256 check_added_monitors!(nodes[0], 2);
2260 fn no_extra_retries_on_back_to_back_fail() {
2261 // In a previous release, we had a race where we may exceed the payment retry count if we
2262 // get two failures in a row with the second indicating that all paths had failed (this field,
2263 // `all_paths_failed`, has since been removed).
2264 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2265 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2266 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2267 // pending which we will see later. Thus, when we previously removed the retry tracking map
2268 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2269 // retry entry even though more events for the same payment were still pending. This led to
2270 // us retrying a payment again even though we'd already given up on it.
2272 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2273 // is used to remove the payment retry counter entries instead. This tests for the specific
2274 // excess-retry case while also testing `PaymentFailed` generation.
2276 let chanmon_cfgs = create_chanmon_cfgs(3);
2277 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2278 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2279 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2281 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2282 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2284 let amt_msat = 200_000_000;
2285 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2286 #[cfg(feature = "std")]
2287 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2288 #[cfg(not(feature = "std"))]
2289 let payment_expiry_secs = 60 * 60;
2290 let mut invoice_features = InvoiceFeatures::empty();
2291 invoice_features.set_variable_length_onion_required();
2292 invoice_features.set_payment_secret_required();
2293 invoice_features.set_basic_mpp_optional();
2294 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2295 .with_expiry_time(payment_expiry_secs as u64)
2296 .with_bolt11_features(invoice_features).unwrap();
2297 let route_params = RouteParameters {
2299 final_value_msat: amt_msat,
2302 let mut route = Route {
2304 Path { hops: vec![RouteHop {
2305 pubkey: nodes[1].node.get_our_node_id(),
2306 node_features: nodes[1].node.node_features(),
2307 short_channel_id: chan_1_scid,
2308 channel_features: nodes[1].node.channel_features(),
2309 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2310 cltv_expiry_delta: 100,
2312 pubkey: nodes[2].node.get_our_node_id(),
2313 node_features: nodes[2].node.node_features(),
2314 short_channel_id: chan_2_scid,
2315 channel_features: nodes[2].node.channel_features(),
2316 fee_msat: 100_000_000,
2317 cltv_expiry_delta: 100,
2318 }], blinded_tail: None },
2319 Path { hops: vec![RouteHop {
2320 pubkey: nodes[1].node.get_our_node_id(),
2321 node_features: nodes[1].node.node_features(),
2322 short_channel_id: chan_1_scid,
2323 channel_features: nodes[1].node.channel_features(),
2324 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2325 cltv_expiry_delta: 100,
2327 pubkey: nodes[2].node.get_our_node_id(),
2328 node_features: nodes[2].node.node_features(),
2329 short_channel_id: chan_2_scid,
2330 channel_features: nodes[2].node.channel_features(),
2331 fee_msat: 100_000_000,
2332 cltv_expiry_delta: 100,
2333 }], blinded_tail: None }
2335 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2337 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2338 let mut second_payment_params = route_params.payment_params.clone();
2339 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2340 // On retry, we'll only return one path
2341 route.paths.remove(1);
2342 route.paths[0].hops[1].fee_msat = amt_msat;
2343 nodes[0].router.expect_find_route(RouteParameters {
2344 payment_params: second_payment_params,
2345 final_value_msat: amt_msat,
2346 }, Ok(route.clone()));
2348 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2349 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2350 let htlc_updates = SendEvent::from_node(&nodes[0]);
2351 check_added_monitors!(nodes[0], 1);
2352 assert_eq!(htlc_updates.msgs.len(), 1);
2354 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2355 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2356 check_added_monitors!(nodes[1], 1);
2357 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2359 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2360 check_added_monitors!(nodes[0], 1);
2361 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2363 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2364 check_added_monitors!(nodes[0], 1);
2365 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2367 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2368 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2369 check_added_monitors!(nodes[1], 1);
2370 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2372 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2373 check_added_monitors!(nodes[1], 1);
2374 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2376 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2377 check_added_monitors!(nodes[0], 1);
2379 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2380 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2381 check_added_monitors!(nodes[0], 1);
2382 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2384 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2385 check_added_monitors!(nodes[1], 1);
2386 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2388 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2389 check_added_monitors!(nodes[1], 1);
2390 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2392 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2393 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2394 check_added_monitors!(nodes[0], 1);
2396 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2397 check_added_monitors!(nodes[0], 1);
2398 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2400 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2401 check_added_monitors!(nodes[1], 1);
2402 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2403 check_added_monitors!(nodes[1], 1);
2404 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2406 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2407 check_added_monitors!(nodes[0], 1);
2409 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2410 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2413 // Previously, we retried payments in an event consumer, which would retry each
2414 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2415 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2416 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2417 // by adding the `PaymentFailed` event.
2419 // Because we now retry payments as a batch, we simply return a single-path route in the
2420 // second, batched, request, have that fail, ensure the payment was abandoned.
2421 let mut events = nodes[0].node.get_and_clear_pending_events();
2422 assert_eq!(events.len(), 3);
2424 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2425 assert_eq!(payment_hash, ev_payment_hash);
2426 assert_eq!(payment_failed_permanently, false);
2428 _ => panic!("Unexpected event"),
2431 Event::PendingHTLCsForwardable { .. } => {},
2432 _ => panic!("Unexpected event"),
2435 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2436 assert_eq!(payment_hash, ev_payment_hash);
2437 assert_eq!(payment_failed_permanently, false);
2439 _ => panic!("Unexpected event"),
2442 nodes[0].node.process_pending_htlc_forwards();
2443 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2444 check_added_monitors!(nodes[0], 1);
2446 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2447 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2448 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2449 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2450 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2452 let mut events = nodes[0].node.get_and_clear_pending_events();
2453 assert_eq!(events.len(), 2);
2455 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2456 assert_eq!(payment_hash, ev_payment_hash);
2457 assert_eq!(payment_failed_permanently, false);
2459 _ => panic!("Unexpected event"),
2462 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2463 assert_eq!(payment_hash, *ev_payment_hash);
2464 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2465 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2467 _ => panic!("Unexpected event"),
2472 fn test_simple_partial_retry() {
2473 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2474 // full amount of the payment, rather than only the missing amount. Here we simply test for
2475 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2476 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2478 let chanmon_cfgs = create_chanmon_cfgs(3);
2479 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2480 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2481 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2483 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2484 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2486 let amt_msat = 200_000_000;
2487 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2488 #[cfg(feature = "std")]
2489 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2490 #[cfg(not(feature = "std"))]
2491 let payment_expiry_secs = 60 * 60;
2492 let mut invoice_features = InvoiceFeatures::empty();
2493 invoice_features.set_variable_length_onion_required();
2494 invoice_features.set_payment_secret_required();
2495 invoice_features.set_basic_mpp_optional();
2496 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2497 .with_expiry_time(payment_expiry_secs as u64)
2498 .with_bolt11_features(invoice_features).unwrap();
2499 let route_params = RouteParameters {
2501 final_value_msat: amt_msat,
2504 let mut route = Route {
2506 Path { hops: vec![RouteHop {
2507 pubkey: nodes[1].node.get_our_node_id(),
2508 node_features: nodes[1].node.node_features(),
2509 short_channel_id: chan_1_scid,
2510 channel_features: nodes[1].node.channel_features(),
2511 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2512 cltv_expiry_delta: 100,
2514 pubkey: nodes[2].node.get_our_node_id(),
2515 node_features: nodes[2].node.node_features(),
2516 short_channel_id: chan_2_scid,
2517 channel_features: nodes[2].node.channel_features(),
2518 fee_msat: 100_000_000,
2519 cltv_expiry_delta: 100,
2520 }], blinded_tail: None },
2521 Path { hops: vec![RouteHop {
2522 pubkey: nodes[1].node.get_our_node_id(),
2523 node_features: nodes[1].node.node_features(),
2524 short_channel_id: chan_1_scid,
2525 channel_features: nodes[1].node.channel_features(),
2527 cltv_expiry_delta: 100,
2529 pubkey: nodes[2].node.get_our_node_id(),
2530 node_features: nodes[2].node.node_features(),
2531 short_channel_id: chan_2_scid,
2532 channel_features: nodes[2].node.channel_features(),
2533 fee_msat: 100_000_000,
2534 cltv_expiry_delta: 100,
2535 }], blinded_tail: None }
2537 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2539 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2540 let mut second_payment_params = route_params.payment_params.clone();
2541 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2542 // On retry, we'll only be asked for one path (or 100k sats)
2543 route.paths.remove(0);
2544 nodes[0].router.expect_find_route(RouteParameters {
2545 payment_params: second_payment_params,
2546 final_value_msat: amt_msat / 2,
2547 }, Ok(route.clone()));
2549 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2550 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2551 let htlc_updates = SendEvent::from_node(&nodes[0]);
2552 check_added_monitors!(nodes[0], 1);
2553 assert_eq!(htlc_updates.msgs.len(), 1);
2555 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2556 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2557 check_added_monitors!(nodes[1], 1);
2558 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2560 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2561 check_added_monitors!(nodes[0], 1);
2562 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2564 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2565 check_added_monitors!(nodes[0], 1);
2566 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2568 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2569 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2570 check_added_monitors!(nodes[1], 1);
2571 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2573 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2574 check_added_monitors!(nodes[1], 1);
2575 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2577 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2578 check_added_monitors!(nodes[0], 1);
2580 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2581 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2582 check_added_monitors!(nodes[0], 1);
2583 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2585 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2586 check_added_monitors!(nodes[1], 1);
2588 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2589 check_added_monitors!(nodes[1], 1);
2591 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2593 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2594 check_added_monitors!(nodes[0], 1);
2596 let mut events = nodes[0].node.get_and_clear_pending_events();
2597 assert_eq!(events.len(), 2);
2599 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2600 assert_eq!(payment_hash, ev_payment_hash);
2601 assert_eq!(payment_failed_permanently, false);
2603 _ => panic!("Unexpected event"),
2606 Event::PendingHTLCsForwardable { .. } => {},
2607 _ => panic!("Unexpected event"),
2610 nodes[0].node.process_pending_htlc_forwards();
2611 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2612 check_added_monitors!(nodes[0], 1);
2614 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2615 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2617 expect_pending_htlcs_forwardable!(nodes[1]);
2618 check_added_monitors!(nodes[1], 1);
2620 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2621 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2622 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2623 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2625 expect_pending_htlcs_forwardable!(nodes[2]);
2626 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2630 #[cfg(feature = "std")]
2631 fn test_threaded_payment_retries() {
2632 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2633 // a single thread and would happily let multiple threads run retries at the same time. Because
2634 // retries are done by first calculating the amount we need to retry, then dropping the
2635 // relevant lock, then actually sending, we would happily let multiple threads retry the same
2636 // amount at the same time, overpaying our original HTLC!
2637 let chanmon_cfgs = create_chanmon_cfgs(4);
2638 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2639 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2640 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2642 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2643 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2644 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2645 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2647 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2648 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2649 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2650 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2652 let amt_msat = 100_000_000;
2653 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2654 #[cfg(feature = "std")]
2655 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2656 #[cfg(not(feature = "std"))]
2657 let payment_expiry_secs = 60 * 60;
2658 let mut invoice_features = InvoiceFeatures::empty();
2659 invoice_features.set_variable_length_onion_required();
2660 invoice_features.set_payment_secret_required();
2661 invoice_features.set_basic_mpp_optional();
2662 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2663 .with_expiry_time(payment_expiry_secs as u64)
2664 .with_bolt11_features(invoice_features).unwrap();
2665 let mut route_params = RouteParameters {
2667 final_value_msat: amt_msat,
2670 let mut route = Route {
2672 Path { hops: vec![RouteHop {
2673 pubkey: nodes[1].node.get_our_node_id(),
2674 node_features: nodes[1].node.node_features(),
2675 short_channel_id: chan_1_scid,
2676 channel_features: nodes[1].node.channel_features(),
2678 cltv_expiry_delta: 100,
2680 pubkey: nodes[3].node.get_our_node_id(),
2681 node_features: nodes[2].node.node_features(),
2682 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2683 channel_features: nodes[2].node.channel_features(),
2684 fee_msat: amt_msat / 1000,
2685 cltv_expiry_delta: 100,
2686 }], blinded_tail: None },
2687 Path { hops: vec![RouteHop {
2688 pubkey: nodes[2].node.get_our_node_id(),
2689 node_features: nodes[2].node.node_features(),
2690 short_channel_id: chan_3_scid,
2691 channel_features: nodes[2].node.channel_features(),
2693 cltv_expiry_delta: 100,
2695 pubkey: nodes[3].node.get_our_node_id(),
2696 node_features: nodes[3].node.node_features(),
2697 short_channel_id: chan_4_scid,
2698 channel_features: nodes[3].node.channel_features(),
2699 fee_msat: amt_msat - amt_msat / 1000,
2700 cltv_expiry_delta: 100,
2701 }], blinded_tail: None }
2703 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2705 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2707 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2708 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
2709 check_added_monitors!(nodes[0], 2);
2710 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2711 assert_eq!(send_msg_events.len(), 2);
2712 send_msg_events.retain(|msg|
2713 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
2714 // Drop the commitment update for nodes[2], we can just let that one sit pending
2716 *node_id == nodes[1].node.get_our_node_id()
2717 } else { panic!(); }
2720 // from here on out, the retry `RouteParameters` amount will be amt/1000
2721 route_params.final_value_msat /= 1000;
2724 let end_time = Instant::now() + Duration::from_secs(1);
2725 macro_rules! thread_body { () => { {
2726 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
2727 let node_ref = NodePtr::from_node(&nodes[0]);
2729 let node_a = unsafe { &*node_ref.0 };
2730 while Instant::now() < end_time {
2731 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2732 // Ignore if we have any pending events, just always pretend we just got a
2733 // PendingHTLCsForwardable
2734 node_a.node.process_pending_htlc_forwards();
2738 let mut threads = Vec::new();
2739 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
2741 // Back in the main thread, poll pending messages and make sure that we never have more than
2742 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
2743 // there are HTLC messages shoved in while its running. This allows us to test that we never
2744 // generate an additional update_add_htlc until we've fully failed the first.
2745 let mut previously_failed_channels = Vec::new();
2747 assert_eq!(send_msg_events.len(), 1);
2748 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
2749 assert_eq!(send_event.msgs.len(), 1);
2751 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
2752 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
2754 // Note that we only push one route into `expect_find_route` at a time, because that's all
2755 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
2756 // we should still ultimately fail for the same reason - because we're trying to send too
2757 // many HTLCs at once.
2758 let mut new_route_params = route_params.clone();
2759 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
2760 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
2761 route.paths[0].hops[1].short_channel_id += 1;
2762 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
2764 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2765 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
2766 // The "normal" commitment_signed_dance delivers the final RAA and then calls
2767 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
2768 // This races with our other threads which may generate an add-HTLCs commitment update via
2769 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
2770 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
2771 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
2772 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
2774 let cur_time = Instant::now();
2775 if cur_time > end_time {
2776 for thread in threads.drain(..) { thread.join().unwrap(); }
2779 // Make sure we have some events to handle when we go around...
2780 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2781 nodes[0].node.process_pending_htlc_forwards();
2782 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2783 check_added_monitors!(nodes[0], 2);
2785 if cur_time > end_time {
2791 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
2792 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
2793 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
2794 // it was last persisted.
2795 let chanmon_cfgs = create_chanmon_cfgs(2);
2796 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2797 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2798 let (persister_a, persister_b, persister_c);
2799 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
2800 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
2801 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2803 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2805 let mut nodes_0_serialized = Vec::new();
2806 if !persist_manager_with_payment {
2807 nodes_0_serialized = nodes[0].node.encode();
2810 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2812 if persist_manager_with_payment {
2813 nodes_0_serialized = nodes[0].node.encode();
2816 nodes[1].node.claim_funds(our_payment_preimage);
2817 check_added_monitors!(nodes[1], 1);
2818 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
2820 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2821 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2822 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
2823 check_added_monitors!(nodes[0], 1);
2825 // The ChannelMonitor should always be the latest version, as we're required to persist it
2826 // during the commitment signed handling.
2827 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2828 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
2830 let events = nodes[0].node.get_and_clear_pending_events();
2831 assert_eq!(events.len(), 2);
2832 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
2833 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
2834 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
2835 // the double-claim that would otherwise appear at the end of this test.
2836 nodes[0].node.timer_tick_occurred();
2837 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2838 assert_eq!(as_broadcasted_txn.len(), 1);
2840 // Ensure that, even after some time, if we restart we still include *something* in the current
2841 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
2842 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
2843 // A naive implementation of the fix here would wipe the pending payments set, causing a
2844 // failure event when we restart.
2845 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2847 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2848 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);
2849 let events = nodes[0].node.get_and_clear_pending_events();
2850 assert!(events.is_empty());
2852 // Ensure that we don't generate any further events even after the channel-closing commitment
2853 // transaction is confirmed on-chain.
2854 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
2855 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2857 let events = nodes[0].node.get_and_clear_pending_events();
2858 assert!(events.is_empty());
2860 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2861 reload_node!(nodes[0], test_default_channel_config(), &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister_c, chain_monitor_c, nodes_0_deserialized_c);
2862 let events = nodes[0].node.get_and_clear_pending_events();
2863 assert!(events.is_empty());
2867 fn no_missing_sent_on_midpoint_reload() {
2868 do_no_missing_sent_on_midpoint_reload(false);
2869 do_no_missing_sent_on_midpoint_reload(true);
2872 fn do_claim_from_closed_chan(fail_payment: bool) {
2873 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
2874 // received had been closed between when the HTLC was received and when we went to claim it.
2875 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
2876 // presumably the sender may retry later. Long ago it also reduced total code in the claim
2879 // However, this doesn't make sense if you're trying to do an atomic swap or some other
2880 // protocol that requires atomicity with some other action - if your money got claimed
2881 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
2882 // is an over-optimization - there should be a very, very low likelihood that a channel closes
2883 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
2884 // Since we now have code to handle this anyway we should allow it.
2886 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
2887 // CLTVs on the paths to different value resulting in a different claim deadline.
2888 let chanmon_cfgs = create_chanmon_cfgs(4);
2889 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2890 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2891 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2893 create_announced_chan_between_nodes(&nodes, 0, 1);
2894 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
2895 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
2896 create_announced_chan_between_nodes(&nodes, 2, 3);
2898 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
2899 let mut route_params = RouteParameters {
2900 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
2901 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
2902 final_value_msat: 10_000_000,
2904 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
2905 None, &nodes[0].node.compute_inflight_htlcs()).unwrap();
2906 // Make sure the route is ordered as the B->D path before C->D
2907 route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
2908 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
2910 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
2911 // the HTLC is being relayed.
2912 route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
2913 route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
2914 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
2916 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2917 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2918 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
2919 check_added_monitors(&nodes[0], 2);
2920 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2921 send_msgs.sort_by(|a, _| {
2923 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
2924 let node_b_id = nodes[1].node.get_our_node_id();
2925 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
2928 assert_eq!(send_msgs.len(), 2);
2929 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
2930 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
2931 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
2932 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
2934 match receive_event.unwrap() {
2935 Event::PaymentClaimable { claim_deadline, .. } => {
2936 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
2941 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
2943 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
2944 - if fail_payment { 0 } else { 2 });
2946 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
2947 // and expire both immediately, though, by connecting another 4 blocks.
2948 let reason = HTLCDestination::FailedPayment { payment_hash };
2949 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
2950 connect_blocks(&nodes[3], 4);
2951 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
2952 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2954 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
2955 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false);
2956 check_closed_broadcast(&nodes[1], 1, true);
2957 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2958 assert_eq!(bs_tx.len(), 1);
2960 mine_transaction(&nodes[3], &bs_tx[0]);
2961 check_added_monitors(&nodes[3], 1);
2962 check_closed_broadcast(&nodes[3], 1, true);
2963 check_closed_event(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false);
2965 nodes[3].node.claim_funds(payment_preimage);
2966 check_added_monitors(&nodes[3], 2);
2967 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
2969 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2970 assert_eq!(ds_tx.len(), 1);
2971 check_spends!(&ds_tx[0], &bs_tx[0]);
2973 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
2974 check_added_monitors(&nodes[1], 1);
2975 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
2977 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
2978 check_added_monitors(&nodes[1], 1);
2979 assert_eq!(bs_claims.len(), 1);
2980 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
2981 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2982 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
2983 } else { panic!(); }
2985 expect_payment_sent!(nodes[0], payment_preimage);
2987 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
2988 assert_eq!(ds_claim_msgs.len(), 1);
2989 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
2990 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2991 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
2992 check_added_monitors(&nodes[2], 1);
2993 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
2994 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
2996 } else { panic!(); };
2998 assert_eq!(cs_claim_msgs.len(), 1);
2999 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3000 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3001 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3002 } else { panic!(); }
3004 expect_payment_path_successful!(nodes[0]);
3009 fn claim_from_closed_chan() {
3010 do_claim_from_closed_chan(true);
3011 do_claim_from_closed_chan(false);
3014 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3015 // Check that a payment metadata received on one HTLC that doesn't match the one received on
3016 // another results in the HTLC being rejected.
3018 // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3019 // first of which we'll deliver and the second of which we'll fail and then re-send with
3020 // modified payment metadata, which will in turn result in it being failed by the recipient.
3021 let chanmon_cfgs = create_chanmon_cfgs(4);
3022 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3023 let mut config = test_default_channel_config();
3024 config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3025 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3028 let new_chain_monitor;
3029 let nodes_0_deserialized;
3031 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3033 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3034 let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3035 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3036 let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3038 // Pay more than half of each channel's max, requiring MPP
3039 let amt_msat = 750_000_000;
3040 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3041 let payment_id = PaymentId(payment_hash.0);
3042 let payment_metadata = vec![44, 49, 52, 142];
3044 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3045 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3046 let mut route_params = RouteParameters {
3048 final_value_msat: amt_msat,
3051 // Send the MPP payment, delivering the updated commitment state to nodes[1].
3052 nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3053 payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata),
3054 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3055 check_added_monitors!(nodes[0], 2);
3057 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3058 assert_eq!(send_events.len(), 2);
3059 let first_send = SendEvent::from_event(send_events.pop().unwrap());
3060 let second_send = SendEvent::from_event(send_events.pop().unwrap());
3062 let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3063 (&first_send, &second_send)
3065 (&second_send, &first_send)
3067 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3068 commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3070 expect_pending_htlcs_forwardable!(nodes[1]);
3071 check_added_monitors(&nodes[1], 1);
3072 let b_forward_ev = SendEvent::from_node(&nodes[1]);
3073 nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3074 commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3076 expect_pending_htlcs_forwardable!(nodes[3]);
3078 // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3079 // will result in nodes[2] failing the HTLC back.
3080 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3081 nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3083 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3084 commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3086 let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3087 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3088 commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3090 let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3091 assert_eq!(payment_fail_retryable_evs.len(), 2);
3092 if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3093 if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3095 // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3096 // stored for our payment.
3098 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3101 // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3102 // the payment state.
3104 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3105 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3106 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3107 persister, new_chain_monitor, nodes_0_deserialized);
3108 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3109 reconnect_nodes(&nodes[1], &nodes[3], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3111 reconnect_nodes(&nodes[2], &nodes[3], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3113 // Create a new channel between C and D as A will refuse to retry on the existing one because
3115 let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3117 // Now retry the failed HTLC.
3118 nodes[0].node.process_pending_htlc_forwards();
3119 check_added_monitors(&nodes[0], 1);
3120 let as_resend = SendEvent::from_node(&nodes[0]);
3121 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3122 commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3124 expect_pending_htlcs_forwardable!(nodes[2]);
3125 check_added_monitors(&nodes[2], 1);
3126 let cs_forward = SendEvent::from_node(&nodes[2]);
3127 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3128 commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3130 // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3131 // the payment metadata was modified, failing only the one modified HTLC and retaining the
3134 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3135 nodes[3].node.process_pending_htlc_forwards();
3136 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3137 &[HTLCDestination::FailedPayment {payment_hash}]);
3138 nodes[3].node.process_pending_htlc_forwards();
3140 check_added_monitors(&nodes[3], 1);
3141 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3143 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3144 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3145 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3146 &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3148 expect_pending_htlcs_forwardable!(nodes[3]);
3149 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3150 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3155 fn test_payment_metadata_consistency() {
3156 do_test_payment_metadata_consistency(true, true);
3157 do_test_payment_metadata_consistency(true, false);
3158 do_test_payment_metadata_consistency(false, true);
3159 do_test_payment_metadata_consistency(false, false);