Merge pull request #1726 from jkczyz/2022-09-offer-parsing
[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::transaction::OutPoint;
17 use crate::chain::keysinterface::KeysInterface;
18 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
19 use crate::ln::channelmanager::{self, BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS};
20 use crate::ln::msgs;
21 use crate::ln::msgs::ChannelMessageHandler;
22 use crate::routing::router::{PaymentParameters, get_route};
23 use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
24 use crate::util::test_utils;
25 use crate::util::errors::APIError;
26 use crate::util::ser::Writeable;
27
28 use bitcoin::{Block, BlockHeader, TxMerkleNode};
29 use bitcoin::hashes::Hash;
30 use bitcoin::network::constants::Network;
31
32 use crate::prelude::*;
33
34 use crate::ln::functional_test_utils::*;
35
36 #[test]
37 fn retry_single_path_payment() {
38         let chanmon_cfgs = create_chanmon_cfgs(3);
39         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
40         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
41         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
42
43         let _chan_0 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
44         let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
45         // Rebalance to find a route
46         send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
47
48         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
49
50         // Rebalance so that the first hop fails.
51         send_payment(&nodes[1], &vec!(&nodes[2])[..], 2_000_000);
52
53         // Make sure the payment fails on the first hop.
54         let payment_id = PaymentId(payment_hash.0);
55         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), payment_id).unwrap();
56         check_added_monitors!(nodes[0], 1);
57         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
58         assert_eq!(events.len(), 1);
59         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
60         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
61         check_added_monitors!(nodes[1], 0);
62         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
63         expect_pending_htlcs_forwardable!(nodes[1]);
64         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 }]);
65         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
66         assert!(htlc_updates.update_add_htlcs.is_empty());
67         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
68         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
69         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
70         check_added_monitors!(nodes[1], 1);
71         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
72         commitment_signed_dance!(nodes[0], nodes[1], htlc_updates.commitment_signed, false);
73         expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
74
75         // Rebalance the channel so the retry succeeds.
76         send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
77
78         // Mine two blocks (we expire retries after 3, so this will check that we don't expire early)
79         connect_blocks(&nodes[0], 2);
80
81         // Retry the payment and make sure it succeeds.
82         nodes[0].node.retry_payment(&route, payment_id).unwrap();
83         check_added_monitors!(nodes[0], 1);
84         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
85         assert_eq!(events.len(), 1);
86         pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 100_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
87         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
88 }
89
90 #[test]
91 fn mpp_failure() {
92         let chanmon_cfgs = create_chanmon_cfgs(4);
93         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
94         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
95         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
96
97         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
98         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
99         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
100         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
101
102         let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
103         let path = route.paths[0].clone();
104         route.paths.push(path);
105         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
106         route.paths[0][0].short_channel_id = chan_1_id;
107         route.paths[0][1].short_channel_id = chan_3_id;
108         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
109         route.paths[1][0].short_channel_id = chan_2_id;
110         route.paths[1][1].short_channel_id = chan_4_id;
111         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
112         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
113 }
114
115 #[test]
116 fn mpp_retry() {
117         let chanmon_cfgs = create_chanmon_cfgs(4);
118         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
119         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
120         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
121
122         let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
123         let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
124         let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
125         let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
126         // Rebalance
127         send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
128
129         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 1_000_000);
130         let path = route.paths[0].clone();
131         route.paths.push(path);
132         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
133         route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
134         route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
135         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
136         route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
137         route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
138
139         // Initiate the MPP payment.
140         let payment_id = PaymentId(payment_hash.0);
141         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), payment_id).unwrap();
142         check_added_monitors!(nodes[0], 2); // one monitor per path
143         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
144         assert_eq!(events.len(), 2);
145
146         // Pass half of the payment along the success path.
147         let success_path_msgs = events.remove(0);
148         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
149
150         // Add the HTLC along the first hop.
151         let fail_path_msgs_1 = events.remove(0);
152         let (update_add, commitment_signed) = match fail_path_msgs_1 {
153                 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 } } => {
154                         assert_eq!(update_add_htlcs.len(), 1);
155                         assert!(update_fail_htlcs.is_empty());
156                         assert!(update_fulfill_htlcs.is_empty());
157                         assert!(update_fail_malformed_htlcs.is_empty());
158                         assert!(update_fee.is_none());
159                         (update_add_htlcs[0].clone(), commitment_signed.clone())
160                 },
161                 _ => panic!("Unexpected event"),
162         };
163         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
164         commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
165
166         // Attempt to forward the payment and complete the 2nd path's failure.
167         expect_pending_htlcs_forwardable!(&nodes[2]);
168         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 }]);
169         let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
170         assert!(htlc_updates.update_add_htlcs.is_empty());
171         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
172         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
173         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
174         check_added_monitors!(nodes[2], 1);
175         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
176         commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
177         expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
178
179         // Rebalance the channel so the second half of the payment can succeed.
180         send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
181
182         // Make sure it errors as expected given a too-large amount.
183         if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = nodes[0].node.retry_payment(&route, payment_id) {
184                 assert!(err.contains("over total_payment_amt_msat"));
185         } else { panic!("Unexpected error"); }
186
187         // Make sure it errors as expected given the wrong payment_id.
188         if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = nodes[0].node.retry_payment(&route, PaymentId([0; 32])) {
189                 assert!(err.contains("not found"));
190         } else { panic!("Unexpected error"); }
191
192         // Retry the second half of the payment and make sure it succeeds.
193         let mut path = route.clone();
194         path.paths.remove(0);
195         nodes[0].node.retry_payment(&path, payment_id).unwrap();
196         check_added_monitors!(nodes[0], 1);
197         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
198         assert_eq!(events.len(), 1);
199         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
200         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
201 }
202
203 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
204         let chanmon_cfgs = create_chanmon_cfgs(4);
205         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
206         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
207         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
208
209         let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
210         let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
211         let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
212         let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
213
214         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
215         let path = route.paths[0].clone();
216         route.paths.push(path);
217         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
218         route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
219         route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
220         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
221         route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
222         route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
223
224         // Initiate the MPP payment.
225         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
226         check_added_monitors!(nodes[0], 2); // one monitor per path
227         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
228         assert_eq!(events.len(), 2);
229
230         // Pass half of the payment along the first path.
231         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), events.remove(0), false, None);
232
233         if send_partial_mpp {
234                 // Time out the partial MPP
235                 for _ in 0..MPP_TIMEOUT_TICKS {
236                         nodes[3].node.timer_tick_occurred();
237                 }
238
239                 // Failed HTLC from node 3 -> 1
240                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
241                 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
242                 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
243                 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
244                 check_added_monitors!(nodes[3], 1);
245                 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
246
247                 // Failed HTLC from node 1 -> 0
248                 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 }]);
249                 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
250                 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
251                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
252                 check_added_monitors!(nodes[1], 1);
253                 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
254
255                 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
256         } else {
257                 // Pass half of the payment along the second path.
258                 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), events.remove(0), true, None);
259
260                 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
261                 for _ in 0..MPP_TIMEOUT_TICKS {
262                         nodes[3].node.timer_tick_occurred();
263                 }
264
265                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
266         }
267 }
268
269 #[test]
270 fn mpp_receive_timeout() {
271         do_mpp_receive_timeout(true);
272         do_mpp_receive_timeout(false);
273 }
274
275 #[test]
276 fn retry_expired_payment() {
277         let chanmon_cfgs = create_chanmon_cfgs(3);
278         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
279         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
280         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
281
282         let _chan_0 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
283         let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
284         // Rebalance to find a route
285         send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
286
287         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
288
289         // Rebalance so that the first hop fails.
290         send_payment(&nodes[1], &vec!(&nodes[2])[..], 2_000_000);
291
292         // Make sure the payment fails on the first hop.
293         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
294         check_added_monitors!(nodes[0], 1);
295         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
296         assert_eq!(events.len(), 1);
297         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
298         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
299         check_added_monitors!(nodes[1], 0);
300         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
301         expect_pending_htlcs_forwardable!(nodes[1]);
302         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 }]);
303         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
304         assert!(htlc_updates.update_add_htlcs.is_empty());
305         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
306         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
307         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
308         check_added_monitors!(nodes[1], 1);
309         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
310         commitment_signed_dance!(nodes[0], nodes[1], htlc_updates.commitment_signed, false);
311         expect_payment_failed!(nodes[0], payment_hash, false);
312
313         // Mine blocks so the payment will have expired.
314         connect_blocks(&nodes[0], 3);
315
316         // Retry the payment and make sure it errors as expected.
317         if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = nodes[0].node.retry_payment(&route, PaymentId(payment_hash.0)) {
318                 assert!(err.contains("not found"));
319         } else {
320                 panic!("Unexpected error");
321         }
322 }
323
324 #[test]
325 fn no_pending_leak_on_initial_send_failure() {
326         // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
327         // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
328         // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
329         // pending payment forever and never time it out.
330         // Here we test exactly that - retrying a payment when a peer was disconnected on the first
331         // try, and then check that no pending payment is being tracked.
332         let chanmon_cfgs = create_chanmon_cfgs(2);
333         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
334         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
335         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
336
337         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
338
339         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
340
341         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
342         nodes[1].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
343
344         unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)),
345                 true, APIError::ChannelUnavailable { ref err },
346                 assert_eq!(err, "Peer for first hop currently disconnected/pending monitor update!"));
347
348         assert!(!nodes[0].node.has_pending_payments());
349 }
350
351 fn do_retry_with_no_persist(confirm_before_reload: bool) {
352         // If we send a pending payment and `send_payment` returns success, we should always either
353         // return a payment failure event or a payment success event, and on failure the payment should
354         // be retryable.
355         //
356         // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
357         // always persisted asynchronously), the ChannelManager has to reload some payment data from
358         // ChannelMonitor(s) in some cases. This tests that reloading.
359         //
360         // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
361         // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
362         // which has separate codepaths for "commitment transaction already confirmed" and not.
363         let chanmon_cfgs = create_chanmon_cfgs(3);
364         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
365         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
366         let persister: test_utils::TestPersister;
367         let new_chain_monitor: test_utils::TestChainMonitor;
368         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
369         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
370
371         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
372         let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
373
374         // Serialize the ChannelManager prior to sending payments
375         let nodes_0_serialized = nodes[0].node.encode();
376
377         // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
378         // out and retry.
379         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
380         let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
381         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
382         check_added_monitors!(nodes[0], 1);
383
384         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
385         assert_eq!(events.len(), 1);
386         let payment_event = SendEvent::from_event(events.pop().unwrap());
387         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
388
389         // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
390         // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
391         // which would prevent retry.
392         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
393         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
394
395         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
396         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
397         // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
398         let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
399
400         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
401
402         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
403         if confirm_before_reload {
404                 mine_transaction(&nodes[0], &as_commitment_tx);
405                 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
406         }
407
408         // The ChannelMonitor should always be the latest version, as we're required to persist it
409         // during the `commitment_signed_dance!()`.
410         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
411         reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
412
413         // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
414         // force-close the channel.
415         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
416         assert!(nodes[0].node.list_channels().is_empty());
417         assert!(nodes[0].node.has_pending_payments());
418         let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
419         assert_eq!(as_broadcasted_txn.len(), 1);
420         assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
421
422         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
423         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
424         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
425
426         // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
427         // error, as the channel has hit the chain.
428         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
429         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
430         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
431         let as_err = nodes[0].node.get_and_clear_pending_msg_events();
432         assert_eq!(as_err.len(), 1);
433         match as_err[0] {
434                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
435                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
436                         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
437                         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_string() });
438                         check_added_monitors!(nodes[1], 1);
439                         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
440                 },
441                 _ => panic!("Unexpected event"),
442         }
443         check_closed_broadcast!(nodes[1], false);
444
445         // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
446         // we close in a moment.
447         nodes[2].node.claim_funds(payment_preimage_1);
448         check_added_monitors!(nodes[2], 1);
449         expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
450
451         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
452         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
453         check_added_monitors!(nodes[1], 1);
454         commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
455         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
456
457         if confirm_before_reload {
458                 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
459                 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
460         }
461
462         // Create a new channel on which to retry the payment before we fail the payment via the
463         // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
464         // connecting several blocks while creating the channel (implying time has passed).
465         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
466         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
467
468         mine_transaction(&nodes[1], &as_commitment_tx);
469         let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
470         assert_eq!(bs_htlc_claim_txn.len(), 1);
471         check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
472
473         if !confirm_before_reload {
474                 mine_transaction(&nodes[0], &as_commitment_tx);
475         }
476         mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
477         expect_payment_sent!(nodes[0], payment_preimage_1);
478         connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
479         let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
480         assert_eq!(as_htlc_timeout_txn.len(), 2);
481         let (first_htlc_timeout_tx, second_htlc_timeout_tx) = (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1]);
482         check_spends!(first_htlc_timeout_tx, as_commitment_tx);
483         check_spends!(second_htlc_timeout_tx, as_commitment_tx);
484         if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
485                 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
486         } else {
487                 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
488         }
489         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
490         expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
491
492         // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
493         // reloaded) via a route over the new channel, which work without issue and eventually be
494         // received and claimed at the recipient just like any other payment.
495         let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
496
497         // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
498         // and not the original fee. We also update node[1]'s relevant config as
499         // do_claim_payment_along_route expects us to never overpay.
500         {
501                 let mut channel_state = nodes[1].node.channel_state.lock().unwrap();
502                 let mut channel = channel_state.by_id.get_mut(&chan_id_2).unwrap();
503                 let mut new_config = channel.config();
504                 new_config.forwarding_fee_base_msat += 100_000;
505                 channel.update_config(&new_config);
506                 new_route.paths[0][0].fee_msat += 100_000;
507         }
508
509         // Force expiration of the channel's previous config.
510         for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
511                 nodes[1].node.timer_tick_occurred();
512         }
513
514         assert!(nodes[0].node.retry_payment(&new_route, payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
515         nodes[0].node.retry_payment(&new_route, PaymentId(payment_hash.0)).unwrap();
516         check_added_monitors!(nodes[0], 1);
517         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
518         assert_eq!(events.len(), 1);
519         pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
520         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
521         expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
522 }
523
524 #[test]
525 fn retry_with_no_persist() {
526         do_retry_with_no_persist(true);
527         do_retry_with_no_persist(false);
528 }
529
530 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
531         // Test that an off-chain completed payment is not retryable on restart. This was previously
532         // broken for dust payments, but we test for both dust and non-dust payments.
533         //
534         // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
535         // output at all.
536         let chanmon_cfgs = create_chanmon_cfgs(3);
537         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
538
539         let mut manually_accept_config = test_default_channel_config();
540         manually_accept_config.manually_accept_inbound_channels = true;
541
542         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
543
544         let first_persister: test_utils::TestPersister;
545         let first_new_chain_monitor: test_utils::TestChainMonitor;
546         let first_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
547         let second_persister: test_utils::TestPersister;
548         let second_new_chain_monitor: test_utils::TestChainMonitor;
549         let second_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
550         let third_persister: test_utils::TestPersister;
551         let third_new_chain_monitor: test_utils::TestChainMonitor;
552         let third_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
553
554         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
555
556         // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
557         let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
558         confirm_transaction(&nodes[0], &funding_tx);
559         confirm_transaction(&nodes[1], &funding_tx);
560         // Ignore the announcement_signatures messages
561         nodes[0].node.get_and_clear_pending_msg_events();
562         nodes[1].node.get_and_clear_pending_msg_events();
563         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
564
565         // Serialize the ChannelManager prior to sending payments
566         let mut nodes_0_serialized = nodes[0].node.encode();
567
568         let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
569         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 });
570
571         // The ChannelMonitor should always be the latest version, as we're required to persist it
572         // during the `commitment_signed_dance!()`.
573         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
574
575         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);
576         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
577
578         // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
579         // force-close the channel.
580         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
581         assert!(nodes[0].node.list_channels().is_empty());
582         assert!(nodes[0].node.has_pending_payments());
583         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
584
585         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
586         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
587
588         // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
589         // error, as the channel has hit the chain.
590         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
591         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
592         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
593         let as_err = nodes[0].node.get_and_clear_pending_msg_events();
594         assert_eq!(as_err.len(), 1);
595         let bs_commitment_tx;
596         match as_err[0] {
597                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
598                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
599                         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
600                         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_string() });
601                         check_added_monitors!(nodes[1], 1);
602                         bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
603                 },
604                 _ => panic!("Unexpected event"),
605         }
606         check_closed_broadcast!(nodes[1], false);
607
608         // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
609         // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
610         // incoming HTLCs with the same payment hash later.
611         nodes[2].node.fail_htlc_backwards(&payment_hash);
612         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
613         check_added_monitors!(nodes[2], 1);
614
615         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
616         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
617         commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
618         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
619                 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
620
621         // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
622         // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
623         // after the commitment transaction, so always connect the commitment transaction.
624         mine_transaction(&nodes[0], &bs_commitment_tx[0]);
625         mine_transaction(&nodes[1], &bs_commitment_tx[0]);
626         if !use_dust {
627                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
628                 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
629                 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
630                 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
631                 assert_eq!(as_htlc_timeout.len(), 1);
632
633                 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
634                 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
635                 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
636                 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
637         }
638
639         // Create a new channel on which to retry the payment before we fail the payment via the
640         // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
641         // connecting several blocks while creating the channel (implying time has passed).
642         // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
643         let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
644         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
645
646         // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
647         // confirming, we will fail as it's considered still-pending...
648         let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
649         assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
650         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
651
652         // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
653         // again. We serialize the node first as we'll then test retrying the HTLC after a restart
654         // (which should also still work).
655         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
656         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
657         // We set mpp_parts_remain to avoid having abandon_payment called
658         expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
659
660         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
661         let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
662         nodes_0_serialized = nodes[0].node.encode();
663
664         assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
665         assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
666
667         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);
668         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
669
670         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
671
672         // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
673         // the payment is not (spuriously) listed as still pending.
674         assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
675         check_added_monitors!(nodes[0], 1);
676         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
677         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
678
679         assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
680         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
681
682         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
683         let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
684         nodes_0_serialized = nodes[0].node.encode();
685
686         // Ensure that after reload we cannot retry the payment.
687         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);
688         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
689
690         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
691
692         assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
693         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
694 }
695
696 #[test]
697 fn test_completed_payment_not_retryable_on_reload() {
698         do_test_completed_payment_not_retryable_on_reload(true);
699         do_test_completed_payment_not_retryable_on_reload(false);
700 }
701
702
703 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
704         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
705         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
706         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
707         // the ChannelMonitor tells it to.
708         //
709         // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
710         // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
711         // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
712         let chanmon_cfgs = create_chanmon_cfgs(2);
713         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
714         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
715         let persister: test_utils::TestPersister;
716         let new_chain_monitor: test_utils::TestChainMonitor;
717         let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
718         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
719
720         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
721
722         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
723         // nodes[0].
724         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
725         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
726         check_closed_broadcast!(nodes[0], true);
727         check_added_monitors!(nodes[0], 1);
728         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
729
730         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
731         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
732
733         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
734         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
735         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
736         assert_eq!(node_txn.len(), 3);
737         assert_eq!(node_txn[0], node_txn[1]);
738         check_spends!(node_txn[1], funding_tx);
739         check_spends!(node_txn[2], node_txn[1]);
740         let timeout_txn = vec![node_txn[2].clone()];
741
742         nodes[1].node.claim_funds(payment_preimage);
743         check_added_monitors!(nodes[1], 1);
744         expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
745
746         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
747         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
748         check_closed_broadcast!(nodes[1], true);
749         check_added_monitors!(nodes[1], 1);
750         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
751         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
752         assert_eq!(claim_txn.len(), 3);
753         check_spends!(claim_txn[0], node_txn[1]);
754         check_spends!(claim_txn[1], funding_tx);
755         check_spends!(claim_txn[2], claim_txn[1]);
756
757         header.prev_blockhash = nodes[0].best_block_hash();
758         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
759
760         if confirm_commitment_tx {
761                 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
762         }
763
764         header.prev_blockhash = nodes[0].best_block_hash();
765         let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
766
767         if payment_timeout {
768                 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
769                 connect_block(&nodes[0], &claim_block);
770                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
771         }
772
773         // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
774         // returning InProgress. This should cause the claim event to never make its way to the
775         // ChannelManager.
776         chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
777         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
778
779         if payment_timeout {
780                 connect_blocks(&nodes[0], 1);
781         } else {
782                 connect_block(&nodes[0], &claim_block);
783         }
784
785         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
786         let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
787                 .get_mut(&funding_txo).unwrap().drain().collect();
788         // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice
789         assert!(mon_updates.len() == 1 || mon_updates.len() == 2);
790         assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
791         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
792
793         // If we persist the ChannelManager here, we should get the PaymentSent event after
794         // deserialization.
795         let mut chan_manager_serialized = Vec::new();
796         if !persist_manager_post_event {
797                 chan_manager_serialized = nodes[0].node.encode();
798         }
799
800         // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
801         // payment sent event.
802         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
803         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
804         for update in mon_updates {
805                 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
806         }
807         if payment_timeout {
808                 expect_payment_failed!(nodes[0], payment_hash, false);
809         } else {
810                 expect_payment_sent!(nodes[0], payment_preimage);
811         }
812
813         // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
814         // twice.
815         if persist_manager_post_event {
816                 chan_manager_serialized = nodes[0].node.encode();
817         }
818
819         // Now reload nodes[0]...
820         reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
821
822         if persist_manager_post_event {
823                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
824         } else if payment_timeout {
825                 expect_payment_failed!(nodes[0], payment_hash, false);
826         } else {
827                 expect_payment_sent!(nodes[0], payment_preimage);
828         }
829
830         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
831         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
832         // payment events should kick in, leaving us with no pending events here.
833         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
834         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
835         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
836 }
837
838 #[test]
839 fn test_dup_htlc_onchain_fails_on_reload() {
840         do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
841         do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
842         do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
843         do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
844         do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
845         do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
846 }
847
848 #[test]
849 fn test_fulfill_restart_failure() {
850         // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
851         // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
852         // again, or fail it, giving us free money.
853         //
854         // Of course probably they won't fail it and give us free money, but because we have code to
855         // handle it, we should test the logic for it anyway. We do that here.
856         let chanmon_cfgs = create_chanmon_cfgs(2);
857         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
858         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
859         let persister: test_utils::TestPersister;
860         let new_chain_monitor: test_utils::TestChainMonitor;
861         let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
862         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
863
864         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
865         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
866
867         // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
868         // pre-fulfill, which we do by serializing it here.
869         let chan_manager_serialized = nodes[1].node.encode();
870         let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
871
872         nodes[1].node.claim_funds(payment_preimage);
873         check_added_monitors!(nodes[1], 1);
874         expect_payment_claimed!(nodes[1], payment_hash, 100_000);
875
876         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
877         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
878         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
879
880         // Now reload nodes[1]...
881         reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
882
883         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
884         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
885
886         nodes[1].node.fail_htlc_backwards(&payment_hash);
887         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
888         check_added_monitors!(nodes[1], 1);
889         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
890         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
891         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
892         // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
893         // it had already considered the payment fulfilled, and now they just got free money.
894         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
895 }
896
897 #[test]
898 fn get_ldk_payment_preimage() {
899         // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
900         let chanmon_cfgs = create_chanmon_cfgs(2);
901         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
902         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
903         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
904         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
905
906         let amt_msat = 60_000;
907         let expiry_secs = 60 * 60;
908         let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs).unwrap();
909
910         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
911                 .with_features(channelmanager::provided_invoice_features());
912         let scorer = test_utils::TestScorer::with_penalty(0);
913         let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
914         let random_seed_bytes = keys_manager.get_secure_random_bytes();
915         let route = get_route(
916                 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
917                 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
918                 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
919         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
920         check_added_monitors!(nodes[0], 1);
921
922         // Make sure to use `get_payment_preimage`
923         let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
924         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
925         assert_eq!(events.len(), 1);
926         pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
927         claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
928 }
929
930 #[test]
931 fn sent_probe_is_probe_of_sending_node() {
932         let chanmon_cfgs = create_chanmon_cfgs(3);
933         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
934         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
935         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
936
937         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
938         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
939
940         // First check we refuse to build a single-hop probe
941         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
942         assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
943
944         // Then build an actual two-hop probing path
945         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
946
947         match nodes[0].node.send_probe(route.paths[0].clone()) {
948                 Ok((payment_hash, payment_id)) => {
949                         assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
950                         assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
951                         assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
952                 },
953                 _ => panic!(),
954         }
955
956         get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
957         check_added_monitors!(nodes[0], 1);
958 }
959
960 #[test]
961 fn successful_probe_yields_event() {
962         let chanmon_cfgs = create_chanmon_cfgs(3);
963         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
964         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
965         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
966
967         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
968         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
969
970         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
971
972         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
973
974         // node[0] -- update_add_htlcs -> node[1]
975         check_added_monitors!(nodes[0], 1);
976         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
977         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
978         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
979         check_added_monitors!(nodes[1], 0);
980         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
981         expect_pending_htlcs_forwardable!(nodes[1]);
982
983         // node[1] -- update_add_htlcs -> node[2]
984         check_added_monitors!(nodes[1], 1);
985         let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
986         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
987         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
988         check_added_monitors!(nodes[2], 0);
989         commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
990
991         // node[1] <- update_fail_htlcs -- node[2]
992         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
993         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
994         check_added_monitors!(nodes[1], 0);
995         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
996
997         // node[0] <- update_fail_htlcs -- node[1]
998         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
999         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1000         check_added_monitors!(nodes[0], 0);
1001         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1002
1003         let mut events = nodes[0].node.get_and_clear_pending_events();
1004         assert_eq!(events.len(), 1);
1005         match events.drain(..).next().unwrap() {
1006                 crate::util::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1007                         assert_eq!(payment_id, ev_pid);
1008                         assert_eq!(payment_hash, ev_ph);
1009                 },
1010                 _ => panic!(),
1011         };
1012 }
1013
1014 #[test]
1015 fn failed_probe_yields_event() {
1016         let chanmon_cfgs = create_chanmon_cfgs(3);
1017         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1018         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1019         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1020
1021         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1022         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1023
1024         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id());
1025
1026         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
1027
1028         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1029
1030         // node[0] -- update_add_htlcs -> node[1]
1031         check_added_monitors!(nodes[0], 1);
1032         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1033         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1034         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1035         check_added_monitors!(nodes[1], 0);
1036         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1037         expect_pending_htlcs_forwardable!(nodes[1]);
1038
1039         // node[0] <- update_fail_htlcs -- node[1]
1040         check_added_monitors!(nodes[1], 1);
1041         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1042         // Skip the PendingHTLCsForwardable event
1043         let _events = nodes[1].node.get_and_clear_pending_events();
1044         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1045         check_added_monitors!(nodes[0], 0);
1046         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1047
1048         let mut events = nodes[0].node.get_and_clear_pending_events();
1049         assert_eq!(events.len(), 1);
1050         match events.drain(..).next().unwrap() {
1051                 crate::util::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1052                         assert_eq!(payment_id, ev_pid);
1053                         assert_eq!(payment_hash, ev_ph);
1054                 },
1055                 _ => panic!(),
1056         };
1057 }
1058
1059 #[test]
1060 fn onchain_failed_probe_yields_event() {
1061         // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1062         // event.
1063         let chanmon_cfgs = create_chanmon_cfgs(3);
1064         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1065         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1066         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1067
1068         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1069         create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1070
1071         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id());
1072
1073         // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1074         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1075         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1076
1077         // node[0] -- update_add_htlcs -> node[1]
1078         check_added_monitors!(nodes[0], 1);
1079         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1080         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1081         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1082         check_added_monitors!(nodes[1], 0);
1083         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1084         expect_pending_htlcs_forwardable!(nodes[1]);
1085
1086         check_added_monitors!(nodes[1], 1);
1087         let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1088
1089         // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1090         // Node A, which after 6 confirmations should result in a probe failure event.
1091         let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1092         confirm_transaction(&nodes[0], &bs_txn[0]);
1093         check_closed_broadcast!(&nodes[0], true);
1094         check_added_monitors!(nodes[0], 1);
1095
1096         let mut events = nodes[0].node.get_and_clear_pending_events();
1097         assert_eq!(events.len(), 2);
1098         let mut found_probe_failed = false;
1099         for event in events.drain(..) {
1100                 match event {
1101                         Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1102                                 assert_eq!(payment_id, ev_pid);
1103                                 assert_eq!(payment_hash, ev_ph);
1104                                 found_probe_failed = true;
1105                         },
1106                         Event::ChannelClosed { .. } => {},
1107                         _ => panic!(),
1108                 }
1109         }
1110         assert!(found_probe_failed);
1111 }
1112
1113 #[test]
1114 fn claimed_send_payment_idempotent() {
1115         // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1116         let chanmon_cfgs = create_chanmon_cfgs(2);
1117         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1118         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1119         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1120
1121         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1122
1123         let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1124         let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1125
1126         macro_rules! check_send_rejected {
1127                 () => {
1128                         // If we try to resend a new payment with a different payment_hash but with the same
1129                         // payment_id, it should be rejected.
1130                         let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1131                         match send_result {
1132                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1133                                 _ => panic!("Unexpected send result: {:?}", send_result),
1134                         }
1135
1136                         // Further, if we try to send a spontaneous payment with the same payment_id it should
1137                         // also be rejected.
1138                         let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1139                         match send_result {
1140                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1141                                 _ => panic!("Unexpected send result: {:?}", send_result),
1142                         }
1143                 }
1144         }
1145
1146         check_send_rejected!();
1147
1148         // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1149         // not been seen by the user. At this point, from the user perspective nothing has changed, so
1150         // we must remain just as idempotent as we were before.
1151         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1152
1153         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1154                 nodes[0].node.timer_tick_occurred();
1155         }
1156
1157         check_send_rejected!();
1158
1159         // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1160         // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1161         // the payment complete. However, they could have called `send_payment` while the event was
1162         // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1163         // after the event is handled a duplicate payment should sitll be rejected.
1164         expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1165         check_send_rejected!();
1166
1167         // If relatively little time has passed, a duplicate payment should still fail.
1168         nodes[0].node.timer_tick_occurred();
1169         check_send_rejected!();
1170
1171         // However, after some time has passed (at least more than the one timer tick above), a
1172         // duplicate payment should go through, as ChannelManager should no longer have any remaining
1173         // references to the old payment data.
1174         for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1175                 nodes[0].node.timer_tick_occurred();
1176         }
1177
1178         nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1179         check_added_monitors!(nodes[0], 1);
1180         pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1181         claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1182 }
1183
1184 #[test]
1185 fn abandoned_send_payment_idempotent() {
1186         // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1187         // abandon_payment.
1188         let chanmon_cfgs = create_chanmon_cfgs(2);
1189         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1190         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1191         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1192
1193         create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1194
1195         let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1196         let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1197
1198         macro_rules! check_send_rejected {
1199                 () => {
1200                         // If we try to resend a new payment with a different payment_hash but with the same
1201                         // payment_id, it should be rejected.
1202                         let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1203                         match send_result {
1204                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1205                                 _ => panic!("Unexpected send result: {:?}", send_result),
1206                         }
1207
1208                         // Further, if we try to send a spontaneous payment with the same payment_id it should
1209                         // also be rejected.
1210                         let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1211                         match send_result {
1212                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1213                                 _ => panic!("Unexpected send result: {:?}", send_result),
1214                         }
1215                 }
1216         }
1217
1218         check_send_rejected!();
1219
1220         nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1221         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1222
1223         pass_failed_payment_back_no_abandon(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash);
1224         check_send_rejected!();
1225
1226         // Until we abandon the payment, no matter how many timer ticks pass, we still cannot reuse the
1227         // PaymentId.
1228         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1229                 nodes[0].node.timer_tick_occurred();
1230         }
1231         check_send_rejected!();
1232
1233         nodes[0].node.abandon_payment(payment_id);
1234         get_event!(nodes[0], Event::PaymentFailed);
1235
1236         // However, we can reuse the PaymentId immediately after we `abandon_payment`.
1237         nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1238         check_added_monitors!(nodes[0], 1);
1239         pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1240         claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1241 }