Update bitcoin crate to 0.29.0
[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, 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 });
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 });
460         let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
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(), 3);
512         let (first_htlc_timeout_tx, second_htlc_timeout_tx) = if as_htlc_timeout_txn[0] == as_commitment_tx {
513                 (&as_htlc_timeout_txn[1], &as_htlc_timeout_txn[2])
514         } else {
515                 assert_eq!(as_htlc_timeout_txn[2], as_commitment_tx);
516                 (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1])
517         };
518         check_spends!(first_htlc_timeout_tx, as_commitment_tx);
519         check_spends!(second_htlc_timeout_tx, as_commitment_tx);
520         if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
521                 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
522         } else {
523                 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
524         }
525         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
526         expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
527
528         // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
529         // reloaded) via a route over the new channel, which work without issue and eventually be
530         // received and claimed at the recipient just like any other payment.
531         let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
532
533         // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
534         // and not the original fee. We also update node[1]'s relevant config as
535         // do_claim_payment_along_route expects us to never overpay.
536         {
537                 let mut channel_state = nodes[1].node.channel_state.lock().unwrap();
538                 let mut channel = channel_state.by_id.get_mut(&chan_id_2).unwrap();
539                 let mut new_config = channel.config();
540                 new_config.forwarding_fee_base_msat += 100_000;
541                 channel.update_config(&new_config);
542                 new_route.paths[0][0].fee_msat += 100_000;
543         }
544
545         // Force expiration of the channel's previous config.
546         for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
547                 nodes[1].node.timer_tick_occurred();
548         }
549
550         assert!(nodes[0].node.retry_payment(&new_route, payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
551         nodes[0].node.retry_payment(&new_route, payment_id).unwrap();
552         check_added_monitors!(nodes[0], 1);
553         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
554         assert_eq!(events.len(), 1);
555         pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
556         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
557         expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
558 }
559
560 #[test]
561 fn retry_with_no_persist() {
562         do_retry_with_no_persist(true);
563         do_retry_with_no_persist(false);
564 }
565
566 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
567         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
568         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
569         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
570         // the ChannelMonitor tells it to.
571         //
572         // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
573         // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
574         // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
575         let chanmon_cfgs = create_chanmon_cfgs(2);
576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
578         let persister: test_utils::TestPersister;
579         let new_chain_monitor: test_utils::TestChainMonitor;
580         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
581         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
582
583         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
584
585         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
586         // nodes[0].
587         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
588         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
589         check_closed_broadcast!(nodes[0], true);
590         check_added_monitors!(nodes[0], 1);
591         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
592
593         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
594         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
595
596         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
597         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
598         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
599         assert_eq!(node_txn.len(), 3);
600         assert_eq!(node_txn[0], node_txn[1]);
601         check_spends!(node_txn[1], funding_tx);
602         check_spends!(node_txn[2], node_txn[1]);
603         let timeout_txn = vec![node_txn[2].clone()];
604
605         nodes[1].node.claim_funds(payment_preimage);
606         check_added_monitors!(nodes[1], 1);
607         expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
608
609         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
610         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
611         check_closed_broadcast!(nodes[1], true);
612         check_added_monitors!(nodes[1], 1);
613         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
614         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
615         assert_eq!(claim_txn.len(), 3);
616         check_spends!(claim_txn[0], node_txn[1]);
617         check_spends!(claim_txn[1], funding_tx);
618         check_spends!(claim_txn[2], claim_txn[1]);
619
620         header.prev_blockhash = nodes[0].best_block_hash();
621         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
622
623         if confirm_commitment_tx {
624                 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
625         }
626
627         header.prev_blockhash = nodes[0].best_block_hash();
628         let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
629
630         if payment_timeout {
631                 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
632                 connect_block(&nodes[0], &claim_block);
633                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
634         }
635
636         // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
637         // returning TemporaryFailure. This should cause the claim event to never make its way to the
638         // ChannelManager.
639         chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
640         chanmon_cfgs[0].persister.set_update_ret(Err(ChannelMonitorUpdateErr::TemporaryFailure));
641
642         if payment_timeout {
643                 connect_blocks(&nodes[0], 1);
644         } else {
645                 connect_block(&nodes[0], &claim_block);
646         }
647
648         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
649         let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
650                 .get_mut(&funding_txo).unwrap().drain().collect();
651         // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice
652         assert!(mon_updates.len() == 1 || mon_updates.len() == 2);
653         assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
654         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
655
656         // If we persist the ChannelManager here, we should get the PaymentSent event after
657         // deserialization.
658         let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
659         if !persist_manager_post_event {
660                 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
661         }
662
663         // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
664         // payment sent event.
665         chanmon_cfgs[0].persister.set_update_ret(Ok(()));
666         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
667         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
668         for update in mon_updates {
669                 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
670         }
671         if payment_timeout {
672                 expect_payment_failed!(nodes[0], payment_hash, true);
673         } else {
674                 expect_payment_sent!(nodes[0], payment_preimage);
675         }
676
677         // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
678         // twice.
679         if persist_manager_post_event {
680                 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
681         }
682
683         // Now reload nodes[0]...
684         persister = test_utils::TestPersister::new();
685         let keys_manager = &chanmon_cfgs[0].keys_manager;
686         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);
687         nodes[0].chain_monitor = &new_chain_monitor;
688         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
689         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
690                 &mut chan_0_monitor_read, keys_manager).unwrap();
691         assert!(chan_0_monitor_read.is_empty());
692
693         let (_, nodes_0_deserialized_tmp) = {
694                 let mut channel_monitors = HashMap::new();
695                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
696                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
697                         ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
698                                 default_config: Default::default(),
699                                 keys_manager,
700                                 fee_estimator: node_cfgs[0].fee_estimator,
701                                 chain_monitor: nodes[0].chain_monitor,
702                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
703                                 logger: nodes[0].logger,
704                                 channel_monitors,
705                         }).unwrap()
706         };
707         nodes_0_deserialized = nodes_0_deserialized_tmp;
708
709         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
710         check_added_monitors!(nodes[0], 1);
711         nodes[0].node = &nodes_0_deserialized;
712
713         if persist_manager_post_event {
714                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
715         } else if payment_timeout {
716                 expect_payment_failed!(nodes[0], payment_hash, true);
717         } else {
718                 expect_payment_sent!(nodes[0], payment_preimage);
719         }
720
721         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
722         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
723         // payment events should kick in, leaving us with no pending events here.
724         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
725         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
726         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
727 }
728
729 #[test]
730 fn test_dup_htlc_onchain_fails_on_reload() {
731         do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
732         do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
733         do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
734         do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
735         do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
736         do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
737 }
738
739 #[test]
740 fn test_fulfill_restart_failure() {
741         // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
742         // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
743         // again, or fail it, giving us free money.
744         //
745         // Of course probably they won't fail it and give us free money, but because we have code to
746         // handle it, we should test the logic for it anyway. We do that here.
747         let chanmon_cfgs = create_chanmon_cfgs(2);
748         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
749         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
750         let persister: test_utils::TestPersister;
751         let new_chain_monitor: test_utils::TestChainMonitor;
752         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
753         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
754
755         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
756         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
757
758         // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
759         // pre-fulfill, which we do by serializing it here.
760         let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
761         nodes[1].node.write(&mut chan_manager_serialized).unwrap();
762         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
763         get_monitor!(nodes[1], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
764
765         nodes[1].node.claim_funds(payment_preimage);
766         check_added_monitors!(nodes[1], 1);
767         expect_payment_claimed!(nodes[1], payment_hash, 100_000);
768
769         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
770         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
771         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
772
773         // Now reload nodes[1]...
774         persister = test_utils::TestPersister::new();
775         let keys_manager = &chanmon_cfgs[1].keys_manager;
776         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);
777         nodes[1].chain_monitor = &new_chain_monitor;
778         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
779         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
780                 &mut chan_0_monitor_read, keys_manager).unwrap();
781         assert!(chan_0_monitor_read.is_empty());
782
783         let (_, nodes_1_deserialized_tmp) = {
784                 let mut channel_monitors = HashMap::new();
785                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
786                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
787                         ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
788                                 default_config: Default::default(),
789                                 keys_manager,
790                                 fee_estimator: node_cfgs[1].fee_estimator,
791                                 chain_monitor: nodes[1].chain_monitor,
792                                 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
793                                 logger: nodes[1].logger,
794                                 channel_monitors,
795                         }).unwrap()
796         };
797         nodes_1_deserialized = nodes_1_deserialized_tmp;
798
799         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
800         check_added_monitors!(nodes[1], 1);
801         nodes[1].node = &nodes_1_deserialized;
802
803         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
804         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
805
806         nodes[1].node.fail_htlc_backwards(&payment_hash);
807         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
808         check_added_monitors!(nodes[1], 1);
809         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
810         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
811         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
812         // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
813         // it had already considered the payment fulfilled, and now they just got free money.
814         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
815 }
816
817 #[test]
818 fn get_ldk_payment_preimage() {
819         // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
820         let chanmon_cfgs = create_chanmon_cfgs(2);
821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
823         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
824         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
825
826         let amt_msat = 60_000;
827         let expiry_secs = 60 * 60;
828         let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs).unwrap();
829
830         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
831                 .with_features(InvoiceFeatures::known());
832         let scorer = test_utils::TestScorer::with_penalty(0);
833         let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
834         let random_seed_bytes = keys_manager.get_secure_random_bytes();
835         let route = get_route(
836                 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
837                 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
838                 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
839         let _payment_id = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
840         check_added_monitors!(nodes[0], 1);
841
842         // Make sure to use `get_payment_preimage`
843         let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
844         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
845         assert_eq!(events.len(), 1);
846         pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
847         claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
848 }
849
850 #[test]
851 fn sent_probe_is_probe_of_sending_node() {
852         let chanmon_cfgs = create_chanmon_cfgs(3);
853         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
854         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
855         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
856
857         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
858         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
859
860         // First check we refuse to build a single-hop probe
861         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
862         assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
863
864         // Then build an actual two-hop probing path
865         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
866
867         match nodes[0].node.send_probe(route.paths[0].clone()) {
868                 Ok((payment_hash, payment_id)) => {
869                         assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
870                         assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
871                         assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
872                 },
873                 _ => panic!(),
874         }
875
876         get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
877         check_added_monitors!(nodes[0], 1);
878 }
879
880 #[test]
881 fn successful_probe_yields_event() {
882         let chanmon_cfgs = create_chanmon_cfgs(3);
883         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
884         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
885         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
886
887         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
888         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
889
890         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
891
892         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
893
894         // node[0] -- update_add_htlcs -> node[1]
895         check_added_monitors!(nodes[0], 1);
896         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
897         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
898         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
899         check_added_monitors!(nodes[1], 0);
900         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
901         expect_pending_htlcs_forwardable!(nodes[1]);
902
903         // node[1] -- update_add_htlcs -> node[2]
904         check_added_monitors!(nodes[1], 1);
905         let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
906         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
907         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
908         check_added_monitors!(nodes[2], 0);
909         commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
910
911         // node[1] <- update_fail_htlcs -- node[2]
912         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
913         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
914         check_added_monitors!(nodes[1], 0);
915         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
916
917         // node[0] <- update_fail_htlcs -- node[1]
918         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
919         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
920         check_added_monitors!(nodes[0], 0);
921         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
922
923         let mut events = nodes[0].node.get_and_clear_pending_events();
924         assert_eq!(events.len(), 1);
925         match events.drain(..).next().unwrap() {
926                 crate::util::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
927                         assert_eq!(payment_id, ev_pid);
928                         assert_eq!(payment_hash, ev_ph);
929                 },
930                 _ => panic!(),
931         };
932 }
933
934 #[test]
935 fn failed_probe_yields_event() {
936         let chanmon_cfgs = create_chanmon_cfgs(3);
937         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
938         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
939         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
940
941         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
942         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000, InitFeatures::known(), InitFeatures::known());
943
944         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id());
945
946         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
947
948         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
949
950         // node[0] -- update_add_htlcs -> node[1]
951         check_added_monitors!(nodes[0], 1);
952         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
953         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
954         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
955         check_added_monitors!(nodes[1], 0);
956         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
957         expect_pending_htlcs_forwardable!(nodes[1]);
958
959         // node[0] <- update_fail_htlcs -- node[1]
960         check_added_monitors!(nodes[1], 1);
961         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
962         // Skip the PendingHTLCsForwardable event
963         let _events = nodes[1].node.get_and_clear_pending_events();
964         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
965         check_added_monitors!(nodes[0], 0);
966         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
967
968         let mut events = nodes[0].node.get_and_clear_pending_events();
969         assert_eq!(events.len(), 1);
970         match events.drain(..).next().unwrap() {
971                 crate::util::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
972                         assert_eq!(payment_id, ev_pid);
973                         assert_eq!(payment_hash, ev_ph);
974                 },
975                 _ => panic!(),
976         };
977 }