Process background events when taking the total_consistency_lock
[rust-lightning] / lightning / src / ln / payment_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
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.
13
14 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
15 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::sign::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason};
19 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
20 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails, RecipientOnionFields};
21 use crate::ln::features::InvoiceFeatures;
22 use crate::ln::msgs;
23 use crate::ln::msgs::ChannelMessageHandler;
24 use crate::ln::outbound_payment::Retry;
25 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
26 use crate::routing::router::{get_route, Path, PaymentParameters, Route, Router, RouteHint, RouteHintHop, RouteHop, RouteParameters};
27 use crate::routing::scoring::ChannelUsage;
28 use crate::util::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
31 use crate::util::string::UntrustedString;
32
33 use bitcoin::{Block, BlockHeader, TxMerkleNode};
34 use bitcoin::hashes::Hash;
35 use bitcoin::network::constants::Network;
36
37 use crate::prelude::*;
38
39 use crate::ln::functional_test_utils::*;
40 use crate::routing::gossip::NodeId;
41 #[cfg(feature = "std")]
42 use {
43         crate::util::time::tests::SinceEpoch,
44         std::time::{SystemTime, Instant, Duration}
45 };
46
47 #[test]
48 fn mpp_failure() {
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);
53
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;
58
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].hops[0].pubkey = nodes[1].node.get_our_node_id();
63         route.paths[0].hops[0].short_channel_id = chan_1_id;
64         route.paths[0].hops[1].short_channel_id = chan_3_id;
65         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
66         route.paths[1].hops[0].short_channel_id = chan_2_id;
67         route.paths[1].hops[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);
70 }
71
72 #[test]
73 fn mpp_retry() {
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);
78
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);
83         // Rebalance
84         send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
85
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].hops[0].pubkey = nodes[1].node.get_our_node_id();
91         route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
92         route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
93         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
94         route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
95         route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
96
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,
102         };
103
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);
110
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);
114
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())
125                 },
126                 _ => panic!("Unexpected event"),
127         };
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);
130
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();
143         match events[1] {
144                 Event::PendingHTLCsForwardable { .. } => {},
145                 _ => panic!("Unexpected event")
146         }
147         events.remove(1);
148         expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
149
150         // Rebalance the channel so the second half of the payment can succeed.
151         send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
152
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);
164 }
165
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);
171
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);
176
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].hops[0].pubkey = nodes[1].node.get_our_node_id();
181         route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
182         route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
183         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
184         route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
185         route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
186
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);
193
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);
197
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();
202                 }
203
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);
211
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);
219
220                 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
221         } else {
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);
225
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();
229                 }
230
231                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
232         }
233 }
234
235 #[test]
236 fn mpp_receive_timeout() {
237         do_mpp_receive_timeout(true);
238         do_mpp_receive_timeout(false);
239 }
240
241 #[test]
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);
253
254         create_announced_chan_between_nodes(&nodes, 0, 1);
255
256         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
257
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());
260
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"));
265
266         assert!(!nodes[0].node.has_pending_payments());
267 }
268
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
272         // be retryable.
273         //
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.
277         //
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);
288
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);
291
292         // Serialize the ChannelManager prior to sending payments
293         let nodes_0_serialized = nodes[0].node.encode();
294
295         // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
296         // out and retry.
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,
303         };
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);
307
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());
312
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());
318
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());
323
324         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
325
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();
330         }
331
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);
336
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].txid(), as_commitment_tx.txid());
347         } else {
348                 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
349         }
350         check_added_monitors!(nodes[0], 1);
351
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());
355
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);
363         match as_err[0] {
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);
370                 },
371                 _ => panic!("Unexpected event"),
372         }
373         check_closed_broadcast!(nodes[1], false);
374
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);
380
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);
386
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);
390         }
391
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);
397
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);
402
403         if !confirm_before_reload {
404                 mine_transaction(&nodes[0], &as_commitment_tx);
405         }
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 (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
410                 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
411                 assert_eq!(txn.len(), 2);
412                 (txn.remove(0), txn.remove(0))
413         };
414         check_spends!(first_htlc_timeout_tx, as_commitment_tx);
415         check_spends!(second_htlc_timeout_tx, as_commitment_tx);
416         if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
417                 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
418         } else {
419                 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
420         }
421         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
422         expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
423
424         // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
425         // reloaded) via a route over the new channel, which work without issue and eventually be
426         // received and claimed at the recipient just like any other payment.
427         let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
428
429         // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
430         // and not the original fee. We also update node[1]'s relevant config as
431         // do_claim_payment_along_route expects us to never overpay.
432         {
433                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
434                 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
435                         .unwrap().lock().unwrap();
436                 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
437                 let mut new_config = channel.config();
438                 new_config.forwarding_fee_base_msat += 100_000;
439                 channel.update_config(&new_config);
440                 new_route.paths[0].hops[0].fee_msat += 100_000;
441         }
442
443         // Force expiration of the channel's previous config.
444         for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
445                 nodes[1].node.timer_tick_occurred();
446         }
447
448         assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
449                 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
450         nodes[0].node.send_payment_with_route(&new_route, payment_hash,
451                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
452         check_added_monitors!(nodes[0], 1);
453         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
454         assert_eq!(events.len(), 1);
455         pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
456         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
457         expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
458 }
459
460 #[test]
461 fn retry_with_no_persist() {
462         do_retry_with_no_persist(true);
463         do_retry_with_no_persist(false);
464 }
465
466 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
467         // Test that an off-chain completed payment is not retryable on restart. This was previously
468         // broken for dust payments, but we test for both dust and non-dust payments.
469         //
470         // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
471         // output at all.
472         let chanmon_cfgs = create_chanmon_cfgs(3);
473         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
474
475         let mut manually_accept_config = test_default_channel_config();
476         manually_accept_config.manually_accept_inbound_channels = true;
477
478         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
479
480         let first_persister: test_utils::TestPersister;
481         let first_new_chain_monitor: test_utils::TestChainMonitor;
482         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>;
483         let second_persister: test_utils::TestPersister;
484         let second_new_chain_monitor: test_utils::TestChainMonitor;
485         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>;
486         let third_persister: test_utils::TestPersister;
487         let third_new_chain_monitor: test_utils::TestChainMonitor;
488         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>;
489
490         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
491
492         // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
493         let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
494         confirm_transaction(&nodes[0], &funding_tx);
495         confirm_transaction(&nodes[1], &funding_tx);
496         // Ignore the announcement_signatures messages
497         nodes[0].node.get_and_clear_pending_msg_events();
498         nodes[1].node.get_and_clear_pending_msg_events();
499         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
500
501         // Serialize the ChannelManager prior to sending payments
502         let mut nodes_0_serialized = nodes[0].node.encode();
503
504         let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
505         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 });
506
507         // The ChannelMonitor should always be the latest version, as we're required to persist it
508         // during the `commitment_signed_dance!()`.
509         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
510
511         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);
512         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
513
514         // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
515         // force-close the channel.
516         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
517         nodes[0].node.timer_tick_occurred();
518         assert!(nodes[0].node.list_channels().is_empty());
519         assert!(nodes[0].node.has_pending_payments());
520         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
521         check_added_monitors!(nodes[0], 1);
522
523         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();
524         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
525
526         // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
527         // error, as the channel has hit the chain.
528         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();
529         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
530         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
531         let as_err = nodes[0].node.get_and_clear_pending_msg_events();
532         assert_eq!(as_err.len(), 1);
533         let bs_commitment_tx;
534         match as_err[0] {
535                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
536                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
537                         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
538                         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())) });
539                         check_added_monitors!(nodes[1], 1);
540                         bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
541                 },
542                 _ => panic!("Unexpected event"),
543         }
544         check_closed_broadcast!(nodes[1], false);
545
546         // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
547         // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
548         // incoming HTLCs with the same payment hash later.
549         nodes[2].node.fail_htlc_backwards(&payment_hash);
550         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
551         check_added_monitors!(nodes[2], 1);
552
553         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
554         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
555         commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
556         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
557                 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
558
559         // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
560         // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
561         // after the commitment transaction, so always connect the commitment transaction.
562         mine_transaction(&nodes[0], &bs_commitment_tx[0]);
563         mine_transaction(&nodes[1], &bs_commitment_tx[0]);
564         if !use_dust {
565                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
566                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + (MIN_CLTV_EXPIRY_DELTA as u32));
567                 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
568                 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
569                 assert_eq!(as_htlc_timeout.len(), 1);
570
571                 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
572                 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
573                 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
574                 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
575         }
576
577         // Create a new channel on which to retry the payment before we fail the payment via the
578         // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
579         // connecting several blocks while creating the channel (implying time has passed).
580         // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
581         let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
582         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
583
584         // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
585         // confirming, we will fail as it's considered still-pending...
586         let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
587         match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
588                 Err(PaymentSendFailure::DuplicatePayment) => {},
589                 _ => panic!("Unexpected error")
590         }
591         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
592
593         // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
594         // again. We serialize the node first as we'll then test retrying the HTLC after a restart
595         // (which should also still work).
596         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
597         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
598         expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
599
600         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
601         let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
602         nodes_0_serialized = nodes[0].node.encode();
603
604         // After the payment failed, we're free to send it again.
605         assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
606                 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
607         assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
608
609         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);
610         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
611
612         nodes[0].node.test_process_background_events();
613         check_added_monitors(&nodes[0], 1);
614
615         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
616
617         // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
618         // the payment is not (spuriously) listed as still pending.
619         assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
620                 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
621         check_added_monitors!(nodes[0], 1);
622         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
623         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
624
625         match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
626                 Err(PaymentSendFailure::DuplicatePayment) => {},
627                 _ => panic!("Unexpected error")
628         }
629         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
630
631         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
632         let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
633         nodes_0_serialized = nodes[0].node.encode();
634
635         // Check that after reload we can send the payment again (though we shouldn't, since it was
636         // claimed previously).
637         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);
638         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
639
640         nodes[0].node.test_process_background_events();
641         check_added_monitors(&nodes[0], 1);
642
643         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
644
645         match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
646                 Err(PaymentSendFailure::DuplicatePayment) => {},
647                 _ => panic!("Unexpected error")
648         }
649         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
650 }
651
652 #[test]
653 fn test_completed_payment_not_retryable_on_reload() {
654         do_test_completed_payment_not_retryable_on_reload(true);
655         do_test_completed_payment_not_retryable_on_reload(false);
656 }
657
658
659 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
660         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
661         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
662         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
663         // the ChannelMonitor tells it to.
664         //
665         // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
666         // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
667         // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
668         let chanmon_cfgs = create_chanmon_cfgs(2);
669         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
670         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
671         let persister: test_utils::TestPersister;
672         let new_chain_monitor: test_utils::TestChainMonitor;
673         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>;
674         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
675
676         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
677
678         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
679         // nodes[0].
680         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
681         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
682         check_closed_broadcast!(nodes[0], true);
683         check_added_monitors!(nodes[0], 1);
684         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
685
686         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
687         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
688
689         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
690         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
691         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
692         assert_eq!(node_txn.len(), 3);
693         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
694         check_spends!(node_txn[1], funding_tx);
695         check_spends!(node_txn[2], node_txn[1]);
696         let timeout_txn = vec![node_txn[2].clone()];
697
698         nodes[1].node.claim_funds(payment_preimage);
699         check_added_monitors!(nodes[1], 1);
700         expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
701
702         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
703         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
704         check_closed_broadcast!(nodes[1], true);
705         check_added_monitors!(nodes[1], 1);
706         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
707         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
708         assert_eq!(claim_txn.len(), 1);
709         check_spends!(claim_txn[0], node_txn[1]);
710
711         header.prev_blockhash = nodes[0].best_block_hash();
712         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
713
714         if confirm_commitment_tx {
715                 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
716         }
717
718         header.prev_blockhash = nodes[0].best_block_hash();
719         let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
720
721         if payment_timeout {
722                 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
723                 connect_block(&nodes[0], &claim_block);
724                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
725         }
726
727         // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
728         // returning InProgress. This should cause the claim event to never make its way to the
729         // ChannelManager.
730         chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
731         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
732
733         if payment_timeout {
734                 connect_blocks(&nodes[0], 1);
735         } else {
736                 connect_block(&nodes[0], &claim_block);
737         }
738
739         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
740         let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
741                 .get_mut(&funding_txo).unwrap().drain().collect();
742         // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
743         // If we're testing connection idempotency we may get substantially more.
744         assert!(mon_updates.len() >= 1);
745         assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
746         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
747
748         // If we persist the ChannelManager here, we should get the PaymentSent event after
749         // deserialization.
750         let mut chan_manager_serialized = Vec::new();
751         if !persist_manager_post_event {
752                 chan_manager_serialized = nodes[0].node.encode();
753         }
754
755         // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
756         // payment sent event.
757         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
758         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
759         for update in mon_updates {
760                 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
761         }
762         if payment_timeout {
763                 expect_payment_failed!(nodes[0], payment_hash, false);
764         } else {
765                 expect_payment_sent!(nodes[0], payment_preimage);
766         }
767
768         // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
769         // twice.
770         if persist_manager_post_event {
771                 chan_manager_serialized = nodes[0].node.encode();
772         }
773
774         // Now reload nodes[0]...
775         reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
776
777         if persist_manager_post_event {
778                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
779         } else if payment_timeout {
780                 expect_payment_failed!(nodes[0], payment_hash, false);
781         } else {
782                 expect_payment_sent!(nodes[0], payment_preimage);
783         }
784
785         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
786         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
787         // payment events should kick in, leaving us with no pending events here.
788         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
789         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
790         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
791         check_added_monitors(&nodes[0], 1);
792 }
793
794 #[test]
795 fn test_dup_htlc_onchain_fails_on_reload() {
796         do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
797         do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
798         do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
799         do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
800         do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
801         do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
802 }
803
804 #[test]
805 fn test_fulfill_restart_failure() {
806         // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
807         // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
808         // again, or fail it, giving us free money.
809         //
810         // Of course probably they won't fail it and give us free money, but because we have code to
811         // handle it, we should test the logic for it anyway. We do that here.
812         let chanmon_cfgs = create_chanmon_cfgs(2);
813         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
814         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
815         let persister: test_utils::TestPersister;
816         let new_chain_monitor: test_utils::TestChainMonitor;
817         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>;
818         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
819
820         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
821         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
822
823         // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
824         // pre-fulfill, which we do by serializing it here.
825         let chan_manager_serialized = nodes[1].node.encode();
826         let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
827
828         nodes[1].node.claim_funds(payment_preimage);
829         check_added_monitors!(nodes[1], 1);
830         expect_payment_claimed!(nodes[1], payment_hash, 100_000);
831
832         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
833         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
834         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
835
836         // Now reload nodes[1]...
837         reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
838
839         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
840         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
841
842         nodes[1].node.fail_htlc_backwards(&payment_hash);
843         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
844         check_added_monitors!(nodes[1], 1);
845         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
846         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
847         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
848         // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
849         // it had already considered the payment fulfilled, and now they just got free money.
850         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
851 }
852
853 #[test]
854 fn get_ldk_payment_preimage() {
855         // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
856         let chanmon_cfgs = create_chanmon_cfgs(2);
857         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
858         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
859         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
860         create_announced_chan_between_nodes(&nodes, 0, 1);
861
862         let amt_msat = 60_000;
863         let expiry_secs = 60 * 60;
864         let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
865
866         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
867                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
868         let scorer = test_utils::TestScorer::new();
869         let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
870         let random_seed_bytes = keys_manager.get_secure_random_bytes();
871         let route = get_route(
872                 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
873                 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
874                 amt_msat, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
875         nodes[0].node.send_payment_with_route(&route, payment_hash,
876                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
877         check_added_monitors!(nodes[0], 1);
878
879         // Make sure to use `get_payment_preimage`
880         let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
881         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
882         assert_eq!(events.len(), 1);
883         pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
884         claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
885 }
886
887 #[test]
888 fn sent_probe_is_probe_of_sending_node() {
889         let chanmon_cfgs = create_chanmon_cfgs(3);
890         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
891         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
892         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
893
894         create_announced_chan_between_nodes(&nodes, 0, 1);
895         create_announced_chan_between_nodes(&nodes, 1, 2);
896
897         // First check we refuse to build a single-hop probe
898         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
899         assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
900
901         // Then build an actual two-hop probing path
902         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
903
904         match nodes[0].node.send_probe(route.paths[0].clone()) {
905                 Ok((payment_hash, payment_id)) => {
906                         assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
907                         assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
908                         assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
909                 },
910                 _ => panic!(),
911         }
912
913         get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
914         check_added_monitors!(nodes[0], 1);
915 }
916
917 #[test]
918 fn successful_probe_yields_event() {
919         let chanmon_cfgs = create_chanmon_cfgs(3);
920         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
921         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
922         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
923
924         create_announced_chan_between_nodes(&nodes, 0, 1);
925         create_announced_chan_between_nodes(&nodes, 1, 2);
926
927         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
928
929         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
930
931         // node[0] -- update_add_htlcs -> node[1]
932         check_added_monitors!(nodes[0], 1);
933         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
934         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
935         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
936         check_added_monitors!(nodes[1], 0);
937         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
938         expect_pending_htlcs_forwardable!(nodes[1]);
939
940         // node[1] -- update_add_htlcs -> node[2]
941         check_added_monitors!(nodes[1], 1);
942         let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
943         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
944         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
945         check_added_monitors!(nodes[2], 0);
946         commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
947
948         // node[1] <- update_fail_htlcs -- node[2]
949         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
950         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
951         check_added_monitors!(nodes[1], 0);
952         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
953
954         // node[0] <- update_fail_htlcs -- node[1]
955         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
956         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
957         check_added_monitors!(nodes[0], 0);
958         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
959
960         let mut events = nodes[0].node.get_and_clear_pending_events();
961         assert_eq!(events.len(), 1);
962         match events.drain(..).next().unwrap() {
963                 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
964                         assert_eq!(payment_id, ev_pid);
965                         assert_eq!(payment_hash, ev_ph);
966                 },
967                 _ => panic!(),
968         };
969         assert!(!nodes[0].node.has_pending_payments());
970 }
971
972 #[test]
973 fn failed_probe_yields_event() {
974         let chanmon_cfgs = create_chanmon_cfgs(3);
975         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
976         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
977         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
978
979         create_announced_chan_between_nodes(&nodes, 0, 1);
980         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
981
982         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
983
984         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000);
985
986         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
987
988         // node[0] -- update_add_htlcs -> node[1]
989         check_added_monitors!(nodes[0], 1);
990         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
991         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
992         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
993         check_added_monitors!(nodes[1], 0);
994         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
995         expect_pending_htlcs_forwardable!(nodes[1]);
996
997         // node[0] <- update_fail_htlcs -- node[1]
998         check_added_monitors!(nodes[1], 1);
999         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1000         // Skip the PendingHTLCsForwardable event
1001         let _events = nodes[1].node.get_and_clear_pending_events();
1002         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1003         check_added_monitors!(nodes[0], 0);
1004         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1005
1006         let mut events = nodes[0].node.get_and_clear_pending_events();
1007         assert_eq!(events.len(), 1);
1008         match events.drain(..).next().unwrap() {
1009                 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1010                         assert_eq!(payment_id, ev_pid);
1011                         assert_eq!(payment_hash, ev_ph);
1012                 },
1013                 _ => panic!(),
1014         };
1015         assert!(!nodes[0].node.has_pending_payments());
1016 }
1017
1018 #[test]
1019 fn onchain_failed_probe_yields_event() {
1020         // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1021         // event.
1022         let chanmon_cfgs = create_chanmon_cfgs(3);
1023         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1024         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1025         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1026
1027         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1028         create_announced_chan_between_nodes(&nodes, 1, 2);
1029
1030         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1031
1032         // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1033         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000);
1034         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1035
1036         // node[0] -- update_add_htlcs -> node[1]
1037         check_added_monitors!(nodes[0], 1);
1038         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1039         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1040         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1041         check_added_monitors!(nodes[1], 0);
1042         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1043         expect_pending_htlcs_forwardable!(nodes[1]);
1044
1045         check_added_monitors!(nodes[1], 1);
1046         let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1047
1048         // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1049         // Node A, which after 6 confirmations should result in a probe failure event.
1050         let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1051         confirm_transaction(&nodes[0], &bs_txn[0]);
1052         check_closed_broadcast!(&nodes[0], true);
1053         check_added_monitors!(nodes[0], 1);
1054
1055         let mut events = nodes[0].node.get_and_clear_pending_events();
1056         assert_eq!(events.len(), 2);
1057         let mut found_probe_failed = false;
1058         for event in events.drain(..) {
1059                 match event {
1060                         Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1061                                 assert_eq!(payment_id, ev_pid);
1062                                 assert_eq!(payment_hash, ev_ph);
1063                                 found_probe_failed = true;
1064                         },
1065                         Event::ChannelClosed { .. } => {},
1066                         _ => panic!(),
1067                 }
1068         }
1069         assert!(found_probe_failed);
1070         assert!(!nodes[0].node.has_pending_payments());
1071 }
1072
1073 #[test]
1074 fn claimed_send_payment_idempotent() {
1075         // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1076         let chanmon_cfgs = create_chanmon_cfgs(2);
1077         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1078         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1079         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1080
1081         create_announced_chan_between_nodes(&nodes, 0, 1).2;
1082
1083         let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1084         let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1085
1086         macro_rules! check_send_rejected {
1087                 () => {
1088                         // If we try to resend a new payment with a different payment_hash but with the same
1089                         // payment_id, it should be rejected.
1090                         let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1091                                 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1092                         match send_result {
1093                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1094                                 _ => panic!("Unexpected send result: {:?}", send_result),
1095                         }
1096
1097                         // Further, if we try to send a spontaneous payment with the same payment_id it should
1098                         // also be rejected.
1099                         let send_result = nodes[0].node.send_spontaneous_payment(
1100                                 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1101                         match send_result {
1102                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1103                                 _ => panic!("Unexpected send result: {:?}", send_result),
1104                         }
1105                 }
1106         }
1107
1108         check_send_rejected!();
1109
1110         // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1111         // not been seen by the user. At this point, from the user perspective nothing has changed, so
1112         // we must remain just as idempotent as we were before.
1113         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1114
1115         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1116                 nodes[0].node.timer_tick_occurred();
1117         }
1118
1119         check_send_rejected!();
1120
1121         // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1122         // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1123         // the payment complete. However, they could have called `send_payment` while the event was
1124         // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1125         // after the event is handled a duplicate payment should sitll be rejected.
1126         expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1127         check_send_rejected!();
1128
1129         // If relatively little time has passed, a duplicate payment should still fail.
1130         nodes[0].node.timer_tick_occurred();
1131         check_send_rejected!();
1132
1133         // However, after some time has passed (at least more than the one timer tick above), a
1134         // duplicate payment should go through, as ChannelManager should no longer have any remaining
1135         // references to the old payment data.
1136         for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1137                 nodes[0].node.timer_tick_occurred();
1138         }
1139
1140         nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1141                 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1142         check_added_monitors!(nodes[0], 1);
1143         pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1144         claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1145 }
1146
1147 #[test]
1148 fn abandoned_send_payment_idempotent() {
1149         // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1150         // abandon_payment.
1151         let chanmon_cfgs = create_chanmon_cfgs(2);
1152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1154         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1155
1156         create_announced_chan_between_nodes(&nodes, 0, 1).2;
1157
1158         let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1159         let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1160
1161         macro_rules! check_send_rejected {
1162                 () => {
1163                         // If we try to resend a new payment with a different payment_hash but with the same
1164                         // payment_id, it should be rejected.
1165                         let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1166                                 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1167                         match send_result {
1168                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1169                                 _ => panic!("Unexpected send result: {:?}", send_result),
1170                         }
1171
1172                         // Further, if we try to send a spontaneous payment with the same payment_id it should
1173                         // also be rejected.
1174                         let send_result = nodes[0].node.send_spontaneous_payment(
1175                                 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1176                         match send_result {
1177                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1178                                 _ => panic!("Unexpected send result: {:?}", send_result),
1179                         }
1180                 }
1181         }
1182
1183         check_send_rejected!();
1184
1185         nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1186         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1187
1188         // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1189         // PaymentId.
1190         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1191                 nodes[0].node.timer_tick_occurred();
1192         }
1193         check_send_rejected!();
1194
1195         pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1196
1197         // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1198         // failed payment back.
1199         nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1200                 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1201         check_added_monitors!(nodes[0], 1);
1202         pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1203         claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1204 }
1205
1206 #[derive(PartialEq)]
1207 enum InterceptTest {
1208         Forward,
1209         Fail,
1210         Timeout,
1211 }
1212
1213 #[test]
1214 fn test_trivial_inflight_htlc_tracking(){
1215         // In this test, we test three scenarios:
1216         // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1217         // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1218         // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1219         let chanmon_cfgs = create_chanmon_cfgs(3);
1220         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1221         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1222         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1223
1224         let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1225         let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1226
1227         // Send and claim the payment. Inflight HTLCs should be empty.
1228         let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1229         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1230         {
1231                 let mut node_0_per_peer_lock;
1232                 let mut node_0_peer_state_lock;
1233                 let channel_1 =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1234
1235                 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1236                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1237                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1238                         channel_1.get_short_channel_id().unwrap()
1239                 );
1240                 assert_eq!(chan_1_used_liquidity, None);
1241         }
1242         {
1243                 let mut node_1_per_peer_lock;
1244                 let mut node_1_peer_state_lock;
1245                 let channel_2 =  get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1246
1247                 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1248                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1249                         &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1250                         channel_2.get_short_channel_id().unwrap()
1251                 );
1252
1253                 assert_eq!(chan_2_used_liquidity, None);
1254         }
1255         let pending_payments = nodes[0].node.list_recent_payments();
1256         assert_eq!(pending_payments.len(), 1);
1257         assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1258
1259         // Remove fulfilled payment
1260         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1261                 nodes[0].node.timer_tick_occurred();
1262         }
1263
1264         // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1265         let (payment_preimage, payment_hash,  _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1266         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1267         {
1268                 let mut node_0_per_peer_lock;
1269                 let mut node_0_peer_state_lock;
1270                 let channel_1 =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1271
1272                 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1273                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1274                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1275                         channel_1.get_short_channel_id().unwrap()
1276                 );
1277                 // First hop accounts for expected 1000 msat fee
1278                 assert_eq!(chan_1_used_liquidity, Some(501000));
1279         }
1280         {
1281                 let mut node_1_per_peer_lock;
1282                 let mut node_1_peer_state_lock;
1283                 let channel_2 =  get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1284
1285                 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1286                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1287                         &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1288                         channel_2.get_short_channel_id().unwrap()
1289                 );
1290
1291                 assert_eq!(chan_2_used_liquidity, Some(500000));
1292         }
1293         let pending_payments = nodes[0].node.list_recent_payments();
1294         assert_eq!(pending_payments.len(), 1);
1295         assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1296
1297         // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1298         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1299
1300         // Remove fulfilled payment
1301         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1302                 nodes[0].node.timer_tick_occurred();
1303         }
1304
1305         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1306         {
1307                 let mut node_0_per_peer_lock;
1308                 let mut node_0_peer_state_lock;
1309                 let channel_1 =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1310
1311                 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1312                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1313                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1314                         channel_1.get_short_channel_id().unwrap()
1315                 );
1316                 assert_eq!(chan_1_used_liquidity, None);
1317         }
1318         {
1319                 let mut node_1_per_peer_lock;
1320                 let mut node_1_peer_state_lock;
1321                 let channel_2 =  get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1322
1323                 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1324                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1325                         &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1326                         channel_2.get_short_channel_id().unwrap()
1327                 );
1328                 assert_eq!(chan_2_used_liquidity, None);
1329         }
1330
1331         let pending_payments = nodes[0].node.list_recent_payments();
1332         assert_eq!(pending_payments.len(), 0);
1333 }
1334
1335 #[test]
1336 fn test_holding_cell_inflight_htlcs() {
1337         let chanmon_cfgs = create_chanmon_cfgs(2);
1338         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1339         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1340         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1341         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1342
1343         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1344         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1345
1346         // Queue up two payments - one will be delivered right away, one immediately goes into the
1347         // holding cell as nodes[0] is AwaitingRAA.
1348         {
1349                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1350                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1351                 check_added_monitors!(nodes[0], 1);
1352                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1353                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1354                 check_added_monitors!(nodes[0], 0);
1355         }
1356
1357         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1358
1359         {
1360                 let mut node_0_per_peer_lock;
1361                 let mut node_0_peer_state_lock;
1362                 let channel =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1363
1364                 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1365                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1366                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1367                         channel.get_short_channel_id().unwrap()
1368                 );
1369
1370                 assert_eq!(used_liquidity, Some(2000000));
1371         }
1372
1373         // Clear pending events so test doesn't throw a "Had excess message on node..." error
1374         nodes[0].node.get_and_clear_pending_msg_events();
1375 }
1376
1377 #[test]
1378 fn intercepted_payment() {
1379         // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1380         // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1381         // payment or (b) fail the payment.
1382         do_test_intercepted_payment(InterceptTest::Forward);
1383         do_test_intercepted_payment(InterceptTest::Fail);
1384         // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1385         do_test_intercepted_payment(InterceptTest::Timeout);
1386 }
1387
1388 fn do_test_intercepted_payment(test: InterceptTest) {
1389         let chanmon_cfgs = create_chanmon_cfgs(3);
1390         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1391
1392         let mut zero_conf_chan_config = test_default_channel_config();
1393         zero_conf_chan_config.manually_accept_inbound_channels = true;
1394         let mut intercept_forwards_config = test_default_channel_config();
1395         intercept_forwards_config.accept_intercept_htlcs = true;
1396         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1397
1398         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1399         let scorer = test_utils::TestScorer::new();
1400         let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1401
1402         let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1403
1404         let amt_msat = 100_000;
1405         let intercept_scid = nodes[1].node.get_intercept_scid();
1406         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1407                 .with_route_hints(vec![
1408                         RouteHint(vec![RouteHintHop {
1409                                 src_node_id: nodes[1].node.get_our_node_id(),
1410                                 short_channel_id: intercept_scid,
1411                                 fees: RoutingFees {
1412                                         base_msat: 1000,
1413                                         proportional_millionths: 0,
1414                                 },
1415                                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1416                                 htlc_minimum_msat: None,
1417                                 htlc_maximum_msat: None,
1418                         }])
1419                 ]).unwrap()
1420                 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap();
1421         let route_params = RouteParameters {
1422                 payment_params,
1423                 final_value_msat: amt_msat,
1424         };
1425         let route = get_route(
1426                 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1427                 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1428                 nodes[0].logger, &scorer, &random_seed_bytes,
1429         ).unwrap();
1430
1431         let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1432         nodes[0].node.send_payment_with_route(&route, payment_hash,
1433                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1434         let payment_event = {
1435                 {
1436                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1437                         assert_eq!(added_monitors.len(), 1);
1438                         added_monitors.clear();
1439                 }
1440                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1441                 assert_eq!(events.len(), 1);
1442                 SendEvent::from_event(events.remove(0))
1443         };
1444         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1445         commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1446
1447         // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1448         let events = nodes[1].node.get_and_clear_pending_events();
1449         assert_eq!(events.len(), 1);
1450         let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1451                 crate::events::Event::HTLCIntercepted {
1452                         intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1453                 } => {
1454                         assert_eq!(pmt_hash, payment_hash);
1455                         assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1456                         assert_eq!(short_channel_id, intercept_scid);
1457                         (intercept_id, expected_outbound_amount_msat)
1458                 },
1459                 _ => panic!()
1460         };
1461
1462         // Check for unknown channel id error.
1463         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();
1464         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()) });
1465
1466         if test == InterceptTest::Fail {
1467                 // Ensure we can fail the intercepted payment back.
1468                 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1469                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1470                 nodes[1].node.process_pending_htlc_forwards();
1471                 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1472                 check_added_monitors!(&nodes[1], 1);
1473                 assert!(update_fail.update_fail_htlcs.len() == 1);
1474                 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1475                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1476                 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1477
1478                 // Ensure the payment fails with the expected error.
1479                 let fail_conditions = PaymentFailedConditions::new()
1480                         .blamed_scid(intercept_scid)
1481                         .blamed_chan_closed(true)
1482                         .expected_htlc_error_data(0x4000 | 10, &[]);
1483                 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1484         } else if test == InterceptTest::Forward {
1485                 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1486                 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1487                 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();
1488                 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1489                 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1490
1491                 // Open the just-in-time channel so the payment can then be forwarded.
1492                 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1493
1494                 // Finally, forward the intercepted payment through and claim it.
1495                 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1496                 expect_pending_htlcs_forwardable!(nodes[1]);
1497
1498                 let payment_event = {
1499                         {
1500                                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1501                                 assert_eq!(added_monitors.len(), 1);
1502                                 added_monitors.clear();
1503                         }
1504                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1505                         assert_eq!(events.len(), 1);
1506                         SendEvent::from_event(events.remove(0))
1507                 };
1508                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1509                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1510                 expect_pending_htlcs_forwardable!(nodes[2]);
1511
1512                 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1513                 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1514                 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1515                 let events = nodes[0].node.get_and_clear_pending_events();
1516                 assert_eq!(events.len(), 2);
1517                 match events[0] {
1518                         Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1519                                 assert_eq!(payment_preimage, *ev_preimage);
1520                                 assert_eq!(payment_hash, *ev_hash);
1521                                 assert_eq!(fee_paid_msat, &Some(1000));
1522                         },
1523                         _ => panic!("Unexpected event")
1524                 }
1525                 match events[1] {
1526                         Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1527                                 assert_eq!(hash, Some(payment_hash));
1528                         },
1529                         _ => panic!("Unexpected event")
1530                 }
1531         } else if test == InterceptTest::Timeout {
1532                 let mut block = Block {
1533                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1534                         txdata: vec![],
1535                 };
1536                 connect_block(&nodes[0], &block);
1537                 connect_block(&nodes[1], &block);
1538                 for _ in 0..TEST_FINAL_CLTV {
1539                         block.header.prev_blockhash = block.block_hash();
1540                         connect_block(&nodes[0], &block);
1541                         connect_block(&nodes[1], &block);
1542                 }
1543                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1544                 check_added_monitors!(nodes[1], 1);
1545                 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1546                 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1547                 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1548                 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1549                 assert!(htlc_timeout_updates.update_fee.is_none());
1550
1551                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1552                 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1553                 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1554
1555                 // Check for unknown intercept id error.
1556                 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1557                 let unknown_intercept_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1558                 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1559                 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1560                 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1561         }
1562 }
1563
1564 #[derive(PartialEq)]
1565 enum AutoRetry {
1566         Success,
1567         Spontaneous,
1568         FailAttempts,
1569         FailTimeout,
1570         FailOnRestart,
1571         FailOnRetry,
1572 }
1573
1574 #[test]
1575 fn automatic_retries() {
1576         do_automatic_retries(AutoRetry::Success);
1577         do_automatic_retries(AutoRetry::Spontaneous);
1578         do_automatic_retries(AutoRetry::FailAttempts);
1579         do_automatic_retries(AutoRetry::FailTimeout);
1580         do_automatic_retries(AutoRetry::FailOnRestart);
1581         do_automatic_retries(AutoRetry::FailOnRetry);
1582 }
1583 fn do_automatic_retries(test: AutoRetry) {
1584         // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1585         // below.
1586         let chanmon_cfgs = create_chanmon_cfgs(3);
1587         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1588         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1589
1590         let persister;
1591         let new_chain_monitor;
1592         let node_0_deserialized;
1593
1594         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1595         let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1596         let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1597
1598         // Marshall data to send the payment
1599         #[cfg(feature = "std")]
1600         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1601         #[cfg(not(feature = "std"))]
1602         let payment_expiry_secs = 60 * 60;
1603         let amt_msat = 1000;
1604         let mut invoice_features = InvoiceFeatures::empty();
1605         invoice_features.set_variable_length_onion_required();
1606         invoice_features.set_payment_secret_required();
1607         invoice_features.set_basic_mpp_optional();
1608         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1609                 .with_expiry_time(payment_expiry_secs as u64)
1610                 .with_bolt11_features(invoice_features).unwrap();
1611         let route_params = RouteParameters {
1612                 payment_params,
1613                 final_value_msat: amt_msat,
1614         };
1615         let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1616
1617         macro_rules! pass_failed_attempt_with_retry_along_path {
1618                 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1619                         // Send a payment attempt that fails due to lack of liquidity on the second hop
1620                         check_added_monitors!(nodes[0], 1);
1621                         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1622                         let mut update_add = update_0.update_add_htlcs[0].clone();
1623                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1624                         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1625                         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1626                         nodes[1].node.process_pending_htlc_forwards();
1627                         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1628                                 vec![HTLCDestination::NextHopChannel {
1629                                         node_id: Some(nodes[2].node.get_our_node_id()),
1630                                         channel_id: $failing_channel_id,
1631                                 }]);
1632                         nodes[1].node.process_pending_htlc_forwards();
1633                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1634                         check_added_monitors!(&nodes[1], 1);
1635                         assert!(update_1.update_fail_htlcs.len() == 1);
1636                         let fail_msg = update_1.update_fail_htlcs[0].clone();
1637                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1638                         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1639
1640                         // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1641                         let mut events = nodes[0].node.get_and_clear_pending_events();
1642                         assert_eq!(events.len(), 2);
1643                         match events[0] {
1644                                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
1645                                         assert_eq!(payment_hash, ev_payment_hash);
1646                                         assert_eq!(payment_failed_permanently, false);
1647                                 },
1648                                 _ => panic!("Unexpected event"),
1649                         }
1650                         if $expect_pending_htlcs_forwardable {
1651                                 match events[1] {
1652                                         Event::PendingHTLCsForwardable { .. } => {},
1653                                         _ => panic!("Unexpected event"),
1654                                 }
1655                         } else {
1656                                 match events[1] {
1657                                         Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1658                                                 assert_eq!(payment_hash, ev_payment_hash);
1659                                         },
1660                                         _ => panic!("Unexpected event"),
1661                                 }
1662                         }
1663                 }
1664         }
1665
1666         if test == AutoRetry::Success {
1667                 // Test that we can succeed on the first retry.
1668                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1669                         PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1670                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1671
1672                 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1673                 // attempt, since the initial second hop channel will be excluded from pathfinding
1674                 create_announced_chan_between_nodes(&nodes, 1, 2);
1675
1676                 // We retry payments in `process_pending_htlc_forwards`
1677                 nodes[0].node.process_pending_htlc_forwards();
1678                 check_added_monitors!(nodes[0], 1);
1679                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1680                 assert_eq!(msg_events.len(), 1);
1681                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1682                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1683         } else if test == AutoRetry::Spontaneous {
1684                 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
1685                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
1686                         Retry::Attempts(1)).unwrap();
1687                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1688
1689                 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1690                 // attempt, since the initial second hop channel will be excluded from pathfinding
1691                 create_announced_chan_between_nodes(&nodes, 1, 2);
1692
1693                 // We retry payments in `process_pending_htlc_forwards`
1694                 nodes[0].node.process_pending_htlc_forwards();
1695                 check_added_monitors!(nodes[0], 1);
1696                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1697                 assert_eq!(msg_events.len(), 1);
1698                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1699                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1700         } else if test == AutoRetry::FailAttempts {
1701                 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1702                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1703                         PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1704                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1705
1706                 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1707                 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1708                 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1709
1710                 // We retry payments in `process_pending_htlc_forwards`
1711                 nodes[0].node.process_pending_htlc_forwards();
1712                 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1713
1714                 // Ensure we won't retry a second time.
1715                 nodes[0].node.process_pending_htlc_forwards();
1716                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1717                 assert_eq!(msg_events.len(), 0);
1718         } else if test == AutoRetry::FailTimeout {
1719                 #[cfg(not(feature = "no-std"))] {
1720                         // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1721                         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1722                                 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
1723                         pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1724
1725                         // Advance the time so the second attempt fails due to timeout.
1726                         SinceEpoch::advance(Duration::from_secs(61));
1727
1728                         // Make sure we don't retry again.
1729                         nodes[0].node.process_pending_htlc_forwards();
1730                         let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1731                         assert_eq!(msg_events.len(), 0);
1732
1733                         let mut events = nodes[0].node.get_and_clear_pending_events();
1734                         assert_eq!(events.len(), 1);
1735                         match events[0] {
1736                                 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1737                                         assert_eq!(payment_hash, *ev_payment_hash);
1738                                         assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1739                                         assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
1740                                 },
1741                                 _ => panic!("Unexpected event"),
1742                         }
1743                 }
1744         } else if test == AutoRetry::FailOnRestart {
1745                 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1746                 // attempts remaining prior to restart.
1747                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1748                         PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1749                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1750
1751                 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1752                 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1753                 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1754
1755                 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1756                 nodes[0].node.process_pending_htlc_forwards();
1757                 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1758
1759                 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1760                 let node_encoded = nodes[0].node.encode();
1761                 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1762                 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1763
1764                 let mut events = nodes[0].node.get_and_clear_pending_events();
1765                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
1766                 // Make sure we don't retry again.
1767                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1768                 assert_eq!(msg_events.len(), 0);
1769
1770                 let mut events = nodes[0].node.get_and_clear_pending_events();
1771                 assert_eq!(events.len(), 1);
1772                 match events[0] {
1773                         Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1774                                 assert_eq!(payment_hash, *ev_payment_hash);
1775                                 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1776                                 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
1777                         },
1778                         _ => panic!("Unexpected event"),
1779                 }
1780         } else if test == AutoRetry::FailOnRetry {
1781                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1782                         PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1783                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1784
1785                 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1786                 // fail to find a route.
1787                 nodes[0].node.process_pending_htlc_forwards();
1788                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1789                 assert_eq!(msg_events.len(), 0);
1790
1791                 let mut events = nodes[0].node.get_and_clear_pending_events();
1792                 assert_eq!(events.len(), 1);
1793                 match events[0] {
1794                         Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1795                                 assert_eq!(payment_hash, *ev_payment_hash);
1796                                 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1797                                 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
1798                         },
1799                         _ => panic!("Unexpected event"),
1800                 }
1801         }
1802 }
1803
1804 #[test]
1805 fn auto_retry_partial_failure() {
1806         // Test that we'll retry appropriately on send partial failure and retry partial failure.
1807         let chanmon_cfgs = create_chanmon_cfgs(2);
1808         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1809         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1810         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1811
1812         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1813         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1814         let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1815
1816         // Marshall data to send the payment
1817         let amt_msat = 20_000;
1818         let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1819         #[cfg(feature = "std")]
1820         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1821         #[cfg(not(feature = "std"))]
1822         let payment_expiry_secs = 60 * 60;
1823         let mut invoice_features = InvoiceFeatures::empty();
1824         invoice_features.set_variable_length_onion_required();
1825         invoice_features.set_payment_secret_required();
1826         invoice_features.set_basic_mpp_optional();
1827         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1828                 .with_expiry_time(payment_expiry_secs as u64)
1829                 .with_bolt11_features(invoice_features).unwrap();
1830         let route_params = RouteParameters {
1831                 payment_params,
1832                 final_value_msat: amt_msat,
1833         };
1834
1835         // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1836         // second (for the initial send path2 over chan_2) fails.
1837         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1838         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1839         // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1840         // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1841         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1842         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1843         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1844
1845         // Configure the initial send, retry1 and retry2's paths.
1846         let send_route = Route {
1847                 paths: vec![
1848                         Path { hops: vec![RouteHop {
1849                                 pubkey: nodes[1].node.get_our_node_id(),
1850                                 node_features: nodes[1].node.node_features(),
1851                                 short_channel_id: chan_1_id,
1852                                 channel_features: nodes[1].node.channel_features(),
1853                                 fee_msat: amt_msat / 2,
1854                                 cltv_expiry_delta: 100,
1855                         }], blinded_tail: None },
1856                         Path { hops: vec![RouteHop {
1857                                 pubkey: nodes[1].node.get_our_node_id(),
1858                                 node_features: nodes[1].node.node_features(),
1859                                 short_channel_id: chan_2_id,
1860                                 channel_features: nodes[1].node.channel_features(),
1861                                 fee_msat: amt_msat / 2,
1862                                 cltv_expiry_delta: 100,
1863                         }], blinded_tail: None },
1864                 ],
1865                 payment_params: Some(route_params.payment_params.clone()),
1866         };
1867         let retry_1_route = Route {
1868                 paths: vec![
1869                         Path { hops: vec![RouteHop {
1870                                 pubkey: nodes[1].node.get_our_node_id(),
1871                                 node_features: nodes[1].node.node_features(),
1872                                 short_channel_id: chan_1_id,
1873                                 channel_features: nodes[1].node.channel_features(),
1874                                 fee_msat: amt_msat / 4,
1875                                 cltv_expiry_delta: 100,
1876                         }], blinded_tail: None },
1877                         Path { hops: vec![RouteHop {
1878                                 pubkey: nodes[1].node.get_our_node_id(),
1879                                 node_features: nodes[1].node.node_features(),
1880                                 short_channel_id: chan_3_id,
1881                                 channel_features: nodes[1].node.channel_features(),
1882                                 fee_msat: amt_msat / 4,
1883                                 cltv_expiry_delta: 100,
1884                         }], blinded_tail: None },
1885                 ],
1886                 payment_params: Some(route_params.payment_params.clone()),
1887         };
1888         let retry_2_route = Route {
1889                 paths: vec![
1890                         Path { hops: vec![RouteHop {
1891                                 pubkey: nodes[1].node.get_our_node_id(),
1892                                 node_features: nodes[1].node.node_features(),
1893                                 short_channel_id: chan_1_id,
1894                                 channel_features: nodes[1].node.channel_features(),
1895                                 fee_msat: amt_msat / 4,
1896                                 cltv_expiry_delta: 100,
1897                         }], blinded_tail: None },
1898                 ],
1899                 payment_params: Some(route_params.payment_params.clone()),
1900         };
1901         nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1902         let mut payment_params = route_params.payment_params.clone();
1903         payment_params.previously_failed_channels.push(chan_2_id);
1904         nodes[0].router.expect_find_route(RouteParameters {
1905                         payment_params, final_value_msat: amt_msat / 2,
1906                 }, Ok(retry_1_route));
1907         let mut payment_params = route_params.payment_params.clone();
1908         payment_params.previously_failed_channels.push(chan_3_id);
1909         nodes[0].router.expect_find_route(RouteParameters {
1910                         payment_params, final_value_msat: amt_msat / 4,
1911                 }, Ok(retry_2_route));
1912
1913         // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1914         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1915                 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1916         let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1917         assert_eq!(closed_chan_events.len(), 4);
1918         match closed_chan_events[0] {
1919                 Event::ChannelClosed { .. } => {},
1920                 _ => panic!("Unexpected event"),
1921         }
1922         match closed_chan_events[1] {
1923                 Event::PaymentPathFailed { .. } => {},
1924                 _ => panic!("Unexpected event"),
1925         }
1926         match closed_chan_events[2] {
1927                 Event::ChannelClosed { .. } => {},
1928                 _ => panic!("Unexpected event"),
1929         }
1930         match closed_chan_events[3] {
1931                 Event::PaymentPathFailed { .. } => {},
1932                 _ => panic!("Unexpected event"),
1933         }
1934
1935         // Pass the first part of the payment along the path.
1936         check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1937         let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1938
1939         // First message is the first update_add, remaining messages are broadcasting channel updates and
1940         // errors for the permfailed channels
1941         assert_eq!(msg_events.len(), 5);
1942         let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1943
1944         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1945         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1946         check_added_monitors!(nodes[1], 1);
1947         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1948
1949         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1950         check_added_monitors!(nodes[0], 1);
1951         let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1952
1953         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1954         check_added_monitors!(nodes[0], 1);
1955         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1956
1957         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1958         check_added_monitors!(nodes[1], 1);
1959
1960         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1961         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1962         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1963         check_added_monitors!(nodes[1], 1);
1964         let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1965
1966         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1967         check_added_monitors!(nodes[0], 1);
1968
1969         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
1970         check_added_monitors!(nodes[0], 1);
1971         let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1972
1973         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1974         check_added_monitors!(nodes[1], 1);
1975
1976         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1977         nodes[1].node.process_pending_htlc_forwards();
1978         expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
1979         nodes[1].node.claim_funds(payment_preimage);
1980         expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
1981         let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1982         assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
1983
1984         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
1985         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
1986         check_added_monitors!(nodes[0], 1);
1987         let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1988
1989         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1990         check_added_monitors!(nodes[1], 4);
1991         let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1992
1993         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1994         check_added_monitors!(nodes[1], 1);
1995         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1996
1997         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1998         check_added_monitors!(nodes[0], 1);
1999
2000         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
2001         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
2002         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
2003         check_added_monitors!(nodes[0], 1);
2004         let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2005
2006         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2007         check_added_monitors!(nodes[1], 1);
2008
2009         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2010         check_added_monitors!(nodes[1], 1);
2011         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2012
2013         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2014         check_added_monitors!(nodes[0], 1);
2015         expect_payment_sent!(nodes[0], payment_preimage);
2016 }
2017
2018 #[test]
2019 fn auto_retry_zero_attempts_send_error() {
2020         let chanmon_cfgs = create_chanmon_cfgs(2);
2021         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2022         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2023         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2024
2025         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2026         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2027
2028         // Marshall data to send the payment
2029         let amt_msat = 20_000;
2030         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2031         #[cfg(feature = "std")]
2032         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2033         #[cfg(not(feature = "std"))]
2034         let payment_expiry_secs = 60 * 60;
2035         let mut invoice_features = InvoiceFeatures::empty();
2036         invoice_features.set_variable_length_onion_required();
2037         invoice_features.set_payment_secret_required();
2038         invoice_features.set_basic_mpp_optional();
2039         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2040                 .with_expiry_time(payment_expiry_secs as u64)
2041                 .with_bolt11_features(invoice_features).unwrap();
2042         let route_params = RouteParameters {
2043                 payment_params,
2044                 final_value_msat: amt_msat,
2045         };
2046
2047         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2048         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2049                 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2050         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2051         let events = nodes[0].node.get_and_clear_pending_events();
2052         assert_eq!(events.len(), 3);
2053         if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2054         if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2055         if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2056         check_added_monitors!(nodes[0], 2);
2057 }
2058
2059 #[test]
2060 fn fails_paying_after_rejected_by_payee() {
2061         let chanmon_cfgs = create_chanmon_cfgs(2);
2062         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2063         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2064         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2065
2066         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2067
2068         // Marshall data to send the payment
2069         let amt_msat = 20_000;
2070         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2071         #[cfg(feature = "std")]
2072         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2073         #[cfg(not(feature = "std"))]
2074         let payment_expiry_secs = 60 * 60;
2075         let mut invoice_features = InvoiceFeatures::empty();
2076         invoice_features.set_variable_length_onion_required();
2077         invoice_features.set_payment_secret_required();
2078         invoice_features.set_basic_mpp_optional();
2079         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2080                 .with_expiry_time(payment_expiry_secs as u64)
2081                 .with_bolt11_features(invoice_features).unwrap();
2082         let route_params = RouteParameters {
2083                 payment_params,
2084                 final_value_msat: amt_msat,
2085         };
2086
2087         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2088                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2089         check_added_monitors!(nodes[0], 1);
2090         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2091         assert_eq!(events.len(), 1);
2092         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2093         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2094         check_added_monitors!(nodes[1], 0);
2095         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2096         expect_pending_htlcs_forwardable!(nodes[1]);
2097         expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2098
2099         nodes[1].node.fail_htlc_backwards(&payment_hash);
2100         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2101         pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2102 }
2103
2104 #[test]
2105 fn retry_multi_path_single_failed_payment() {
2106         // Tests that we can/will retry after a single path of an MPP payment failed immediately
2107         let chanmon_cfgs = create_chanmon_cfgs(2);
2108         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2109         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2110         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2111
2112         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2113         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2114
2115         let amt_msat = 100_010_000;
2116
2117         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2118         #[cfg(feature = "std")]
2119         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2120         #[cfg(not(feature = "std"))]
2121         let payment_expiry_secs = 60 * 60;
2122         let mut invoice_features = InvoiceFeatures::empty();
2123         invoice_features.set_variable_length_onion_required();
2124         invoice_features.set_payment_secret_required();
2125         invoice_features.set_basic_mpp_optional();
2126         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2127                 .with_expiry_time(payment_expiry_secs as u64)
2128                 .with_bolt11_features(invoice_features).unwrap();
2129         let route_params = RouteParameters {
2130                 payment_params: payment_params.clone(),
2131                 final_value_msat: amt_msat,
2132         };
2133
2134         let chans = nodes[0].node.list_usable_channels();
2135         let mut route = Route {
2136                 paths: vec![
2137                         Path { hops: vec![RouteHop {
2138                                 pubkey: nodes[1].node.get_our_node_id(),
2139                                 node_features: nodes[1].node.node_features(),
2140                                 short_channel_id: chans[0].short_channel_id.unwrap(),
2141                                 channel_features: nodes[1].node.channel_features(),
2142                                 fee_msat: 10_000,
2143                                 cltv_expiry_delta: 100,
2144                         }], blinded_tail: None },
2145                         Path { hops: vec![RouteHop {
2146                                 pubkey: nodes[1].node.get_our_node_id(),
2147                                 node_features: nodes[1].node.node_features(),
2148                                 short_channel_id: chans[1].short_channel_id.unwrap(),
2149                                 channel_features: nodes[1].node.channel_features(),
2150                                 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2151                                 cltv_expiry_delta: 100,
2152                         }], blinded_tail: None },
2153                 ],
2154                 payment_params: Some(payment_params),
2155         };
2156         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2157         // On retry, split the payment across both channels.
2158         route.paths[0].hops[0].fee_msat = 50_000_001;
2159         route.paths[1].hops[0].fee_msat = 50_000_000;
2160         let mut pay_params = route.payment_params.clone().unwrap();
2161         pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2162         nodes[0].router.expect_find_route(RouteParameters {
2163                         payment_params: pay_params,
2164                         // Note that the second request here requests the amount we originally failed to send,
2165                         // not the amount remaining on the full payment, which should be changed.
2166                         final_value_msat: 100_000_001,
2167                 }, Ok(route.clone()));
2168
2169         {
2170                 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2171                 // The initial send attempt, 2 paths
2172                 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2173                 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2174                 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2175                 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2176                 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2177         }
2178
2179         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2180                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2181         let events = nodes[0].node.get_and_clear_pending_events();
2182         assert_eq!(events.len(), 1);
2183         match events[0] {
2184                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2185                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2186                         short_channel_id: Some(expected_scid), .. } =>
2187                 {
2188                         assert_eq!(payment_hash, ev_payment_hash);
2189                         assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2190                         assert!(err_msg.contains("max HTLC"));
2191                 },
2192                 _ => panic!("Unexpected event"),
2193         }
2194         let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2195         assert_eq!(htlc_msgs.len(), 2);
2196         check_added_monitors!(nodes[0], 2);
2197 }
2198
2199 #[test]
2200 fn immediate_retry_on_failure() {
2201         // Tests that we can/will retry immediately after a failure
2202         let chanmon_cfgs = create_chanmon_cfgs(2);
2203         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2204         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2205         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2206
2207         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2208         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2209
2210         let amt_msat = 100_000_001;
2211         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2212         #[cfg(feature = "std")]
2213         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2214         #[cfg(not(feature = "std"))]
2215         let payment_expiry_secs = 60 * 60;
2216         let mut invoice_features = InvoiceFeatures::empty();
2217         invoice_features.set_variable_length_onion_required();
2218         invoice_features.set_payment_secret_required();
2219         invoice_features.set_basic_mpp_optional();
2220         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2221                 .with_expiry_time(payment_expiry_secs as u64)
2222                 .with_bolt11_features(invoice_features).unwrap();
2223         let route_params = RouteParameters {
2224                 payment_params,
2225                 final_value_msat: amt_msat,
2226         };
2227
2228         let chans = nodes[0].node.list_usable_channels();
2229         let mut route = Route {
2230                 paths: vec![
2231                         Path { hops: vec![RouteHop {
2232                                 pubkey: nodes[1].node.get_our_node_id(),
2233                                 node_features: nodes[1].node.node_features(),
2234                                 short_channel_id: chans[0].short_channel_id.unwrap(),
2235                                 channel_features: nodes[1].node.channel_features(),
2236                                 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2237                                 cltv_expiry_delta: 100,
2238                         }], blinded_tail: None },
2239                 ],
2240                 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2241         };
2242         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2243         // On retry, split the payment across both channels.
2244         route.paths.push(route.paths[0].clone());
2245         route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2246         route.paths[0].hops[0].fee_msat = 50_000_000;
2247         route.paths[1].hops[0].fee_msat = 50_000_001;
2248         let mut pay_params = route_params.payment_params.clone();
2249         pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2250         nodes[0].router.expect_find_route(RouteParameters {
2251                         payment_params: pay_params, final_value_msat: amt_msat,
2252                 }, Ok(route.clone()));
2253
2254         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2255                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2256         let events = nodes[0].node.get_and_clear_pending_events();
2257         assert_eq!(events.len(), 1);
2258         match events[0] {
2259                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2260                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2261                         short_channel_id: Some(expected_scid), .. } =>
2262                 {
2263                         assert_eq!(payment_hash, ev_payment_hash);
2264                         assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2265                         assert!(err_msg.contains("max HTLC"));
2266                 },
2267                 _ => panic!("Unexpected event"),
2268         }
2269         let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2270         assert_eq!(htlc_msgs.len(), 2);
2271         check_added_monitors!(nodes[0], 2);
2272 }
2273
2274 #[test]
2275 fn no_extra_retries_on_back_to_back_fail() {
2276         // In a previous release, we had a race where we may exceed the payment retry count if we
2277         // get two failures in a row with the second indicating that all paths had failed (this field,
2278         // `all_paths_failed`, has since been removed).
2279         // Generally, when we give up trying to retry a payment, we don't know for sure what the
2280         // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2281         // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2282         // pending which we will see later. Thus, when we previously removed the retry tracking map
2283         // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2284         // retry entry even though more events for the same payment were still pending. This led to
2285         // us retrying a payment again even though we'd already given up on it.
2286         //
2287         // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2288         // is used to remove the payment retry counter entries instead. This tests for the specific
2289         // excess-retry case while also testing `PaymentFailed` generation.
2290
2291         let chanmon_cfgs = create_chanmon_cfgs(3);
2292         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2293         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2294         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2295
2296         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2297         let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2298
2299         let amt_msat = 200_000_000;
2300         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2301         #[cfg(feature = "std")]
2302         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2303         #[cfg(not(feature = "std"))]
2304         let payment_expiry_secs = 60 * 60;
2305         let mut invoice_features = InvoiceFeatures::empty();
2306         invoice_features.set_variable_length_onion_required();
2307         invoice_features.set_payment_secret_required();
2308         invoice_features.set_basic_mpp_optional();
2309         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2310                 .with_expiry_time(payment_expiry_secs as u64)
2311                 .with_bolt11_features(invoice_features).unwrap();
2312         let route_params = RouteParameters {
2313                 payment_params,
2314                 final_value_msat: amt_msat,
2315         };
2316
2317         let mut route = Route {
2318                 paths: vec![
2319                         Path { hops: vec![RouteHop {
2320                                 pubkey: nodes[1].node.get_our_node_id(),
2321                                 node_features: nodes[1].node.node_features(),
2322                                 short_channel_id: chan_1_scid,
2323                                 channel_features: nodes[1].node.channel_features(),
2324                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2325                                 cltv_expiry_delta: 100,
2326                         }, RouteHop {
2327                                 pubkey: nodes[2].node.get_our_node_id(),
2328                                 node_features: nodes[2].node.node_features(),
2329                                 short_channel_id: chan_2_scid,
2330                                 channel_features: nodes[2].node.channel_features(),
2331                                 fee_msat: 100_000_000,
2332                                 cltv_expiry_delta: 100,
2333                         }], blinded_tail: None },
2334                         Path { hops: vec![RouteHop {
2335                                 pubkey: nodes[1].node.get_our_node_id(),
2336                                 node_features: nodes[1].node.node_features(),
2337                                 short_channel_id: chan_1_scid,
2338                                 channel_features: nodes[1].node.channel_features(),
2339                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2340                                 cltv_expiry_delta: 100,
2341                         }, RouteHop {
2342                                 pubkey: nodes[2].node.get_our_node_id(),
2343                                 node_features: nodes[2].node.node_features(),
2344                                 short_channel_id: chan_2_scid,
2345                                 channel_features: nodes[2].node.channel_features(),
2346                                 fee_msat: 100_000_000,
2347                                 cltv_expiry_delta: 100,
2348                         }], blinded_tail: None }
2349                 ],
2350                 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2351         };
2352         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2353         let mut second_payment_params = route_params.payment_params.clone();
2354         second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2355         // On retry, we'll only return one path
2356         route.paths.remove(1);
2357         route.paths[0].hops[1].fee_msat = amt_msat;
2358         nodes[0].router.expect_find_route(RouteParameters {
2359                         payment_params: second_payment_params,
2360                         final_value_msat: amt_msat,
2361                 }, Ok(route.clone()));
2362
2363         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2364                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2365         let htlc_updates = SendEvent::from_node(&nodes[0]);
2366         check_added_monitors!(nodes[0], 1);
2367         assert_eq!(htlc_updates.msgs.len(), 1);
2368
2369         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2370         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2371         check_added_monitors!(nodes[1], 1);
2372         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2373
2374         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2375         check_added_monitors!(nodes[0], 1);
2376         let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2377
2378         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2379         check_added_monitors!(nodes[0], 1);
2380         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2381
2382         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2383         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2384         check_added_monitors!(nodes[1], 1);
2385         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2386
2387         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2388         check_added_monitors!(nodes[1], 1);
2389         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2390
2391         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2392         check_added_monitors!(nodes[0], 1);
2393
2394         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2395         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2396         check_added_monitors!(nodes[0], 1);
2397         let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2398
2399         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2400         check_added_monitors!(nodes[1], 1);
2401         let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2402
2403         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2404         check_added_monitors!(nodes[1], 1);
2405         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2406
2407         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2408         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2409         check_added_monitors!(nodes[0], 1);
2410
2411         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2412         check_added_monitors!(nodes[0], 1);
2413         let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2414
2415         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2416         check_added_monitors!(nodes[1], 1);
2417         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2418         check_added_monitors!(nodes[1], 1);
2419         let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2420
2421         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2422         check_added_monitors!(nodes[0], 1);
2423
2424         // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2425         // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2426         // with it set.
2427         //
2428         // Previously, we retried payments in an event consumer, which would retry each
2429         // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2430         // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2431         // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2432         // by adding the `PaymentFailed` event.
2433         //
2434         // Because we now retry payments as a batch, we simply return a single-path route in the
2435         // second, batched, request, have that fail, ensure the payment was abandoned.
2436         let mut events = nodes[0].node.get_and_clear_pending_events();
2437         assert_eq!(events.len(), 3);
2438         match events[0] {
2439                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2440                         assert_eq!(payment_hash, ev_payment_hash);
2441                         assert_eq!(payment_failed_permanently, false);
2442                 },
2443                 _ => panic!("Unexpected event"),
2444         }
2445         match events[1] {
2446                 Event::PendingHTLCsForwardable { .. } => {},
2447                 _ => panic!("Unexpected event"),
2448         }
2449         match events[2] {
2450                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2451                         assert_eq!(payment_hash, ev_payment_hash);
2452                         assert_eq!(payment_failed_permanently, false);
2453                 },
2454                 _ => panic!("Unexpected event"),
2455         }
2456
2457         nodes[0].node.process_pending_htlc_forwards();
2458         let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2459         check_added_monitors!(nodes[0], 1);
2460
2461         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2462         commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2463         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2464         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2465         commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2466
2467         let mut events = nodes[0].node.get_and_clear_pending_events();
2468         assert_eq!(events.len(), 2);
2469         match events[0] {
2470                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2471                         assert_eq!(payment_hash, ev_payment_hash);
2472                         assert_eq!(payment_failed_permanently, false);
2473                 },
2474                 _ => panic!("Unexpected event"),
2475         }
2476         match events[1] {
2477                 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2478                         assert_eq!(payment_hash, *ev_payment_hash);
2479                         assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2480                         assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2481                 },
2482                 _ => panic!("Unexpected event"),
2483         }
2484 }
2485
2486 #[test]
2487 fn test_simple_partial_retry() {
2488         // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2489         // full amount of the payment, rather than only the missing amount. Here we simply test for
2490         // this by sending a payment with two parts, failing one, and retrying the second. Note that
2491         // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2492         // request.
2493         let chanmon_cfgs = create_chanmon_cfgs(3);
2494         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2495         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2496         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2497
2498         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2499         let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2500
2501         let amt_msat = 200_000_000;
2502         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2503         #[cfg(feature = "std")]
2504         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2505         #[cfg(not(feature = "std"))]
2506         let payment_expiry_secs = 60 * 60;
2507         let mut invoice_features = InvoiceFeatures::empty();
2508         invoice_features.set_variable_length_onion_required();
2509         invoice_features.set_payment_secret_required();
2510         invoice_features.set_basic_mpp_optional();
2511         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2512                 .with_expiry_time(payment_expiry_secs as u64)
2513                 .with_bolt11_features(invoice_features).unwrap();
2514         let route_params = RouteParameters {
2515                 payment_params,
2516                 final_value_msat: amt_msat,
2517         };
2518
2519         let mut route = Route {
2520                 paths: vec![
2521                         Path { hops: vec![RouteHop {
2522                                 pubkey: nodes[1].node.get_our_node_id(),
2523                                 node_features: nodes[1].node.node_features(),
2524                                 short_channel_id: chan_1_scid,
2525                                 channel_features: nodes[1].node.channel_features(),
2526                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2527                                 cltv_expiry_delta: 100,
2528                         }, RouteHop {
2529                                 pubkey: nodes[2].node.get_our_node_id(),
2530                                 node_features: nodes[2].node.node_features(),
2531                                 short_channel_id: chan_2_scid,
2532                                 channel_features: nodes[2].node.channel_features(),
2533                                 fee_msat: 100_000_000,
2534                                 cltv_expiry_delta: 100,
2535                         }], blinded_tail: None },
2536                         Path { hops: vec![RouteHop {
2537                                 pubkey: nodes[1].node.get_our_node_id(),
2538                                 node_features: nodes[1].node.node_features(),
2539                                 short_channel_id: chan_1_scid,
2540                                 channel_features: nodes[1].node.channel_features(),
2541                                 fee_msat: 100_000,
2542                                 cltv_expiry_delta: 100,
2543                         }, RouteHop {
2544                                 pubkey: nodes[2].node.get_our_node_id(),
2545                                 node_features: nodes[2].node.node_features(),
2546                                 short_channel_id: chan_2_scid,
2547                                 channel_features: nodes[2].node.channel_features(),
2548                                 fee_msat: 100_000_000,
2549                                 cltv_expiry_delta: 100,
2550                         }], blinded_tail: None }
2551                 ],
2552                 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2553         };
2554         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2555         let mut second_payment_params = route_params.payment_params.clone();
2556         second_payment_params.previously_failed_channels = vec![chan_2_scid];
2557         // On retry, we'll only be asked for one path (or 100k sats)
2558         route.paths.remove(0);
2559         nodes[0].router.expect_find_route(RouteParameters {
2560                         payment_params: second_payment_params,
2561                         final_value_msat: amt_msat / 2,
2562                 }, Ok(route.clone()));
2563
2564         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2565                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2566         let htlc_updates = SendEvent::from_node(&nodes[0]);
2567         check_added_monitors!(nodes[0], 1);
2568         assert_eq!(htlc_updates.msgs.len(), 1);
2569
2570         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2571         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2572         check_added_monitors!(nodes[1], 1);
2573         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2574
2575         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2576         check_added_monitors!(nodes[0], 1);
2577         let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2578
2579         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2580         check_added_monitors!(nodes[0], 1);
2581         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2582
2583         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2584         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2585         check_added_monitors!(nodes[1], 1);
2586         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2587
2588         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2589         check_added_monitors!(nodes[1], 1);
2590         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2591
2592         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2593         check_added_monitors!(nodes[0], 1);
2594
2595         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2596         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2597         check_added_monitors!(nodes[0], 1);
2598         let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2599
2600         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2601         check_added_monitors!(nodes[1], 1);
2602
2603         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2604         check_added_monitors!(nodes[1], 1);
2605
2606         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2607
2608         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2609         check_added_monitors!(nodes[0], 1);
2610
2611         let mut events = nodes[0].node.get_and_clear_pending_events();
2612         assert_eq!(events.len(), 2);
2613         match events[0] {
2614                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2615                         assert_eq!(payment_hash, ev_payment_hash);
2616                         assert_eq!(payment_failed_permanently, false);
2617                 },
2618                 _ => panic!("Unexpected event"),
2619         }
2620         match events[1] {
2621                 Event::PendingHTLCsForwardable { .. } => {},
2622                 _ => panic!("Unexpected event"),
2623         }
2624
2625         nodes[0].node.process_pending_htlc_forwards();
2626         let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2627         check_added_monitors!(nodes[0], 1);
2628
2629         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2630         commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2631
2632         expect_pending_htlcs_forwardable!(nodes[1]);
2633         check_added_monitors!(nodes[1], 1);
2634
2635         let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2636         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2637         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2638         commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2639
2640         expect_pending_htlcs_forwardable!(nodes[2]);
2641         expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2642 }
2643
2644 #[test]
2645 #[cfg(feature = "std")]
2646 fn test_threaded_payment_retries() {
2647         // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2648         // a single thread and would happily let multiple threads run retries at the same time. Because
2649         // retries are done by first calculating the amount we need to retry, then dropping the
2650         // relevant lock, then actually sending, we would happily let multiple threads retry the same
2651         // amount at the same time, overpaying our original HTLC!
2652         let chanmon_cfgs = create_chanmon_cfgs(4);
2653         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2654         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2655         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2656
2657         // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2658         // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2659         // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2660         // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2661         // our channel.
2662         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2663         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2664         let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2665         let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2666
2667         let amt_msat = 100_000_000;
2668         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2669         #[cfg(feature = "std")]
2670         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2671         #[cfg(not(feature = "std"))]
2672         let payment_expiry_secs = 60 * 60;
2673         let mut invoice_features = InvoiceFeatures::empty();
2674         invoice_features.set_variable_length_onion_required();
2675         invoice_features.set_payment_secret_required();
2676         invoice_features.set_basic_mpp_optional();
2677         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2678                 .with_expiry_time(payment_expiry_secs as u64)
2679                 .with_bolt11_features(invoice_features).unwrap();
2680         let mut route_params = RouteParameters {
2681                 payment_params,
2682                 final_value_msat: amt_msat,
2683         };
2684
2685         let mut route = Route {
2686                 paths: vec![
2687                         Path { hops: vec![RouteHop {
2688                                 pubkey: nodes[1].node.get_our_node_id(),
2689                                 node_features: nodes[1].node.node_features(),
2690                                 short_channel_id: chan_1_scid,
2691                                 channel_features: nodes[1].node.channel_features(),
2692                                 fee_msat: 0,
2693                                 cltv_expiry_delta: 100,
2694                         }, RouteHop {
2695                                 pubkey: nodes[3].node.get_our_node_id(),
2696                                 node_features: nodes[2].node.node_features(),
2697                                 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2698                                 channel_features: nodes[2].node.channel_features(),
2699                                 fee_msat: amt_msat / 1000,
2700                                 cltv_expiry_delta: 100,
2701                         }], blinded_tail: None },
2702                         Path { hops: vec![RouteHop {
2703                                 pubkey: nodes[2].node.get_our_node_id(),
2704                                 node_features: nodes[2].node.node_features(),
2705                                 short_channel_id: chan_3_scid,
2706                                 channel_features: nodes[2].node.channel_features(),
2707                                 fee_msat: 100_000,
2708                                 cltv_expiry_delta: 100,
2709                         }, RouteHop {
2710                                 pubkey: nodes[3].node.get_our_node_id(),
2711                                 node_features: nodes[3].node.node_features(),
2712                                 short_channel_id: chan_4_scid,
2713                                 channel_features: nodes[3].node.channel_features(),
2714                                 fee_msat: amt_msat - amt_msat / 1000,
2715                                 cltv_expiry_delta: 100,
2716                         }], blinded_tail: None }
2717                 ],
2718                 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2719         };
2720         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2721
2722         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2723                 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
2724         check_added_monitors!(nodes[0], 2);
2725         let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2726         assert_eq!(send_msg_events.len(), 2);
2727         send_msg_events.retain(|msg|
2728                 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
2729                         // Drop the commitment update for nodes[2], we can just let that one sit pending
2730                         // forever.
2731                         *node_id == nodes[1].node.get_our_node_id()
2732                 } else { panic!(); }
2733         );
2734
2735         // from here on out, the retry `RouteParameters` amount will be amt/1000
2736         route_params.final_value_msat /= 1000;
2737         route.paths.pop();
2738
2739         let end_time = Instant::now() + Duration::from_secs(1);
2740         macro_rules! thread_body { () => { {
2741                 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
2742                 let node_ref = NodePtr::from_node(&nodes[0]);
2743                 move || {
2744                         let node_a = unsafe { &*node_ref.0 };
2745                         while Instant::now() < end_time {
2746                                 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2747                                 // Ignore if we have any pending events, just always pretend we just got a
2748                                 // PendingHTLCsForwardable
2749                                 node_a.node.process_pending_htlc_forwards();
2750                         }
2751                 }
2752         } } }
2753         let mut threads = Vec::new();
2754         for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
2755
2756         // Back in the main thread, poll pending messages and make sure that we never have more than
2757         // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
2758         // there are HTLC messages shoved in while its running. This allows us to test that we never
2759         // generate an additional update_add_htlc until we've fully failed the first.
2760         let mut previously_failed_channels = Vec::new();
2761         loop {
2762                 assert_eq!(send_msg_events.len(), 1);
2763                 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
2764                 assert_eq!(send_event.msgs.len(), 1);
2765
2766                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
2767                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
2768
2769                 // Note that we only push one route into `expect_find_route` at a time, because that's all
2770                 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
2771                 // we should still ultimately fail for the same reason - because we're trying to send too
2772                 // many HTLCs at once.
2773                 let mut new_route_params = route_params.clone();
2774                 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
2775                 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
2776                 route.paths[0].hops[1].short_channel_id += 1;
2777                 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
2778
2779                 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2780                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
2781                 // The "normal" commitment_signed_dance delivers the final RAA and then calls
2782                 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
2783                 // This races with our other threads which may generate an add-HTLCs commitment update via
2784                 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
2785                 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
2786                 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
2787                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
2788
2789                 let cur_time = Instant::now();
2790                 if cur_time > end_time {
2791                         for thread in threads.drain(..) { thread.join().unwrap(); }
2792                 }
2793
2794                 // Make sure we have some events to handle when we go around...
2795                 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2796                 nodes[0].node.process_pending_htlc_forwards();
2797                 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2798                 check_added_monitors!(nodes[0], 2);
2799
2800                 if cur_time > end_time {
2801                         break;
2802                 }
2803         }
2804 }
2805
2806 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
2807         // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
2808         // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
2809         // it was last persisted.
2810         let chanmon_cfgs = create_chanmon_cfgs(2);
2811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2813         let (persister_a, persister_b, persister_c);
2814         let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
2815         let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
2816         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2817
2818         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2819
2820         let mut nodes_0_serialized = Vec::new();
2821         if !persist_manager_with_payment {
2822                 nodes_0_serialized = nodes[0].node.encode();
2823         }
2824
2825         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2826
2827         if persist_manager_with_payment {
2828                 nodes_0_serialized = nodes[0].node.encode();
2829         }
2830
2831         nodes[1].node.claim_funds(our_payment_preimage);
2832         check_added_monitors!(nodes[1], 1);
2833         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
2834
2835         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2836         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2837         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
2838         check_added_monitors!(nodes[0], 1);
2839
2840         // The ChannelMonitor should always be the latest version, as we're required to persist it
2841         // during the commitment signed handling.
2842         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2843         reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
2844
2845         let events = nodes[0].node.get_and_clear_pending_events();
2846         assert_eq!(events.len(), 2);
2847         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
2848         if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
2849         // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
2850         // the double-claim that would otherwise appear at the end of this test.
2851         nodes[0].node.timer_tick_occurred();
2852         let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2853         assert_eq!(as_broadcasted_txn.len(), 1);
2854
2855         // Ensure that, even after some time, if we restart we still include *something* in the current
2856         // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
2857         // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
2858         // A naive implementation of the fix here would wipe the pending payments set, causing a
2859         // failure event when we restart.
2860         for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2861
2862         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2863         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);
2864         let events = nodes[0].node.get_and_clear_pending_events();
2865         assert!(events.is_empty());
2866
2867         // Ensure that we don't generate any further events even after the channel-closing commitment
2868         // transaction is confirmed on-chain.
2869         confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
2870         for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2871
2872         let events = nodes[0].node.get_and_clear_pending_events();
2873         assert!(events.is_empty());
2874
2875         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2876         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);
2877         let events = nodes[0].node.get_and_clear_pending_events();
2878         assert!(events.is_empty());
2879         check_added_monitors(&nodes[0], 1);
2880 }
2881
2882 #[test]
2883 fn no_missing_sent_on_midpoint_reload() {
2884         do_no_missing_sent_on_midpoint_reload(false);
2885         do_no_missing_sent_on_midpoint_reload(true);
2886 }
2887
2888 fn do_claim_from_closed_chan(fail_payment: bool) {
2889         // Previously, LDK would refuse to claim a payment if a channel on which the payment was
2890         // received had been closed between when the HTLC was received and when we went to claim it.
2891         // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
2892         // presumably the sender may retry later. Long ago it also reduced total code in the claim
2893         // pipeline.
2894         //
2895         // However, this doesn't make sense if you're trying to do an atomic swap or some other
2896         // protocol that requires atomicity with some other action - if your money got claimed
2897         // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
2898         // is an over-optimization - there should be a very, very low likelihood that a channel closes
2899         // between when we receive the last HTLC for a payment and the user goes to claim the payment.
2900         // Since we now have code to handle this anyway we should allow it.
2901
2902         // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
2903         // CLTVs on the paths to different value resulting in a different claim deadline.
2904         let chanmon_cfgs = create_chanmon_cfgs(4);
2905         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2906         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2907         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2908
2909         create_announced_chan_between_nodes(&nodes, 0, 1);
2910         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
2911         let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
2912         create_announced_chan_between_nodes(&nodes, 2, 3);
2913
2914         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
2915         let mut route_params = RouteParameters {
2916                 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
2917                         .with_bolt11_features(nodes[1].node.invoice_features()).unwrap(),
2918                 final_value_msat: 10_000_000,
2919         };
2920         let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
2921                 None, &nodes[0].node.compute_inflight_htlcs()).unwrap();
2922         // Make sure the route is ordered as the B->D path before C->D
2923         route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
2924                 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
2925
2926         // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
2927         // the HTLC is being relayed.
2928         route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
2929         route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
2930         let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
2931
2932         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2933         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2934                 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
2935         check_added_monitors(&nodes[0], 2);
2936         let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2937         send_msgs.sort_by(|a, _| {
2938                 let a_node_id =
2939                         if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
2940                 let node_b_id = nodes[1].node.get_our_node_id();
2941                 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
2942         });
2943
2944         assert_eq!(send_msgs.len(), 2);
2945         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
2946                 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
2947         let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
2948                 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
2949
2950         match receive_event.unwrap() {
2951                 Event::PaymentClaimable { claim_deadline, .. } => {
2952                         assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
2953                 },
2954                 _ => panic!(),
2955         }
2956
2957         // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
2958         // height.
2959         connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
2960                 - if fail_payment { 0 } else { 2 });
2961         if fail_payment {
2962                 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
2963                 // and expire both immediately, though, by connecting another 4 blocks.
2964                 let reason = HTLCDestination::FailedPayment { payment_hash };
2965                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
2966                 connect_blocks(&nodes[3], 4);
2967                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
2968                 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2969         } else {
2970                 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
2971                 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false);
2972                 check_closed_broadcast(&nodes[1], 1, true);
2973                 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2974                 assert_eq!(bs_tx.len(), 1);
2975
2976                 mine_transaction(&nodes[3], &bs_tx[0]);
2977                 check_added_monitors(&nodes[3], 1);
2978                 check_closed_broadcast(&nodes[3], 1, true);
2979                 check_closed_event(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false);
2980
2981                 nodes[3].node.claim_funds(payment_preimage);
2982                 check_added_monitors(&nodes[3], 2);
2983                 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
2984
2985                 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2986                 assert_eq!(ds_tx.len(), 1);
2987                 check_spends!(&ds_tx[0], &bs_tx[0]);
2988
2989                 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
2990                 check_added_monitors(&nodes[1], 1);
2991                 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
2992
2993                 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
2994                 check_added_monitors(&nodes[1], 1);
2995                 assert_eq!(bs_claims.len(), 1);
2996                 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
2997                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2998                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
2999                 } else { panic!(); }
3000
3001                 expect_payment_sent!(nodes[0], payment_preimage);
3002
3003                 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
3004                 assert_eq!(ds_claim_msgs.len(), 1);
3005                 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
3006                         nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3007                         let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3008                         check_added_monitors(&nodes[2], 1);
3009                         commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3010                         expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3011                         cs_claim_msgs
3012                 } else { panic!(); };
3013
3014                 assert_eq!(cs_claim_msgs.len(), 1);
3015                 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3016                         nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3017                         commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3018                 } else { panic!(); }
3019
3020                 expect_payment_path_successful!(nodes[0]);
3021         }
3022 }
3023
3024 #[test]
3025 fn claim_from_closed_chan() {
3026         do_claim_from_closed_chan(true);
3027         do_claim_from_closed_chan(false);
3028 }
3029
3030 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3031         // Check that a payment metadata received on one HTLC that doesn't match the one received on
3032         // another results in the HTLC being rejected.
3033         //
3034         // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3035         // first of which we'll deliver and the second of which we'll fail and then re-send with
3036         // modified payment metadata, which will in turn result in it being failed by the recipient.
3037         let chanmon_cfgs = create_chanmon_cfgs(4);
3038         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3039         let mut config = test_default_channel_config();
3040         config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3041         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3042
3043         let persister;
3044         let new_chain_monitor;
3045         let nodes_0_deserialized;
3046
3047         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3048
3049         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3050         let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3051         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3052         let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3053
3054         // Pay more than half of each channel's max, requiring MPP
3055         let amt_msat = 750_000_000;
3056         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3057         let payment_id = PaymentId(payment_hash.0);
3058         let payment_metadata = vec![44, 49, 52, 142];
3059
3060         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3061                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
3062         let mut route_params = RouteParameters {
3063                 payment_params,
3064                 final_value_msat: amt_msat,
3065         };
3066
3067         // Send the MPP payment, delivering the updated commitment state to nodes[1].
3068         nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3069                         payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata),
3070                 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3071         check_added_monitors!(nodes[0], 2);
3072
3073         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3074         assert_eq!(send_events.len(), 2);
3075         let first_send = SendEvent::from_event(send_events.pop().unwrap());
3076         let second_send = SendEvent::from_event(send_events.pop().unwrap());
3077
3078         let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3079                 (&first_send, &second_send)
3080         } else {
3081                 (&second_send, &first_send)
3082         };
3083         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3084         commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3085
3086         expect_pending_htlcs_forwardable!(nodes[1]);
3087         check_added_monitors(&nodes[1], 1);
3088         let b_forward_ev = SendEvent::from_node(&nodes[1]);
3089         nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3090         commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3091
3092         expect_pending_htlcs_forwardable!(nodes[3]);
3093
3094         // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3095         // will result in nodes[2] failing the HTLC back.
3096         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3097         nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3098
3099         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3100         commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3101
3102         let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3103         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3104         commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3105
3106         let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3107         assert_eq!(payment_fail_retryable_evs.len(), 2);
3108         if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3109         if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3110
3111         // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3112         // stored for our payment.
3113         if do_modify {
3114                 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3115         }
3116
3117         // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3118         // the payment state.
3119         if do_reload {
3120                 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3121                 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3122                 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3123                         persister, new_chain_monitor, nodes_0_deserialized);
3124                 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3125                 reconnect_nodes(&nodes[1], &nodes[3], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3126         }
3127         reconnect_nodes(&nodes[2], &nodes[3], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3128
3129         // Create a new channel between C and D as A will refuse to retry on the existing one because
3130         // it just failed.
3131         let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3132
3133         // Now retry the failed HTLC.
3134         nodes[0].node.process_pending_htlc_forwards();
3135         check_added_monitors(&nodes[0], 1);
3136         let as_resend = SendEvent::from_node(&nodes[0]);
3137         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3138         commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3139
3140         expect_pending_htlcs_forwardable!(nodes[2]);
3141         check_added_monitors(&nodes[2], 1);
3142         let cs_forward = SendEvent::from_node(&nodes[2]);
3143         nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3144         commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3145
3146         // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3147         // the payment metadata was modified, failing only the one modified HTLC and retaining the
3148         // other.
3149         if do_modify {
3150                 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3151                 nodes[3].node.process_pending_htlc_forwards();
3152                 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3153                         &[HTLCDestination::FailedPayment {payment_hash}]);
3154                 nodes[3].node.process_pending_htlc_forwards();
3155
3156                 check_added_monitors(&nodes[3], 1);
3157                 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3158
3159                 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3160                 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3161                 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3162                         &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3163         } else {
3164                 expect_pending_htlcs_forwardable!(nodes[3]);
3165                 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3166                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3167         }
3168 }
3169
3170 #[test]
3171 fn test_payment_metadata_consistency() {
3172         do_test_payment_metadata_consistency(true, true);
3173         do_test_payment_metadata_consistency(true, false);
3174         do_test_payment_metadata_consistency(false, true);
3175         do_test_payment_metadata_consistency(false, false);
3176 }