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