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