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