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