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