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