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