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