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::chain::keysinterface::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, 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::{Block, BlockHeader, TxMerkleNode};
34 use bitcoin::hashes::Hash;
35 use bitcoin::network::constants::Network;
37 use crate::prelude::*;
39 use crate::ln::functional_test_utils::*;
40 use crate::routing::gossip::NodeId;
41 #[cfg(feature = "std")]
43 crate::util::time::tests::SinceEpoch,
44 std::time::{SystemTime, Instant, Duration}
49 let chanmon_cfgs = create_chanmon_cfgs(4);
50 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
51 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
52 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
54 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
55 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
56 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
57 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
59 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
60 let path = route.paths[0].clone();
61 route.paths.push(path);
62 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
63 route.paths[0][0].short_channel_id = chan_1_id;
64 route.paths[0][1].short_channel_id = chan_3_id;
65 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
66 route.paths[1][0].short_channel_id = chan_2_id;
67 route.paths[1][1].short_channel_id = chan_4_id;
68 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
69 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
74 let chanmon_cfgs = create_chanmon_cfgs(4);
75 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
76 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
77 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
79 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
80 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
81 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
82 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
84 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
86 let amt_msat = 1_000_000;
87 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
88 let path = route.paths[0].clone();
89 route.paths.push(path);
90 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
91 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
92 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
93 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
94 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
95 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
97 // Initiate the MPP payment.
98 let payment_id = PaymentId(payment_hash.0);
99 let mut route_params = RouteParameters {
100 payment_params: route.payment_params.clone().unwrap(),
101 final_value_msat: amt_msat,
104 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
105 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
106 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
107 check_added_monitors!(nodes[0], 2); // one monitor per path
108 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
109 assert_eq!(events.len(), 2);
111 // Pass half of the payment along the success path.
112 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
113 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
115 // Add the HTLC along the first hop.
116 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
117 let (update_add, commitment_signed) = match fail_path_msgs_1 {
118 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 } } => {
119 assert_eq!(update_add_htlcs.len(), 1);
120 assert!(update_fail_htlcs.is_empty());
121 assert!(update_fulfill_htlcs.is_empty());
122 assert!(update_fail_malformed_htlcs.is_empty());
123 assert!(update_fee.is_none());
124 (update_add_htlcs[0].clone(), commitment_signed.clone())
126 _ => panic!("Unexpected event"),
128 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
129 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
131 // Attempt to forward the payment and complete the 2nd path's failure.
132 expect_pending_htlcs_forwardable!(&nodes[2]);
133 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 }]);
134 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
135 assert!(htlc_updates.update_add_htlcs.is_empty());
136 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
137 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
138 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
139 check_added_monitors!(nodes[2], 1);
140 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
141 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
142 let mut events = nodes[0].node.get_and_clear_pending_events();
144 Event::PendingHTLCsForwardable { .. } => {},
145 _ => panic!("Unexpected event")
148 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
150 // Rebalance the channel so the second half of the payment can succeed.
151 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
153 // Retry the second half of the payment and make sure it succeeds.
154 route.paths.remove(0);
155 route_params.final_value_msat = 1_000_000;
156 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
157 nodes[0].router.expect_find_route(route_params, Ok(route));
158 nodes[0].node.process_pending_htlc_forwards();
159 check_added_monitors!(nodes[0], 1);
160 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
161 assert_eq!(events.len(), 1);
162 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
163 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
166 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
167 let chanmon_cfgs = create_chanmon_cfgs(4);
168 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
169 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
170 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
172 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
173 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
174 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
175 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
177 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
178 let path = route.paths[0].clone();
179 route.paths.push(path);
180 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
181 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
182 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
183 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
184 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
185 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
187 // Initiate the MPP payment.
188 nodes[0].node.send_payment_with_route(&route, payment_hash,
189 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
190 check_added_monitors!(nodes[0], 2); // one monitor per path
191 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
192 assert_eq!(events.len(), 2);
194 // Pass half of the payment along the first path.
195 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
196 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
198 if send_partial_mpp {
199 // Time out the partial MPP
200 for _ in 0..MPP_TIMEOUT_TICKS {
201 nodes[3].node.timer_tick_occurred();
204 // Failed HTLC from node 3 -> 1
205 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
206 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
207 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
208 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
209 check_added_monitors!(nodes[3], 1);
210 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
212 // Failed HTLC from node 1 -> 0
213 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 }]);
214 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
215 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
216 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
217 check_added_monitors!(nodes[1], 1);
218 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
220 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
222 // Pass half of the payment along the second path.
223 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
224 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
226 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
227 for _ in 0..MPP_TIMEOUT_TICKS {
228 nodes[3].node.timer_tick_occurred();
231 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
236 fn mpp_receive_timeout() {
237 do_mpp_receive_timeout(true);
238 do_mpp_receive_timeout(false);
242 fn no_pending_leak_on_initial_send_failure() {
243 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
244 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
245 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
246 // pending payment forever and never time it out.
247 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
248 // try, and then check that no pending payment is being tracked.
249 let chanmon_cfgs = create_chanmon_cfgs(2);
250 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
251 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
252 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
254 create_announced_chan_between_nodes(&nodes, 0, 1);
256 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
258 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
259 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
261 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
262 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
263 ), true, APIError::ChannelUnavailable { ref err },
264 assert_eq!(err, "Peer for first hop currently disconnected"));
266 assert!(!nodes[0].node.has_pending_payments());
269 fn do_retry_with_no_persist(confirm_before_reload: bool) {
270 // If we send a pending payment and `send_payment` returns success, we should always either
271 // return a payment failure event or a payment success event, and on failure the payment should
274 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
275 // always persisted asynchronously), the ChannelManager has to reload some payment data from
276 // ChannelMonitor(s) in some cases. This tests that reloading.
278 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
279 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
280 // which has separate codepaths for "commitment transaction already confirmed" and not.
281 let chanmon_cfgs = create_chanmon_cfgs(3);
282 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
283 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
284 let persister: test_utils::TestPersister;
285 let new_chain_monitor: test_utils::TestChainMonitor;
286 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>;
287 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
289 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
290 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
292 // Serialize the ChannelManager prior to sending payments
293 let nodes_0_serialized = nodes[0].node.encode();
295 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
297 let amt_msat = 1_000_000;
298 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
299 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
300 let route_params = RouteParameters {
301 payment_params: route.payment_params.clone().unwrap(),
302 final_value_msat: amt_msat,
304 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
305 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
306 check_added_monitors!(nodes[0], 1);
308 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
309 assert_eq!(events.len(), 1);
310 let payment_event = SendEvent::from_event(events.pop().unwrap());
311 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
313 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
314 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
315 // which would prevent retry.
316 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
317 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
319 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
320 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
321 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
322 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
324 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
326 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
327 if confirm_before_reload {
328 mine_transaction(&nodes[0], &as_commitment_tx);
329 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
332 // The ChannelMonitor should always be the latest version, as we're required to persist it
333 // during the `commitment_signed_dance!()`.
334 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
335 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
337 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
338 // force-close the channel.
339 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
340 assert!(nodes[0].node.list_channels().is_empty());
341 assert!(nodes[0].node.has_pending_payments());
342 nodes[0].node.timer_tick_occurred();
343 if !confirm_before_reload {
344 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
345 assert_eq!(as_broadcasted_txn.len(), 1);
346 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
348 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
350 check_added_monitors!(nodes[0], 1);
352 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
353 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();
354 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
356 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
357 // error, as the channel has hit the chain.
358 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
359 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
360 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
361 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
362 assert_eq!(as_err.len(), 1);
364 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
365 assert_eq!(node_id, nodes[1].node.get_our_node_id());
366 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
367 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())) });
368 check_added_monitors!(nodes[1], 1);
369 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
371 _ => panic!("Unexpected event"),
373 check_closed_broadcast!(nodes[1], false);
375 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
376 // we close in a moment.
377 nodes[2].node.claim_funds(payment_preimage_1);
378 check_added_monitors!(nodes[2], 1);
379 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
381 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
382 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
383 check_added_monitors!(nodes[1], 1);
384 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
385 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
387 if confirm_before_reload {
388 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
389 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
392 // Create a new channel on which to retry the payment before we fail the payment via the
393 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
394 // connecting several blocks while creating the channel (implying time has passed).
395 create_announced_chan_between_nodes(&nodes, 0, 1);
396 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
398 mine_transaction(&nodes[1], &as_commitment_tx);
399 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
400 assert_eq!(bs_htlc_claim_txn.len(), 1);
401 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
403 if !confirm_before_reload {
404 mine_transaction(&nodes[0], &as_commitment_tx);
406 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
407 expect_payment_sent!(nodes[0], payment_preimage_1);
408 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
409 let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
410 assert_eq!(as_htlc_timeout_txn.len(), 2);
411 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1]);
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][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][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 - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
564 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (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], node_txn[1]);
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 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
695 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
696 check_closed_broadcast!(nodes[1], true);
697 check_added_monitors!(nodes[1], 1);
698 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
699 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
700 assert_eq!(claim_txn.len(), 1);
701 check_spends!(claim_txn[0], node_txn[1]);
703 header.prev_blockhash = nodes[0].best_block_hash();
704 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
706 if confirm_commitment_tx {
707 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
710 header.prev_blockhash = nodes[0].best_block_hash();
711 let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
714 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
715 connect_block(&nodes[0], &claim_block);
716 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
719 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
720 // returning InProgress. This should cause the claim event to never make its way to the
722 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
723 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
726 connect_blocks(&nodes[0], 1);
728 connect_block(&nodes[0], &claim_block);
731 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
732 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
733 .get_mut(&funding_txo).unwrap().drain().collect();
734 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
735 // If we're testing connection idempotency we may get substantially more.
736 assert!(mon_updates.len() >= 1);
737 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
738 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
740 // If we persist the ChannelManager here, we should get the PaymentSent event after
742 let mut chan_manager_serialized = Vec::new();
743 if !persist_manager_post_event {
744 chan_manager_serialized = nodes[0].node.encode();
747 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
748 // payment sent event.
749 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
750 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
751 for update in mon_updates {
752 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
755 expect_payment_failed!(nodes[0], payment_hash, false);
757 expect_payment_sent!(nodes[0], payment_preimage);
760 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
762 if persist_manager_post_event {
763 chan_manager_serialized = nodes[0].node.encode();
766 // Now reload nodes[0]...
767 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
769 if persist_manager_post_event {
770 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
771 } else if payment_timeout {
772 expect_payment_failed!(nodes[0], payment_hash, false);
774 expect_payment_sent!(nodes[0], payment_preimage);
777 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
778 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
779 // payment events should kick in, leaving us with no pending events here.
780 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
781 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
782 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
786 fn test_dup_htlc_onchain_fails_on_reload() {
787 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
788 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
789 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
790 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
791 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
792 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
796 fn test_fulfill_restart_failure() {
797 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
798 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
799 // again, or fail it, giving us free money.
801 // Of course probably they won't fail it and give us free money, but because we have code to
802 // handle it, we should test the logic for it anyway. We do that here.
803 let chanmon_cfgs = create_chanmon_cfgs(2);
804 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
805 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
806 let persister: test_utils::TestPersister;
807 let new_chain_monitor: test_utils::TestChainMonitor;
808 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>;
809 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
811 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
812 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
814 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
815 // pre-fulfill, which we do by serializing it here.
816 let chan_manager_serialized = nodes[1].node.encode();
817 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
819 nodes[1].node.claim_funds(payment_preimage);
820 check_added_monitors!(nodes[1], 1);
821 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
823 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
824 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
825 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
827 // Now reload nodes[1]...
828 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
830 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
831 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
833 nodes[1].node.fail_htlc_backwards(&payment_hash);
834 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
835 check_added_monitors!(nodes[1], 1);
836 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
837 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
838 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
839 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
840 // it had already considered the payment fulfilled, and now they just got free money.
841 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
845 fn get_ldk_payment_preimage() {
846 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
847 let chanmon_cfgs = create_chanmon_cfgs(2);
848 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
849 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
850 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
851 create_announced_chan_between_nodes(&nodes, 0, 1);
853 let amt_msat = 60_000;
854 let expiry_secs = 60 * 60;
855 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
857 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
858 .with_features(nodes[1].node.invoice_features());
859 let scorer = test_utils::TestScorer::new();
860 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
861 let random_seed_bytes = keys_manager.get_secure_random_bytes();
862 let route = get_route(
863 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
864 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
865 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
866 nodes[0].node.send_payment_with_route(&route, payment_hash,
867 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
868 check_added_monitors!(nodes[0], 1);
870 // Make sure to use `get_payment_preimage`
871 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
872 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
873 assert_eq!(events.len(), 1);
874 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
875 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
879 fn sent_probe_is_probe_of_sending_node() {
880 let chanmon_cfgs = create_chanmon_cfgs(3);
881 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
882 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
883 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
885 create_announced_chan_between_nodes(&nodes, 0, 1);
886 create_announced_chan_between_nodes(&nodes, 1, 2);
888 // First check we refuse to build a single-hop probe
889 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
890 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
892 // Then build an actual two-hop probing path
893 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
895 match nodes[0].node.send_probe(route.paths[0].clone()) {
896 Ok((payment_hash, payment_id)) => {
897 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
898 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
899 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
904 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
905 check_added_monitors!(nodes[0], 1);
909 fn successful_probe_yields_event() {
910 let chanmon_cfgs = create_chanmon_cfgs(3);
911 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
912 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
913 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
915 create_announced_chan_between_nodes(&nodes, 0, 1);
916 create_announced_chan_between_nodes(&nodes, 1, 2);
918 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
920 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
922 // node[0] -- update_add_htlcs -> node[1]
923 check_added_monitors!(nodes[0], 1);
924 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
925 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
926 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
927 check_added_monitors!(nodes[1], 0);
928 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
929 expect_pending_htlcs_forwardable!(nodes[1]);
931 // node[1] -- update_add_htlcs -> node[2]
932 check_added_monitors!(nodes[1], 1);
933 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
934 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
935 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
936 check_added_monitors!(nodes[2], 0);
937 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
939 // node[1] <- update_fail_htlcs -- node[2]
940 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
941 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
942 check_added_monitors!(nodes[1], 0);
943 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
945 // node[0] <- update_fail_htlcs -- node[1]
946 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
947 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
948 check_added_monitors!(nodes[0], 0);
949 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
951 let mut events = nodes[0].node.get_and_clear_pending_events();
952 assert_eq!(events.len(), 1);
953 match events.drain(..).next().unwrap() {
954 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
955 assert_eq!(payment_id, ev_pid);
956 assert_eq!(payment_hash, ev_ph);
960 assert!(!nodes[0].node.has_pending_payments());
964 fn failed_probe_yields_event() {
965 let chanmon_cfgs = create_chanmon_cfgs(3);
966 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
967 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
968 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
970 create_announced_chan_between_nodes(&nodes, 0, 1);
971 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
973 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
975 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
977 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
979 // node[0] -- update_add_htlcs -> node[1]
980 check_added_monitors!(nodes[0], 1);
981 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
982 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
983 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
984 check_added_monitors!(nodes[1], 0);
985 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
986 expect_pending_htlcs_forwardable!(nodes[1]);
988 // node[0] <- update_fail_htlcs -- node[1]
989 check_added_monitors!(nodes[1], 1);
990 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
991 // Skip the PendingHTLCsForwardable event
992 let _events = nodes[1].node.get_and_clear_pending_events();
993 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
994 check_added_monitors!(nodes[0], 0);
995 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
997 let mut events = nodes[0].node.get_and_clear_pending_events();
998 assert_eq!(events.len(), 1);
999 match events.drain(..).next().unwrap() {
1000 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1001 assert_eq!(payment_id, ev_pid);
1002 assert_eq!(payment_hash, ev_ph);
1006 assert!(!nodes[0].node.has_pending_payments());
1010 fn onchain_failed_probe_yields_event() {
1011 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1013 let chanmon_cfgs = create_chanmon_cfgs(3);
1014 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1015 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1016 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1018 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1019 create_announced_chan_between_nodes(&nodes, 1, 2);
1021 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1023 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1024 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1025 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1027 // node[0] -- update_add_htlcs -> node[1]
1028 check_added_monitors!(nodes[0], 1);
1029 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1030 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1031 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1032 check_added_monitors!(nodes[1], 0);
1033 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1034 expect_pending_htlcs_forwardable!(nodes[1]);
1036 check_added_monitors!(nodes[1], 1);
1037 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1039 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1040 // Node A, which after 6 confirmations should result in a probe failure event.
1041 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1042 confirm_transaction(&nodes[0], &bs_txn[0]);
1043 check_closed_broadcast!(&nodes[0], true);
1044 check_added_monitors!(nodes[0], 1);
1046 let mut events = nodes[0].node.get_and_clear_pending_events();
1047 assert_eq!(events.len(), 2);
1048 let mut found_probe_failed = false;
1049 for event in events.drain(..) {
1051 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1052 assert_eq!(payment_id, ev_pid);
1053 assert_eq!(payment_hash, ev_ph);
1054 found_probe_failed = true;
1056 Event::ChannelClosed { .. } => {},
1060 assert!(found_probe_failed);
1061 assert!(!nodes[0].node.has_pending_payments());
1065 fn claimed_send_payment_idempotent() {
1066 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1067 let chanmon_cfgs = create_chanmon_cfgs(2);
1068 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1069 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1070 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1072 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1074 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1075 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1077 macro_rules! check_send_rejected {
1079 // If we try to resend a new payment with a different payment_hash but with the same
1080 // payment_id, it should be rejected.
1081 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1082 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1084 Err(PaymentSendFailure::DuplicatePayment) => {},
1085 _ => panic!("Unexpected send result: {:?}", send_result),
1088 // Further, if we try to send a spontaneous payment with the same payment_id it should
1089 // also be rejected.
1090 let send_result = nodes[0].node.send_spontaneous_payment(
1091 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1093 Err(PaymentSendFailure::DuplicatePayment) => {},
1094 _ => panic!("Unexpected send result: {:?}", send_result),
1099 check_send_rejected!();
1101 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1102 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1103 // we must remain just as idempotent as we were before.
1104 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1106 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1107 nodes[0].node.timer_tick_occurred();
1110 check_send_rejected!();
1112 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1113 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1114 // the payment complete. However, they could have called `send_payment` while the event was
1115 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1116 // after the event is handled a duplicate payment should sitll be rejected.
1117 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1118 check_send_rejected!();
1120 // If relatively little time has passed, a duplicate payment should still fail.
1121 nodes[0].node.timer_tick_occurred();
1122 check_send_rejected!();
1124 // However, after some time has passed (at least more than the one timer tick above), a
1125 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1126 // references to the old payment data.
1127 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1128 nodes[0].node.timer_tick_occurred();
1131 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1132 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1133 check_added_monitors!(nodes[0], 1);
1134 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1135 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1139 fn abandoned_send_payment_idempotent() {
1140 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1142 let chanmon_cfgs = create_chanmon_cfgs(2);
1143 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1144 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1145 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1147 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1149 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1150 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1152 macro_rules! check_send_rejected {
1154 // If we try to resend a new payment with a different payment_hash but with the same
1155 // payment_id, it should be rejected.
1156 let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1157 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1159 Err(PaymentSendFailure::DuplicatePayment) => {},
1160 _ => panic!("Unexpected send result: {:?}", send_result),
1163 // Further, if we try to send a spontaneous payment with the same payment_id it should
1164 // also be rejected.
1165 let send_result = nodes[0].node.send_spontaneous_payment(
1166 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1168 Err(PaymentSendFailure::DuplicatePayment) => {},
1169 _ => panic!("Unexpected send result: {:?}", send_result),
1174 check_send_rejected!();
1176 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1177 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1179 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1181 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1182 nodes[0].node.timer_tick_occurred();
1184 check_send_rejected!();
1186 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1188 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1189 // failed payment back.
1190 nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1191 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1192 check_added_monitors!(nodes[0], 1);
1193 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1194 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1197 #[derive(PartialEq)]
1198 enum InterceptTest {
1205 fn test_trivial_inflight_htlc_tracking(){
1206 // In this test, we test three scenarios:
1207 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1208 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1209 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1210 let chanmon_cfgs = create_chanmon_cfgs(3);
1211 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1212 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1213 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1215 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1216 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1218 // Send and claim the payment. Inflight HTLCs should be empty.
1219 let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1220 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1222 let mut node_0_per_peer_lock;
1223 let mut node_0_peer_state_lock;
1224 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1226 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1227 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1228 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1229 channel_1.get_short_channel_id().unwrap()
1231 assert_eq!(chan_1_used_liquidity, None);
1234 let mut node_1_per_peer_lock;
1235 let mut node_1_peer_state_lock;
1236 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1238 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1239 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1240 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1241 channel_2.get_short_channel_id().unwrap()
1244 assert_eq!(chan_2_used_liquidity, None);
1246 let pending_payments = nodes[0].node.list_recent_payments();
1247 assert_eq!(pending_payments.len(), 1);
1248 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1250 // Remove fulfilled payment
1251 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1252 nodes[0].node.timer_tick_occurred();
1255 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1256 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1257 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1259 let mut node_0_per_peer_lock;
1260 let mut node_0_peer_state_lock;
1261 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1263 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1264 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1265 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1266 channel_1.get_short_channel_id().unwrap()
1268 // First hop accounts for expected 1000 msat fee
1269 assert_eq!(chan_1_used_liquidity, Some(501000));
1272 let mut node_1_per_peer_lock;
1273 let mut node_1_peer_state_lock;
1274 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1276 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1277 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1278 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1279 channel_2.get_short_channel_id().unwrap()
1282 assert_eq!(chan_2_used_liquidity, Some(500000));
1284 let pending_payments = nodes[0].node.list_recent_payments();
1285 assert_eq!(pending_payments.len(), 1);
1286 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1288 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1289 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1291 // Remove fulfilled payment
1292 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1293 nodes[0].node.timer_tick_occurred();
1296 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1298 let mut node_0_per_peer_lock;
1299 let mut node_0_peer_state_lock;
1300 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1302 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1303 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1304 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1305 channel_1.get_short_channel_id().unwrap()
1307 assert_eq!(chan_1_used_liquidity, None);
1310 let mut node_1_per_peer_lock;
1311 let mut node_1_peer_state_lock;
1312 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1314 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1315 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1316 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1317 channel_2.get_short_channel_id().unwrap()
1319 assert_eq!(chan_2_used_liquidity, None);
1322 let pending_payments = nodes[0].node.list_recent_payments();
1323 assert_eq!(pending_payments.len(), 0);
1327 fn test_holding_cell_inflight_htlcs() {
1328 let chanmon_cfgs = create_chanmon_cfgs(2);
1329 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1330 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1331 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1332 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1334 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1335 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1337 // Queue up two payments - one will be delivered right away, one immediately goes into the
1338 // holding cell as nodes[0] is AwaitingRAA.
1340 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1341 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1342 check_added_monitors!(nodes[0], 1);
1343 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1344 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1345 check_added_monitors!(nodes[0], 0);
1348 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1351 let mut node_0_per_peer_lock;
1352 let mut node_0_peer_state_lock;
1353 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1355 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1356 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1357 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1358 channel.get_short_channel_id().unwrap()
1361 assert_eq!(used_liquidity, Some(2000000));
1364 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1365 nodes[0].node.get_and_clear_pending_msg_events();
1369 fn intercepted_payment() {
1370 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1371 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1372 // payment or (b) fail the payment.
1373 do_test_intercepted_payment(InterceptTest::Forward);
1374 do_test_intercepted_payment(InterceptTest::Fail);
1375 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1376 do_test_intercepted_payment(InterceptTest::Timeout);
1379 fn do_test_intercepted_payment(test: InterceptTest) {
1380 let chanmon_cfgs = create_chanmon_cfgs(3);
1381 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1383 let mut zero_conf_chan_config = test_default_channel_config();
1384 zero_conf_chan_config.manually_accept_inbound_channels = true;
1385 let mut intercept_forwards_config = test_default_channel_config();
1386 intercept_forwards_config.accept_intercept_htlcs = true;
1387 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1389 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1390 let scorer = test_utils::TestScorer::new();
1391 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1393 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1395 let amt_msat = 100_000;
1396 let intercept_scid = nodes[1].node.get_intercept_scid();
1397 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1398 .with_route_hints(vec![
1399 RouteHint(vec![RouteHintHop {
1400 src_node_id: nodes[1].node.get_our_node_id(),
1401 short_channel_id: intercept_scid,
1404 proportional_millionths: 0,
1406 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1407 htlc_minimum_msat: None,
1408 htlc_maximum_msat: None,
1411 .with_features(nodes[2].node.invoice_features());
1412 let route_params = RouteParameters {
1414 final_value_msat: amt_msat,
1416 let route = get_route(
1417 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1418 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1419 route_params.payment_params.final_cltv_expiry_delta, nodes[0].logger, &scorer,
1423 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1424 nodes[0].node.send_payment_with_route(&route, payment_hash,
1425 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1426 let payment_event = {
1428 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1429 assert_eq!(added_monitors.len(), 1);
1430 added_monitors.clear();
1432 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1433 assert_eq!(events.len(), 1);
1434 SendEvent::from_event(events.remove(0))
1436 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1437 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1439 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1440 let events = nodes[1].node.get_and_clear_pending_events();
1441 assert_eq!(events.len(), 1);
1442 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1443 crate::events::Event::HTLCIntercepted {
1444 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1446 assert_eq!(pmt_hash, payment_hash);
1447 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1448 assert_eq!(short_channel_id, intercept_scid);
1449 (intercept_id, expected_outbound_amount_msat)
1454 // Check for unknown channel id error.
1455 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();
1456 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()) });
1458 if test == InterceptTest::Fail {
1459 // Ensure we can fail the intercepted payment back.
1460 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1461 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1462 nodes[1].node.process_pending_htlc_forwards();
1463 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1464 check_added_monitors!(&nodes[1], 1);
1465 assert!(update_fail.update_fail_htlcs.len() == 1);
1466 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1467 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1468 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1470 // Ensure the payment fails with the expected error.
1471 let fail_conditions = PaymentFailedConditions::new()
1472 .blamed_scid(intercept_scid)
1473 .blamed_chan_closed(true)
1474 .expected_htlc_error_data(0x4000 | 10, &[]);
1475 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1476 } else if test == InterceptTest::Forward {
1477 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1478 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1479 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();
1480 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1481 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1483 // Open the just-in-time channel so the payment can then be forwarded.
1484 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1486 // Finally, forward the intercepted payment through and claim it.
1487 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1488 expect_pending_htlcs_forwardable!(nodes[1]);
1490 let payment_event = {
1492 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1493 assert_eq!(added_monitors.len(), 1);
1494 added_monitors.clear();
1496 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1497 assert_eq!(events.len(), 1);
1498 SendEvent::from_event(events.remove(0))
1500 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1501 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1502 expect_pending_htlcs_forwardable!(nodes[2]);
1504 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1505 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1506 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1507 let events = nodes[0].node.get_and_clear_pending_events();
1508 assert_eq!(events.len(), 2);
1510 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1511 assert_eq!(payment_preimage, *ev_preimage);
1512 assert_eq!(payment_hash, *ev_hash);
1513 assert_eq!(fee_paid_msat, &Some(1000));
1515 _ => panic!("Unexpected event")
1518 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1519 assert_eq!(hash, Some(payment_hash));
1521 _ => panic!("Unexpected event")
1523 } else if test == InterceptTest::Timeout {
1524 let mut block = Block {
1525 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1528 connect_block(&nodes[0], &block);
1529 connect_block(&nodes[1], &block);
1530 for _ in 0..TEST_FINAL_CLTV {
1531 block.header.prev_blockhash = block.block_hash();
1532 connect_block(&nodes[0], &block);
1533 connect_block(&nodes[1], &block);
1535 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1536 check_added_monitors!(nodes[1], 1);
1537 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1538 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1539 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1540 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1541 assert!(htlc_timeout_updates.update_fee.is_none());
1543 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1544 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1545 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1547 // Check for unknown intercept id error.
1548 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1549 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();
1550 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1551 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1552 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1556 #[derive(PartialEq)]
1567 fn automatic_retries() {
1568 do_automatic_retries(AutoRetry::Success);
1569 do_automatic_retries(AutoRetry::Spontaneous);
1570 do_automatic_retries(AutoRetry::FailAttempts);
1571 do_automatic_retries(AutoRetry::FailTimeout);
1572 do_automatic_retries(AutoRetry::FailOnRestart);
1573 do_automatic_retries(AutoRetry::FailOnRetry);
1575 fn do_automatic_retries(test: AutoRetry) {
1576 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1578 let chanmon_cfgs = create_chanmon_cfgs(3);
1579 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1580 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1583 let new_chain_monitor;
1584 let node_0_deserialized;
1586 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1587 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1588 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1590 // Marshall data to send the payment
1591 #[cfg(feature = "std")]
1592 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1593 #[cfg(not(feature = "std"))]
1594 let payment_expiry_secs = 60 * 60;
1595 let amt_msat = 1000;
1596 let mut invoice_features = InvoiceFeatures::empty();
1597 invoice_features.set_variable_length_onion_required();
1598 invoice_features.set_payment_secret_required();
1599 invoice_features.set_basic_mpp_optional();
1600 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1601 .with_expiry_time(payment_expiry_secs as u64)
1602 .with_features(invoice_features);
1603 let route_params = RouteParameters {
1605 final_value_msat: amt_msat,
1607 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1609 macro_rules! pass_failed_attempt_with_retry_along_path {
1610 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1611 // Send a payment attempt that fails due to lack of liquidity on the second hop
1612 check_added_monitors!(nodes[0], 1);
1613 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1614 let mut update_add = update_0.update_add_htlcs[0].clone();
1615 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1616 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1617 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1618 nodes[1].node.process_pending_htlc_forwards();
1619 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1620 vec![HTLCDestination::NextHopChannel {
1621 node_id: Some(nodes[2].node.get_our_node_id()),
1622 channel_id: $failing_channel_id,
1624 nodes[1].node.process_pending_htlc_forwards();
1625 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1626 check_added_monitors!(&nodes[1], 1);
1627 assert!(update_1.update_fail_htlcs.len() == 1);
1628 let fail_msg = update_1.update_fail_htlcs[0].clone();
1629 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1630 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1632 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1633 let mut events = nodes[0].node.get_and_clear_pending_events();
1634 assert_eq!(events.len(), 2);
1636 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1637 assert_eq!(payment_hash, ev_payment_hash);
1638 assert_eq!(payment_failed_permanently, false);
1640 _ => panic!("Unexpected event"),
1642 if $expect_pending_htlcs_forwardable {
1644 Event::PendingHTLCsForwardable { .. } => {},
1645 _ => panic!("Unexpected event"),
1649 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1650 assert_eq!(payment_hash, ev_payment_hash);
1652 _ => panic!("Unexpected event"),
1658 if test == AutoRetry::Success {
1659 // Test that we can succeed on the first retry.
1660 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1661 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1662 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1664 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1665 // attempt, since the initial second hop channel will be excluded from pathfinding
1666 create_announced_chan_between_nodes(&nodes, 1, 2);
1668 // We retry payments in `process_pending_htlc_forwards`
1669 nodes[0].node.process_pending_htlc_forwards();
1670 check_added_monitors!(nodes[0], 1);
1671 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1672 assert_eq!(msg_events.len(), 1);
1673 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1674 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1675 } else if test == AutoRetry::Spontaneous {
1676 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
1677 RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
1678 Retry::Attempts(1)).unwrap();
1679 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1681 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1682 // attempt, since the initial second hop channel will be excluded from pathfinding
1683 create_announced_chan_between_nodes(&nodes, 1, 2);
1685 // We retry payments in `process_pending_htlc_forwards`
1686 nodes[0].node.process_pending_htlc_forwards();
1687 check_added_monitors!(nodes[0], 1);
1688 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1689 assert_eq!(msg_events.len(), 1);
1690 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1691 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1692 } else if test == AutoRetry::FailAttempts {
1693 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1694 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1695 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1696 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1698 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1699 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1700 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1702 // We retry payments in `process_pending_htlc_forwards`
1703 nodes[0].node.process_pending_htlc_forwards();
1704 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1706 // Ensure we won't retry a second time.
1707 nodes[0].node.process_pending_htlc_forwards();
1708 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1709 assert_eq!(msg_events.len(), 0);
1710 } else if test == AutoRetry::FailTimeout {
1711 #[cfg(not(feature = "no-std"))] {
1712 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1713 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1714 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
1715 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1717 // Advance the time so the second attempt fails due to timeout.
1718 SinceEpoch::advance(Duration::from_secs(61));
1720 // Make sure we don't retry again.
1721 nodes[0].node.process_pending_htlc_forwards();
1722 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1723 assert_eq!(msg_events.len(), 0);
1725 let mut events = nodes[0].node.get_and_clear_pending_events();
1726 assert_eq!(events.len(), 1);
1728 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1729 assert_eq!(payment_hash, *ev_payment_hash);
1730 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1731 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
1733 _ => panic!("Unexpected event"),
1736 } else if test == AutoRetry::FailOnRestart {
1737 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1738 // attempts remaining prior to restart.
1739 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1740 PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1741 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1743 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1744 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1745 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1747 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1748 nodes[0].node.process_pending_htlc_forwards();
1749 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1751 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1752 let node_encoded = nodes[0].node.encode();
1753 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1754 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1756 let mut events = nodes[0].node.get_and_clear_pending_events();
1757 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
1758 // Make sure we don't retry again.
1759 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1760 assert_eq!(msg_events.len(), 0);
1762 let mut events = nodes[0].node.get_and_clear_pending_events();
1763 assert_eq!(events.len(), 1);
1765 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1766 assert_eq!(payment_hash, *ev_payment_hash);
1767 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1768 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
1770 _ => panic!("Unexpected event"),
1772 } else if test == AutoRetry::FailOnRetry {
1773 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1774 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1775 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1777 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1778 // fail to find a route.
1779 nodes[0].node.process_pending_htlc_forwards();
1780 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1781 assert_eq!(msg_events.len(), 0);
1783 let mut events = nodes[0].node.get_and_clear_pending_events();
1784 assert_eq!(events.len(), 1);
1786 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1787 assert_eq!(payment_hash, *ev_payment_hash);
1788 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1789 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
1791 _ => panic!("Unexpected event"),
1797 fn auto_retry_partial_failure() {
1798 // Test that we'll retry appropriately on send partial failure and retry partial failure.
1799 let chanmon_cfgs = create_chanmon_cfgs(2);
1800 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1801 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1802 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1804 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1805 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1806 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1808 // Marshall data to send the payment
1809 let amt_msat = 20_000;
1810 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1811 #[cfg(feature = "std")]
1812 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1813 #[cfg(not(feature = "std"))]
1814 let payment_expiry_secs = 60 * 60;
1815 let mut invoice_features = InvoiceFeatures::empty();
1816 invoice_features.set_variable_length_onion_required();
1817 invoice_features.set_payment_secret_required();
1818 invoice_features.set_basic_mpp_optional();
1819 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1820 .with_expiry_time(payment_expiry_secs as u64)
1821 .with_features(invoice_features);
1822 let route_params = RouteParameters {
1824 final_value_msat: amt_msat,
1827 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1828 // second (for the initial send path2 over chan_2) fails.
1829 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1830 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1831 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1832 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1833 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1834 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1835 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1837 // Configure the initial send, retry1 and retry2's paths.
1838 let send_route = Route {
1841 pubkey: nodes[1].node.get_our_node_id(),
1842 node_features: nodes[1].node.node_features(),
1843 short_channel_id: chan_1_id,
1844 channel_features: nodes[1].node.channel_features(),
1845 fee_msat: amt_msat / 2,
1846 cltv_expiry_delta: 100,
1849 pubkey: nodes[1].node.get_our_node_id(),
1850 node_features: nodes[1].node.node_features(),
1851 short_channel_id: chan_2_id,
1852 channel_features: nodes[1].node.channel_features(),
1853 fee_msat: amt_msat / 2,
1854 cltv_expiry_delta: 100,
1857 payment_params: Some(route_params.payment_params.clone()),
1859 let retry_1_route = Route {
1862 pubkey: nodes[1].node.get_our_node_id(),
1863 node_features: nodes[1].node.node_features(),
1864 short_channel_id: chan_1_id,
1865 channel_features: nodes[1].node.channel_features(),
1866 fee_msat: amt_msat / 4,
1867 cltv_expiry_delta: 100,
1870 pubkey: nodes[1].node.get_our_node_id(),
1871 node_features: nodes[1].node.node_features(),
1872 short_channel_id: chan_3_id,
1873 channel_features: nodes[1].node.channel_features(),
1874 fee_msat: amt_msat / 4,
1875 cltv_expiry_delta: 100,
1878 payment_params: Some(route_params.payment_params.clone()),
1880 let retry_2_route = Route {
1883 pubkey: nodes[1].node.get_our_node_id(),
1884 node_features: nodes[1].node.node_features(),
1885 short_channel_id: chan_1_id,
1886 channel_features: nodes[1].node.channel_features(),
1887 fee_msat: amt_msat / 4,
1888 cltv_expiry_delta: 100,
1891 payment_params: Some(route_params.payment_params.clone()),
1893 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1894 let mut payment_params = route_params.payment_params.clone();
1895 payment_params.previously_failed_channels.push(chan_2_id);
1896 nodes[0].router.expect_find_route(RouteParameters {
1897 payment_params, final_value_msat: amt_msat / 2,
1898 }, Ok(retry_1_route));
1899 let mut payment_params = route_params.payment_params.clone();
1900 payment_params.previously_failed_channels.push(chan_3_id);
1901 nodes[0].router.expect_find_route(RouteParameters {
1902 payment_params, final_value_msat: amt_msat / 4,
1903 }, Ok(retry_2_route));
1905 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1906 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1907 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1908 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1909 assert_eq!(closed_chan_events.len(), 4);
1910 match closed_chan_events[0] {
1911 Event::ChannelClosed { .. } => {},
1912 _ => panic!("Unexpected event"),
1914 match closed_chan_events[1] {
1915 Event::PaymentPathFailed { .. } => {},
1916 _ => panic!("Unexpected event"),
1918 match closed_chan_events[2] {
1919 Event::ChannelClosed { .. } => {},
1920 _ => panic!("Unexpected event"),
1922 match closed_chan_events[3] {
1923 Event::PaymentPathFailed { .. } => {},
1924 _ => panic!("Unexpected event"),
1927 // Pass the first part of the payment along the path.
1928 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1929 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1931 // First message is the first update_add, remaining messages are broadcasting channel updates and
1932 // errors for the permfailed channels
1933 assert_eq!(msg_events.len(), 5);
1934 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1936 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1937 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1938 check_added_monitors!(nodes[1], 1);
1939 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1941 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1942 check_added_monitors!(nodes[0], 1);
1943 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1945 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1946 check_added_monitors!(nodes[0], 1);
1947 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1949 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1950 check_added_monitors!(nodes[1], 1);
1952 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1953 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1954 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1955 check_added_monitors!(nodes[1], 1);
1956 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1958 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1959 check_added_monitors!(nodes[0], 1);
1961 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
1962 check_added_monitors!(nodes[0], 1);
1963 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1965 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1966 check_added_monitors!(nodes[1], 1);
1968 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1969 nodes[1].node.process_pending_htlc_forwards();
1970 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
1971 nodes[1].node.claim_funds(payment_preimage);
1972 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
1973 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1974 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
1976 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
1977 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
1978 check_added_monitors!(nodes[0], 1);
1979 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1981 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1982 check_added_monitors!(nodes[1], 4);
1983 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1985 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1986 check_added_monitors!(nodes[1], 1);
1987 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1989 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1990 check_added_monitors!(nodes[0], 1);
1992 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
1993 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
1994 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
1995 check_added_monitors!(nodes[0], 1);
1996 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1998 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
1999 check_added_monitors!(nodes[1], 1);
2001 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2002 check_added_monitors!(nodes[1], 1);
2003 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2005 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2006 check_added_monitors!(nodes[0], 1);
2007 expect_payment_sent!(nodes[0], payment_preimage);
2011 fn auto_retry_zero_attempts_send_error() {
2012 let chanmon_cfgs = create_chanmon_cfgs(2);
2013 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2014 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2015 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2017 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2018 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2020 // Marshall data to send the payment
2021 let amt_msat = 20_000;
2022 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2023 #[cfg(feature = "std")]
2024 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2025 #[cfg(not(feature = "std"))]
2026 let payment_expiry_secs = 60 * 60;
2027 let mut invoice_features = InvoiceFeatures::empty();
2028 invoice_features.set_variable_length_onion_required();
2029 invoice_features.set_payment_secret_required();
2030 invoice_features.set_basic_mpp_optional();
2031 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2032 .with_expiry_time(payment_expiry_secs as u64)
2033 .with_features(invoice_features);
2034 let route_params = RouteParameters {
2036 final_value_msat: amt_msat,
2039 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2040 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2041 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2042 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2043 let events = nodes[0].node.get_and_clear_pending_events();
2044 assert_eq!(events.len(), 3);
2045 if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2046 if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2047 if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2048 check_added_monitors!(nodes[0], 2);
2052 fn fails_paying_after_rejected_by_payee() {
2053 let chanmon_cfgs = create_chanmon_cfgs(2);
2054 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2055 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2056 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2058 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2060 // Marshall data to send the payment
2061 let amt_msat = 20_000;
2062 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2063 #[cfg(feature = "std")]
2064 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2065 #[cfg(not(feature = "std"))]
2066 let payment_expiry_secs = 60 * 60;
2067 let mut invoice_features = InvoiceFeatures::empty();
2068 invoice_features.set_variable_length_onion_required();
2069 invoice_features.set_payment_secret_required();
2070 invoice_features.set_basic_mpp_optional();
2071 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2072 .with_expiry_time(payment_expiry_secs as u64)
2073 .with_features(invoice_features);
2074 let route_params = RouteParameters {
2076 final_value_msat: amt_msat,
2079 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2080 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2081 check_added_monitors!(nodes[0], 1);
2082 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2083 assert_eq!(events.len(), 1);
2084 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2085 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2086 check_added_monitors!(nodes[1], 0);
2087 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2088 expect_pending_htlcs_forwardable!(nodes[1]);
2089 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2091 nodes[1].node.fail_htlc_backwards(&payment_hash);
2092 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2093 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2097 fn retry_multi_path_single_failed_payment() {
2098 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2099 let chanmon_cfgs = create_chanmon_cfgs(2);
2100 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2101 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2102 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2104 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2105 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2107 let amt_msat = 100_010_000;
2109 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2110 #[cfg(feature = "std")]
2111 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2112 #[cfg(not(feature = "std"))]
2113 let payment_expiry_secs = 60 * 60;
2114 let mut invoice_features = InvoiceFeatures::empty();
2115 invoice_features.set_variable_length_onion_required();
2116 invoice_features.set_payment_secret_required();
2117 invoice_features.set_basic_mpp_optional();
2118 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2119 .with_expiry_time(payment_expiry_secs as u64)
2120 .with_features(invoice_features);
2121 let route_params = RouteParameters {
2122 payment_params: payment_params.clone(),
2123 final_value_msat: amt_msat,
2126 let chans = nodes[0].node.list_usable_channels();
2127 let mut route = Route {
2130 pubkey: nodes[1].node.get_our_node_id(),
2131 node_features: nodes[1].node.node_features(),
2132 short_channel_id: chans[0].short_channel_id.unwrap(),
2133 channel_features: nodes[1].node.channel_features(),
2135 cltv_expiry_delta: 100,
2138 pubkey: nodes[1].node.get_our_node_id(),
2139 node_features: nodes[1].node.node_features(),
2140 short_channel_id: chans[1].short_channel_id.unwrap(),
2141 channel_features: nodes[1].node.channel_features(),
2142 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2143 cltv_expiry_delta: 100,
2146 payment_params: Some(payment_params),
2148 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2149 // On retry, split the payment across both channels.
2150 route.paths[0][0].fee_msat = 50_000_001;
2151 route.paths[1][0].fee_msat = 50_000_000;
2152 let mut pay_params = route.payment_params.clone().unwrap();
2153 pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2154 nodes[0].router.expect_find_route(RouteParameters {
2155 payment_params: pay_params,
2156 // Note that the second request here requests the amount we originally failed to send,
2157 // not the amount remaining on the full payment, which should be changed.
2158 final_value_msat: 100_000_001,
2159 }, Ok(route.clone()));
2162 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2163 // The initial send attempt, 2 paths
2164 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2165 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2166 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2167 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2168 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2171 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2172 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2173 let events = nodes[0].node.get_and_clear_pending_events();
2174 assert_eq!(events.len(), 1);
2176 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2177 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2178 short_channel_id: Some(expected_scid), .. } =>
2180 assert_eq!(payment_hash, ev_payment_hash);
2181 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2182 assert!(err_msg.contains("max HTLC"));
2184 _ => panic!("Unexpected event"),
2186 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2187 assert_eq!(htlc_msgs.len(), 2);
2188 check_added_monitors!(nodes[0], 2);
2192 fn immediate_retry_on_failure() {
2193 // Tests that we can/will retry immediately after a failure
2194 let chanmon_cfgs = create_chanmon_cfgs(2);
2195 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2196 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2197 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2199 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2200 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2202 let amt_msat = 100_000_001;
2203 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2204 #[cfg(feature = "std")]
2205 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2206 #[cfg(not(feature = "std"))]
2207 let payment_expiry_secs = 60 * 60;
2208 let mut invoice_features = InvoiceFeatures::empty();
2209 invoice_features.set_variable_length_onion_required();
2210 invoice_features.set_payment_secret_required();
2211 invoice_features.set_basic_mpp_optional();
2212 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2213 .with_expiry_time(payment_expiry_secs as u64)
2214 .with_features(invoice_features);
2215 let route_params = RouteParameters {
2217 final_value_msat: amt_msat,
2220 let chans = nodes[0].node.list_usable_channels();
2221 let mut route = Route {
2224 pubkey: nodes[1].node.get_our_node_id(),
2225 node_features: nodes[1].node.node_features(),
2226 short_channel_id: chans[0].short_channel_id.unwrap(),
2227 channel_features: nodes[1].node.channel_features(),
2228 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2229 cltv_expiry_delta: 100,
2232 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2234 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2235 // On retry, split the payment across both channels.
2236 route.paths.push(route.paths[0].clone());
2237 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2238 route.paths[0][0].fee_msat = 50_000_000;
2239 route.paths[1][0].fee_msat = 50_000_001;
2240 let mut pay_params = route_params.payment_params.clone();
2241 pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2242 nodes[0].router.expect_find_route(RouteParameters {
2243 payment_params: pay_params, final_value_msat: amt_msat,
2244 }, Ok(route.clone()));
2246 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2247 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2248 let events = nodes[0].node.get_and_clear_pending_events();
2249 assert_eq!(events.len(), 1);
2251 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2252 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2253 short_channel_id: Some(expected_scid), .. } =>
2255 assert_eq!(payment_hash, ev_payment_hash);
2256 assert_eq!(expected_scid, route.paths[1][0].short_channel_id);
2257 assert!(err_msg.contains("max HTLC"));
2259 _ => panic!("Unexpected event"),
2261 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2262 assert_eq!(htlc_msgs.len(), 2);
2263 check_added_monitors!(nodes[0], 2);
2267 fn no_extra_retries_on_back_to_back_fail() {
2268 // In a previous release, we had a race where we may exceed the payment retry count if we
2269 // get two failures in a row with the second indicating that all paths had failed (this field,
2270 // `all_paths_failed`, has since been removed).
2271 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2272 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2273 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2274 // pending which we will see later. Thus, when we previously removed the retry tracking map
2275 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2276 // retry entry even though more events for the same payment were still pending. This led to
2277 // us retrying a payment again even though we'd already given up on it.
2279 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2280 // is used to remove the payment retry counter entries instead. This tests for the specific
2281 // excess-retry case while also testing `PaymentFailed` generation.
2283 let chanmon_cfgs = create_chanmon_cfgs(3);
2284 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2285 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2286 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2288 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2289 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2291 let amt_msat = 200_000_000;
2292 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2293 #[cfg(feature = "std")]
2294 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2295 #[cfg(not(feature = "std"))]
2296 let payment_expiry_secs = 60 * 60;
2297 let mut invoice_features = InvoiceFeatures::empty();
2298 invoice_features.set_variable_length_onion_required();
2299 invoice_features.set_payment_secret_required();
2300 invoice_features.set_basic_mpp_optional();
2301 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2302 .with_expiry_time(payment_expiry_secs as u64)
2303 .with_features(invoice_features);
2304 let route_params = RouteParameters {
2306 final_value_msat: amt_msat,
2309 let mut route = Route {
2312 pubkey: nodes[1].node.get_our_node_id(),
2313 node_features: nodes[1].node.node_features(),
2314 short_channel_id: chan_1_scid,
2315 channel_features: nodes[1].node.channel_features(),
2316 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2317 cltv_expiry_delta: 100,
2319 pubkey: nodes[2].node.get_our_node_id(),
2320 node_features: nodes[2].node.node_features(),
2321 short_channel_id: chan_2_scid,
2322 channel_features: nodes[2].node.channel_features(),
2323 fee_msat: 100_000_000,
2324 cltv_expiry_delta: 100,
2327 pubkey: nodes[1].node.get_our_node_id(),
2328 node_features: nodes[1].node.node_features(),
2329 short_channel_id: chan_1_scid,
2330 channel_features: nodes[1].node.channel_features(),
2331 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2332 cltv_expiry_delta: 100,
2334 pubkey: nodes[2].node.get_our_node_id(),
2335 node_features: nodes[2].node.node_features(),
2336 short_channel_id: chan_2_scid,
2337 channel_features: nodes[2].node.channel_features(),
2338 fee_msat: 100_000_000,
2339 cltv_expiry_delta: 100,
2342 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2344 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2345 let mut second_payment_params = route_params.payment_params.clone();
2346 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2347 // On retry, we'll only return one path
2348 route.paths.remove(1);
2349 route.paths[0][1].fee_msat = amt_msat;
2350 nodes[0].router.expect_find_route(RouteParameters {
2351 payment_params: second_payment_params,
2352 final_value_msat: amt_msat,
2353 }, Ok(route.clone()));
2355 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2356 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2357 let htlc_updates = SendEvent::from_node(&nodes[0]);
2358 check_added_monitors!(nodes[0], 1);
2359 assert_eq!(htlc_updates.msgs.len(), 1);
2361 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2362 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2363 check_added_monitors!(nodes[1], 1);
2364 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2366 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2367 check_added_monitors!(nodes[0], 1);
2368 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2370 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2371 check_added_monitors!(nodes[0], 1);
2372 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2374 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2375 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2376 check_added_monitors!(nodes[1], 1);
2377 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2379 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2380 check_added_monitors!(nodes[1], 1);
2381 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2383 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2384 check_added_monitors!(nodes[0], 1);
2386 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2387 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2388 check_added_monitors!(nodes[0], 1);
2389 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2391 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2392 check_added_monitors!(nodes[1], 1);
2393 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2395 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2396 check_added_monitors!(nodes[1], 1);
2397 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2399 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2400 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2401 check_added_monitors!(nodes[0], 1);
2403 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2404 check_added_monitors!(nodes[0], 1);
2405 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2407 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2408 check_added_monitors!(nodes[1], 1);
2409 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2410 check_added_monitors!(nodes[1], 1);
2411 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2413 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2414 check_added_monitors!(nodes[0], 1);
2416 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2417 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2420 // Previously, we retried payments in an event consumer, which would retry each
2421 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2422 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2423 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2424 // by adding the `PaymentFailed` event.
2426 // Because we now retry payments as a batch, we simply return a single-path route in the
2427 // second, batched, request, have that fail, ensure the payment was abandoned.
2428 let mut events = nodes[0].node.get_and_clear_pending_events();
2429 assert_eq!(events.len(), 3);
2431 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2432 assert_eq!(payment_hash, ev_payment_hash);
2433 assert_eq!(payment_failed_permanently, false);
2435 _ => panic!("Unexpected event"),
2438 Event::PendingHTLCsForwardable { .. } => {},
2439 _ => panic!("Unexpected event"),
2442 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2443 assert_eq!(payment_hash, ev_payment_hash);
2444 assert_eq!(payment_failed_permanently, false);
2446 _ => panic!("Unexpected event"),
2449 nodes[0].node.process_pending_htlc_forwards();
2450 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2451 check_added_monitors!(nodes[0], 1);
2453 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2454 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2455 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2456 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2457 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2459 let mut events = nodes[0].node.get_and_clear_pending_events();
2460 assert_eq!(events.len(), 2);
2462 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2463 assert_eq!(payment_hash, ev_payment_hash);
2464 assert_eq!(payment_failed_permanently, false);
2466 _ => panic!("Unexpected event"),
2469 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2470 assert_eq!(payment_hash, *ev_payment_hash);
2471 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2472 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2474 _ => panic!("Unexpected event"),
2479 fn test_simple_partial_retry() {
2480 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2481 // full amount of the payment, rather than only the missing amount. Here we simply test for
2482 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2483 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2485 let chanmon_cfgs = create_chanmon_cfgs(3);
2486 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2487 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2488 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2490 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2491 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2493 let amt_msat = 200_000_000;
2494 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2495 #[cfg(feature = "std")]
2496 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2497 #[cfg(not(feature = "std"))]
2498 let payment_expiry_secs = 60 * 60;
2499 let mut invoice_features = InvoiceFeatures::empty();
2500 invoice_features.set_variable_length_onion_required();
2501 invoice_features.set_payment_secret_required();
2502 invoice_features.set_basic_mpp_optional();
2503 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2504 .with_expiry_time(payment_expiry_secs as u64)
2505 .with_features(invoice_features);
2506 let route_params = RouteParameters {
2508 final_value_msat: amt_msat,
2511 let mut route = Route {
2514 pubkey: nodes[1].node.get_our_node_id(),
2515 node_features: nodes[1].node.node_features(),
2516 short_channel_id: chan_1_scid,
2517 channel_features: nodes[1].node.channel_features(),
2518 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2519 cltv_expiry_delta: 100,
2521 pubkey: nodes[2].node.get_our_node_id(),
2522 node_features: nodes[2].node.node_features(),
2523 short_channel_id: chan_2_scid,
2524 channel_features: nodes[2].node.channel_features(),
2525 fee_msat: 100_000_000,
2526 cltv_expiry_delta: 100,
2529 pubkey: nodes[1].node.get_our_node_id(),
2530 node_features: nodes[1].node.node_features(),
2531 short_channel_id: chan_1_scid,
2532 channel_features: nodes[1].node.channel_features(),
2534 cltv_expiry_delta: 100,
2536 pubkey: nodes[2].node.get_our_node_id(),
2537 node_features: nodes[2].node.node_features(),
2538 short_channel_id: chan_2_scid,
2539 channel_features: nodes[2].node.channel_features(),
2540 fee_msat: 100_000_000,
2541 cltv_expiry_delta: 100,
2544 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2546 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2547 let mut second_payment_params = route_params.payment_params.clone();
2548 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2549 // On retry, we'll only be asked for one path (or 100k sats)
2550 route.paths.remove(0);
2551 nodes[0].router.expect_find_route(RouteParameters {
2552 payment_params: second_payment_params,
2553 final_value_msat: amt_msat / 2,
2554 }, Ok(route.clone()));
2556 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2557 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2558 let htlc_updates = SendEvent::from_node(&nodes[0]);
2559 check_added_monitors!(nodes[0], 1);
2560 assert_eq!(htlc_updates.msgs.len(), 1);
2562 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2563 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2564 check_added_monitors!(nodes[1], 1);
2565 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2567 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2568 check_added_monitors!(nodes[0], 1);
2569 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2571 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2572 check_added_monitors!(nodes[0], 1);
2573 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2575 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2576 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2577 check_added_monitors!(nodes[1], 1);
2578 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2580 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2581 check_added_monitors!(nodes[1], 1);
2582 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2584 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2585 check_added_monitors!(nodes[0], 1);
2587 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2588 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2589 check_added_monitors!(nodes[0], 1);
2590 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2592 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2593 check_added_monitors!(nodes[1], 1);
2595 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2596 check_added_monitors!(nodes[1], 1);
2598 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2600 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2601 check_added_monitors!(nodes[0], 1);
2603 let mut events = nodes[0].node.get_and_clear_pending_events();
2604 assert_eq!(events.len(), 2);
2606 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2607 assert_eq!(payment_hash, ev_payment_hash);
2608 assert_eq!(payment_failed_permanently, false);
2610 _ => panic!("Unexpected event"),
2613 Event::PendingHTLCsForwardable { .. } => {},
2614 _ => panic!("Unexpected event"),
2617 nodes[0].node.process_pending_htlc_forwards();
2618 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2619 check_added_monitors!(nodes[0], 1);
2621 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2622 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2624 expect_pending_htlcs_forwardable!(nodes[1]);
2625 check_added_monitors!(nodes[1], 1);
2627 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2628 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2629 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2630 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2632 expect_pending_htlcs_forwardable!(nodes[2]);
2633 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2637 #[cfg(feature = "std")]
2638 fn test_threaded_payment_retries() {
2639 // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2640 // a single thread and would happily let multiple threads run retries at the same time. Because
2641 // retries are done by first calculating the amount we need to retry, then dropping the
2642 // relevant lock, then actually sending, we would happily let multiple threads retry the same
2643 // amount at the same time, overpaying our original HTLC!
2644 let chanmon_cfgs = create_chanmon_cfgs(4);
2645 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2646 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2647 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2649 // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2650 // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2651 // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2652 // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2654 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2655 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2656 let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2657 let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2659 let amt_msat = 100_000_000;
2660 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2661 #[cfg(feature = "std")]
2662 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2663 #[cfg(not(feature = "std"))]
2664 let payment_expiry_secs = 60 * 60;
2665 let mut invoice_features = InvoiceFeatures::empty();
2666 invoice_features.set_variable_length_onion_required();
2667 invoice_features.set_payment_secret_required();
2668 invoice_features.set_basic_mpp_optional();
2669 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2670 .with_expiry_time(payment_expiry_secs as u64)
2671 .with_features(invoice_features);
2672 let mut route_params = RouteParameters {
2674 final_value_msat: amt_msat,
2677 let mut route = Route {
2680 pubkey: nodes[1].node.get_our_node_id(),
2681 node_features: nodes[1].node.node_features(),
2682 short_channel_id: chan_1_scid,
2683 channel_features: nodes[1].node.channel_features(),
2685 cltv_expiry_delta: 100,
2687 pubkey: nodes[3].node.get_our_node_id(),
2688 node_features: nodes[2].node.node_features(),
2689 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2690 channel_features: nodes[2].node.channel_features(),
2691 fee_msat: amt_msat / 1000,
2692 cltv_expiry_delta: 100,
2695 pubkey: nodes[2].node.get_our_node_id(),
2696 node_features: nodes[2].node.node_features(),
2697 short_channel_id: chan_3_scid,
2698 channel_features: nodes[2].node.channel_features(),
2700 cltv_expiry_delta: 100,
2702 pubkey: nodes[3].node.get_our_node_id(),
2703 node_features: nodes[3].node.node_features(),
2704 short_channel_id: chan_4_scid,
2705 channel_features: nodes[3].node.channel_features(),
2706 fee_msat: amt_msat - amt_msat / 1000,
2707 cltv_expiry_delta: 100,
2710 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2712 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2714 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2715 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
2716 check_added_monitors!(nodes[0], 2);
2717 let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2718 assert_eq!(send_msg_events.len(), 2);
2719 send_msg_events.retain(|msg|
2720 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
2721 // Drop the commitment update for nodes[2], we can just let that one sit pending
2723 *node_id == nodes[1].node.get_our_node_id()
2724 } else { panic!(); }
2727 // from here on out, the retry `RouteParameters` amount will be amt/1000
2728 route_params.final_value_msat /= 1000;
2731 let end_time = Instant::now() + Duration::from_secs(1);
2732 macro_rules! thread_body { () => { {
2733 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
2734 let node_ref = NodePtr::from_node(&nodes[0]);
2736 let node_a = unsafe { &*node_ref.0 };
2737 while Instant::now() < end_time {
2738 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2739 // Ignore if we have any pending events, just always pretend we just got a
2740 // PendingHTLCsForwardable
2741 node_a.node.process_pending_htlc_forwards();
2745 let mut threads = Vec::new();
2746 for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
2748 // Back in the main thread, poll pending messages and make sure that we never have more than
2749 // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
2750 // there are HTLC messages shoved in while its running. This allows us to test that we never
2751 // generate an additional update_add_htlc until we've fully failed the first.
2752 let mut previously_failed_channels = Vec::new();
2754 assert_eq!(send_msg_events.len(), 1);
2755 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
2756 assert_eq!(send_event.msgs.len(), 1);
2758 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
2759 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
2761 // Note that we only push one route into `expect_find_route` at a time, because that's all
2762 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
2763 // we should still ultimately fail for the same reason - because we're trying to send too
2764 // many HTLCs at once.
2765 let mut new_route_params = route_params.clone();
2766 previously_failed_channels.push(route.paths[0][1].short_channel_id);
2767 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
2768 route.paths[0][1].short_channel_id += 1;
2769 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
2771 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2772 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
2773 // The "normal" commitment_signed_dance delivers the final RAA and then calls
2774 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
2775 // This races with our other threads which may generate an add-HTLCs commitment update via
2776 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
2777 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
2778 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
2779 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
2781 let cur_time = Instant::now();
2782 if cur_time > end_time {
2783 for thread in threads.drain(..) { thread.join().unwrap(); }
2786 // Make sure we have some events to handle when we go around...
2787 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2788 nodes[0].node.process_pending_htlc_forwards();
2789 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2790 check_added_monitors!(nodes[0], 2);
2792 if cur_time > end_time {
2798 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
2799 // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
2800 // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
2801 // it was last persisted.
2802 let chanmon_cfgs = create_chanmon_cfgs(2);
2803 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2804 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2805 let (persister_a, persister_b, persister_c);
2806 let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
2807 let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
2808 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2810 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2812 let mut nodes_0_serialized = Vec::new();
2813 if !persist_manager_with_payment {
2814 nodes_0_serialized = nodes[0].node.encode();
2817 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2819 if persist_manager_with_payment {
2820 nodes_0_serialized = nodes[0].node.encode();
2823 nodes[1].node.claim_funds(our_payment_preimage);
2824 check_added_monitors!(nodes[1], 1);
2825 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
2827 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2828 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2829 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
2830 check_added_monitors!(nodes[0], 1);
2832 // The ChannelMonitor should always be the latest version, as we're required to persist it
2833 // during the commitment signed handling.
2834 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2835 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
2837 let events = nodes[0].node.get_and_clear_pending_events();
2838 assert_eq!(events.len(), 2);
2839 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
2840 if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
2841 // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
2842 // the double-claim that would otherwise appear at the end of this test.
2843 nodes[0].node.timer_tick_occurred();
2844 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2845 assert_eq!(as_broadcasted_txn.len(), 1);
2847 // Ensure that, even after some time, if we restart we still include *something* in the current
2848 // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
2849 // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
2850 // A naive implementation of the fix here would wipe the pending payments set, causing a
2851 // failure event when we restart.
2852 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2854 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2855 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);
2856 let events = nodes[0].node.get_and_clear_pending_events();
2857 assert!(events.is_empty());
2859 // Ensure that we don't generate any further events even after the channel-closing commitment
2860 // transaction is confirmed on-chain.
2861 confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
2862 for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2864 let events = nodes[0].node.get_and_clear_pending_events();
2865 assert!(events.is_empty());
2867 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2868 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);
2869 let events = nodes[0].node.get_and_clear_pending_events();
2870 assert!(events.is_empty());
2874 fn no_missing_sent_on_midpoint_reload() {
2875 do_no_missing_sent_on_midpoint_reload(false);
2876 do_no_missing_sent_on_midpoint_reload(true);
2879 fn do_claim_from_closed_chan(fail_payment: bool) {
2880 // Previously, LDK would refuse to claim a payment if a channel on which the payment was
2881 // received had been closed between when the HTLC was received and when we went to claim it.
2882 // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
2883 // presumably the sender may retry later. Long ago it also reduced total code in the claim
2886 // However, this doesn't make sense if you're trying to do an atomic swap or some other
2887 // protocol that requires atomicity with some other action - if your money got claimed
2888 // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
2889 // is an over-optimization - there should be a very, very low likelihood that a channel closes
2890 // between when we receive the last HTLC for a payment and the user goes to claim the payment.
2891 // Since we now have code to handle this anyway we should allow it.
2893 // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
2894 // CLTVs on the paths to different value resulting in a different claim deadline.
2895 let chanmon_cfgs = create_chanmon_cfgs(4);
2896 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2897 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2898 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2900 create_announced_chan_between_nodes(&nodes, 0, 1);
2901 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
2902 let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
2903 create_announced_chan_between_nodes(&nodes, 2, 3);
2905 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
2906 let mut route_params = RouteParameters {
2907 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
2908 .with_features(nodes[1].node.invoice_features()),
2909 final_value_msat: 10_000_000,
2911 let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
2912 None, &nodes[0].node.compute_inflight_htlcs()).unwrap();
2913 // Make sure the route is ordered as the B->D path before C->D
2914 route.paths.sort_by(|a, _| if a[0].pubkey == nodes[1].node.get_our_node_id() {
2915 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
2917 // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
2918 // the HTLC is being relayed.
2919 route.paths[0][1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
2920 route.paths[1][1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
2921 let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
2923 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2924 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2925 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
2926 check_added_monitors(&nodes[0], 2);
2927 let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2928 send_msgs.sort_by(|a, _| {
2930 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
2931 let node_b_id = nodes[1].node.get_our_node_id();
2932 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
2935 assert_eq!(send_msgs.len(), 2);
2936 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
2937 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
2938 let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
2939 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
2941 match receive_event.unwrap() {
2942 Event::PaymentClaimable { claim_deadline, .. } => {
2943 assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
2948 // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
2950 connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
2951 - if fail_payment { 0 } else { 2 });
2953 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
2954 // and expire both immediately, though, by connecting another 4 blocks.
2955 let reason = HTLCDestination::FailedPayment { payment_hash };
2956 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
2957 connect_blocks(&nodes[3], 4);
2958 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
2959 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2961 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
2962 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false);
2963 check_closed_broadcast(&nodes[1], 1, true);
2964 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2965 assert_eq!(bs_tx.len(), 1);
2967 mine_transaction(&nodes[3], &bs_tx[0]);
2968 check_added_monitors(&nodes[3], 1);
2969 check_closed_broadcast(&nodes[3], 1, true);
2970 check_closed_event(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false);
2972 nodes[3].node.claim_funds(payment_preimage);
2973 check_added_monitors(&nodes[3], 2);
2974 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
2976 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2977 assert_eq!(ds_tx.len(), 1);
2978 check_spends!(&ds_tx[0], &bs_tx[0]);
2980 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
2981 check_added_monitors(&nodes[1], 1);
2982 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
2984 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
2985 check_added_monitors(&nodes[1], 1);
2986 assert_eq!(bs_claims.len(), 1);
2987 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
2988 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2989 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
2990 } else { panic!(); }
2992 expect_payment_sent!(nodes[0], payment_preimage);
2994 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
2995 assert_eq!(ds_claim_msgs.len(), 1);
2996 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
2997 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2998 let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
2999 check_added_monitors(&nodes[2], 1);
3000 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3001 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3003 } else { panic!(); };
3005 assert_eq!(cs_claim_msgs.len(), 1);
3006 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3007 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3008 commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3009 } else { panic!(); }
3011 expect_payment_path_successful!(nodes[0]);
3016 fn claim_from_closed_chan() {
3017 do_claim_from_closed_chan(true);
3018 do_claim_from_closed_chan(false);