1 // This file is Copyright its original authors, visible in version control
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
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.
14 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
15 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitor, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::chain::transaction::OutPoint;
17 use crate::chain::keysinterface::KeysInterface;
18 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
19 use crate::ln::channelmanager::{self, BREAKDOWN_TIMEOUT, ChannelManager, ChannelManagerReadArgs, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS};
21 use crate::ln::msgs::ChannelMessageHandler;
22 use crate::routing::router::{PaymentParameters, get_route};
23 use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
24 use crate::util::test_utils;
25 use crate::util::errors::APIError;
26 use crate::util::enforcing_trait_impls::EnforcingSigner;
27 use crate::util::ser::{ReadableArgs, Writeable};
30 use bitcoin::{Block, BlockHeader, BlockHash, TxMerkleNode};
31 use bitcoin::hashes::Hash;
32 use bitcoin::network::constants::Network;
34 use crate::prelude::*;
36 use crate::ln::functional_test_utils::*;
39 fn retry_single_path_payment() {
40 let chanmon_cfgs = create_chanmon_cfgs(3);
41 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
42 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
43 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
45 let _chan_0 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
46 let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
47 // Rebalance to find a route
48 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
50 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
52 // Rebalance so that the first hop fails.
53 send_payment(&nodes[1], &vec!(&nodes[2])[..], 2_000_000);
55 // Make sure the payment fails on the first hop.
56 let payment_id = PaymentId(payment_hash.0);
57 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), payment_id).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());
77 // Rebalance the channel so the retry succeeds.
78 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
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);
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);
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);
99 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
100 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
101 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
102 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
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);
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);
124 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
125 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
126 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
127 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
129 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
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;
141 // Initiate the MPP payment.
142 let payment_id = PaymentId(payment_hash.0);
143 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), payment_id).unwrap();
144 check_added_monitors!(nodes[0], 2); // one monitor per path
145 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
146 assert_eq!(events.len(), 2);
148 // Pass half of the payment along the success path.
149 let success_path_msgs = events.remove(0);
150 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
152 // Add the HTLC along the first hop.
153 let fail_path_msgs_1 = events.remove(0);
154 let (update_add, commitment_signed) = match fail_path_msgs_1 {
155 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 } } => {
156 assert_eq!(update_add_htlcs.len(), 1);
157 assert!(update_fail_htlcs.is_empty());
158 assert!(update_fulfill_htlcs.is_empty());
159 assert!(update_fail_malformed_htlcs.is_empty());
160 assert!(update_fee.is_none());
161 (update_add_htlcs[0].clone(), commitment_signed.clone())
163 _ => panic!("Unexpected event"),
165 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
166 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
168 // Attempt to forward the payment and complete the 2nd path's failure.
169 expect_pending_htlcs_forwardable!(&nodes[2]);
170 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 }]);
171 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
172 assert!(htlc_updates.update_add_htlcs.is_empty());
173 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
174 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
175 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
176 check_added_monitors!(nodes[2], 1);
177 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
178 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
179 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
181 // Rebalance the channel so the second half of the payment can succeed.
182 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
184 // Make sure it errors as expected given a too-large amount.
185 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = nodes[0].node.retry_payment(&route, payment_id) {
186 assert!(err.contains("over total_payment_amt_msat"));
187 } else { panic!("Unexpected error"); }
189 // Make sure it errors as expected given the wrong payment_id.
190 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = nodes[0].node.retry_payment(&route, PaymentId([0; 32])) {
191 assert!(err.contains("not found"));
192 } else { panic!("Unexpected error"); }
194 // Retry the second half of the payment and make sure it succeeds.
195 let mut path = route.clone();
196 path.paths.remove(0);
197 nodes[0].node.retry_payment(&path, payment_id).unwrap();
198 check_added_monitors!(nodes[0], 1);
199 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
200 assert_eq!(events.len(), 1);
201 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
202 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
205 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
206 let chanmon_cfgs = create_chanmon_cfgs(4);
207 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
208 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
209 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
211 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
212 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
213 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
214 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
216 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
217 let path = route.paths[0].clone();
218 route.paths.push(path);
219 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
220 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
221 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
222 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
223 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
224 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
226 // Initiate the MPP payment.
227 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
228 check_added_monitors!(nodes[0], 2); // one monitor per path
229 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
230 assert_eq!(events.len(), 2);
232 // Pass half of the payment along the first path.
233 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), events.remove(0), false, None);
235 if send_partial_mpp {
236 // Time out the partial MPP
237 for _ in 0..MPP_TIMEOUT_TICKS {
238 nodes[3].node.timer_tick_occurred();
241 // Failed HTLC from node 3 -> 1
242 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
243 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
244 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
245 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
246 check_added_monitors!(nodes[3], 1);
247 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
249 // Failed HTLC from node 1 -> 0
250 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 }]);
251 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
252 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
253 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
254 check_added_monitors!(nodes[1], 1);
255 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
257 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
259 // Pass half of the payment along the second path.
260 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), events.remove(0), true, None);
262 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
263 for _ in 0..MPP_TIMEOUT_TICKS {
264 nodes[3].node.timer_tick_occurred();
267 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
272 fn mpp_receive_timeout() {
273 do_mpp_receive_timeout(true);
274 do_mpp_receive_timeout(false);
278 fn retry_expired_payment() {
279 let chanmon_cfgs = create_chanmon_cfgs(3);
280 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
281 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
282 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
284 let _chan_0 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
285 let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
286 // Rebalance to find a route
287 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
289 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
291 // Rebalance so that the first hop fails.
292 send_payment(&nodes[1], &vec!(&nodes[2])[..], 2_000_000);
294 // Make sure the payment fails on the first hop.
295 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
296 check_added_monitors!(nodes[0], 1);
297 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
298 assert_eq!(events.len(), 1);
299 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
300 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
301 check_added_monitors!(nodes[1], 0);
302 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
303 expect_pending_htlcs_forwardable!(nodes[1]);
304 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 }]);
305 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
306 assert!(htlc_updates.update_add_htlcs.is_empty());
307 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
308 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
309 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
310 check_added_monitors!(nodes[1], 1);
311 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
312 commitment_signed_dance!(nodes[0], nodes[1], htlc_updates.commitment_signed, false);
313 expect_payment_failed!(nodes[0], payment_hash, false);
315 // Mine blocks so the payment will have expired.
316 connect_blocks(&nodes[0], 3);
318 // Retry the payment and make sure it errors as expected.
319 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = nodes[0].node.retry_payment(&route, PaymentId(payment_hash.0)) {
320 assert!(err.contains("not found"));
322 panic!("Unexpected error");
327 fn no_pending_leak_on_initial_send_failure() {
328 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
329 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
330 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
331 // pending payment forever and never time it out.
332 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
333 // try, and then check that no pending payment is being tracked.
334 let chanmon_cfgs = create_chanmon_cfgs(2);
335 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
336 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
337 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
339 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
341 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
343 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
344 nodes[1].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
346 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)),
347 true, APIError::ChannelUnavailable { ref err },
348 assert_eq!(err, "Peer for first hop currently disconnected/pending monitor update!"));
350 assert!(!nodes[0].node.has_pending_payments());
353 fn do_retry_with_no_persist(confirm_before_reload: bool) {
354 // If we send a pending payment and `send_payment` returns success, we should always either
355 // return a payment failure event or a payment success event, and on failure the payment should
358 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
359 // always persisted asynchronously), the ChannelManager has to reload some payment data from
360 // ChannelMonitor(s) in some cases. This tests that reloading.
362 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
363 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
364 // which has separate codepaths for "commitment transaction already confirmed" and not.
365 let chanmon_cfgs = create_chanmon_cfgs(3);
366 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
367 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
368 let persister: test_utils::TestPersister;
369 let new_chain_monitor: test_utils::TestChainMonitor;
370 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
371 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
373 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
374 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
376 // Serialize the ChannelManager prior to sending payments
377 let nodes_0_serialized = nodes[0].node.encode();
379 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
381 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
382 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
383 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
384 check_added_monitors!(nodes[0], 1);
386 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
387 assert_eq!(events.len(), 1);
388 let payment_event = SendEvent::from_event(events.pop().unwrap());
389 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
391 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
392 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
393 // which would prevent retry.
394 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
395 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
397 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
398 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
399 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
400 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
402 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
404 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
405 if confirm_before_reload {
406 mine_transaction(&nodes[0], &as_commitment_tx);
407 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
410 // The ChannelMonitor should always be the latest version, as we're required to persist it
411 // during the `commitment_signed_dance!()`.
412 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
413 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
415 persister = test_utils::TestPersister::new();
416 let keys_manager = &chanmon_cfgs[0].keys_manager;
417 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);
418 nodes[0].chain_monitor = &new_chain_monitor;
419 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
420 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
421 &mut chan_0_monitor_read, keys_manager).unwrap();
422 assert!(chan_0_monitor_read.is_empty());
424 let mut nodes_0_read = &nodes_0_serialized[..];
425 let (_, nodes_0_deserialized_tmp) = {
426 let mut channel_monitors = HashMap::new();
427 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
428 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
429 default_config: test_default_channel_config(),
431 fee_estimator: node_cfgs[0].fee_estimator,
432 chain_monitor: nodes[0].chain_monitor,
433 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
434 logger: nodes[0].logger,
438 nodes_0_deserialized = nodes_0_deserialized_tmp;
439 assert!(nodes_0_read.is_empty());
441 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
442 ChannelMonitorUpdateStatus::Completed);
443 nodes[0].node = &nodes_0_deserialized;
444 check_added_monitors!(nodes[0], 1);
446 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
447 // force-close the channel.
448 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
449 assert!(nodes[0].node.list_channels().is_empty());
450 assert!(nodes[0].node.has_pending_payments());
451 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
452 assert_eq!(as_broadcasted_txn.len(), 1);
453 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
455 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
456 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
457 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
459 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
460 // error, as the channel has hit the chain.
461 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
462 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
463 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
464 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
465 assert_eq!(as_err.len(), 1);
467 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
468 assert_eq!(node_id, nodes[1].node.get_our_node_id());
469 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
470 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_string() });
471 check_added_monitors!(nodes[1], 1);
472 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
474 _ => panic!("Unexpected event"),
476 check_closed_broadcast!(nodes[1], false);
478 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
479 // we close in a moment.
480 nodes[2].node.claim_funds(payment_preimage_1);
481 check_added_monitors!(nodes[2], 1);
482 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
484 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
485 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
486 check_added_monitors!(nodes[1], 1);
487 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
489 if confirm_before_reload {
490 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
491 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
494 // Create a new channel on which to retry the payment before we fail the payment via the
495 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
496 // connecting several blocks while creating the channel (implying time has passed).
497 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
498 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
500 mine_transaction(&nodes[1], &as_commitment_tx);
501 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
502 assert_eq!(bs_htlc_claim_txn.len(), 1);
503 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
504 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
506 if !confirm_before_reload {
507 mine_transaction(&nodes[0], &as_commitment_tx);
509 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
510 expect_payment_sent!(nodes[0], payment_preimage_1);
511 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
512 let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
513 assert_eq!(as_htlc_timeout_txn.len(), 2);
514 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1]);
515 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
516 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
517 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
518 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
520 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
522 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
523 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
525 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
526 // reloaded) via a route over the new channel, which work without issue and eventually be
527 // received and claimed at the recipient just like any other payment.
528 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
530 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
531 // and not the original fee. We also update node[1]'s relevant config as
532 // do_claim_payment_along_route expects us to never overpay.
534 let mut channel_state = nodes[1].node.channel_state.lock().unwrap();
535 let mut channel = channel_state.by_id.get_mut(&chan_id_2).unwrap();
536 let mut new_config = channel.config();
537 new_config.forwarding_fee_base_msat += 100_000;
538 channel.update_config(&new_config);
539 new_route.paths[0][0].fee_msat += 100_000;
542 // Force expiration of the channel's previous config.
543 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
544 nodes[1].node.timer_tick_occurred();
547 assert!(nodes[0].node.retry_payment(&new_route, payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
548 nodes[0].node.retry_payment(&new_route, PaymentId(payment_hash.0)).unwrap();
549 check_added_monitors!(nodes[0], 1);
550 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
551 assert_eq!(events.len(), 1);
552 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
553 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
554 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
558 fn retry_with_no_persist() {
559 do_retry_with_no_persist(true);
560 do_retry_with_no_persist(false);
563 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
564 // Test that an off-chain completed payment is not retryable on restart. This was previously
565 // broken for dust payments, but we test for both dust and non-dust payments.
567 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
569 let chanmon_cfgs = create_chanmon_cfgs(3);
570 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
572 let mut manually_accept_config = test_default_channel_config();
573 manually_accept_config.manually_accept_inbound_channels = true;
575 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
577 let first_persister: test_utils::TestPersister;
578 let first_new_chain_monitor: test_utils::TestChainMonitor;
579 let first_nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
580 let second_persister: test_utils::TestPersister;
581 let second_new_chain_monitor: test_utils::TestChainMonitor;
582 let second_nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
583 let third_persister: test_utils::TestPersister;
584 let third_new_chain_monitor: test_utils::TestChainMonitor;
585 let third_nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
587 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
589 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
590 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
591 confirm_transaction(&nodes[0], &funding_tx);
592 confirm_transaction(&nodes[1], &funding_tx);
593 // Ignore the announcement_signatures messages
594 nodes[0].node.get_and_clear_pending_msg_events();
595 nodes[1].node.get_and_clear_pending_msg_events();
596 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
598 // Serialize the ChannelManager prior to sending payments
599 let mut nodes_0_serialized = nodes[0].node.encode();
601 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
602 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 });
604 // The ChannelMonitor should always be the latest version, as we're required to persist it
605 // during the `commitment_signed_dance!()`.
606 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
607 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
609 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
611 macro_rules! reload_node {
612 ($chain_monitor: ident, $chan_manager: ident, $persister: ident) => { {
613 $persister = test_utils::TestPersister::new();
614 let keys_manager = &chanmon_cfgs[0].keys_manager;
615 $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);
616 nodes[0].chain_monitor = &$chain_monitor;
617 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
618 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
619 &mut chan_0_monitor_read, keys_manager).unwrap();
620 assert!(chan_0_monitor_read.is_empty());
622 let mut chan_1_monitor = None;
623 let mut channel_monitors = HashMap::new();
624 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
626 if !chan_1_monitor_serialized.0.is_empty() {
627 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
628 chan_1_monitor = Some(<(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
629 &mut chan_1_monitor_read, keys_manager).unwrap().1);
630 assert!(chan_1_monitor_read.is_empty());
631 channel_monitors.insert(chan_1_monitor.as_ref().unwrap().get_funding_txo().0, chan_1_monitor.as_mut().unwrap());
634 let mut nodes_0_read = &nodes_0_serialized[..];
635 let (_, nodes_0_deserialized_tmp) = {
636 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
637 default_config: test_default_channel_config(),
639 fee_estimator: node_cfgs[0].fee_estimator,
640 chain_monitor: nodes[0].chain_monitor,
641 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
642 logger: nodes[0].logger,
646 $chan_manager = nodes_0_deserialized_tmp;
647 assert!(nodes_0_read.is_empty());
649 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
650 ChannelMonitorUpdateStatus::Completed);
651 if !chan_1_monitor_serialized.0.is_empty() {
652 let funding_txo = chan_1_monitor.as_ref().unwrap().get_funding_txo().0;
653 assert_eq!(nodes[0].chain_monitor.watch_channel(funding_txo, chan_1_monitor.unwrap()),
654 ChannelMonitorUpdateStatus::Completed);
656 nodes[0].node = &$chan_manager;
657 check_added_monitors!(nodes[0], if !chan_1_monitor_serialized.0.is_empty() { 2 } else { 1 });
659 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
663 reload_node!(first_new_chain_monitor, first_nodes_0_deserialized, first_persister);
665 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
666 // force-close the channel.
667 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
668 assert!(nodes[0].node.list_channels().is_empty());
669 assert!(nodes[0].node.has_pending_payments());
670 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
672 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
673 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
675 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
676 // error, as the channel has hit the chain.
677 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
678 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
679 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
680 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
681 assert_eq!(as_err.len(), 1);
682 let bs_commitment_tx;
684 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
685 assert_eq!(node_id, nodes[1].node.get_our_node_id());
686 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
687 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_string() });
688 check_added_monitors!(nodes[1], 1);
689 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
691 _ => panic!("Unexpected event"),
693 check_closed_broadcast!(nodes[1], false);
695 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
696 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
697 // incoming HTLCs with the same payment hash later.
698 nodes[2].node.fail_htlc_backwards(&payment_hash);
699 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
700 check_added_monitors!(nodes[2], 1);
702 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
703 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
704 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
705 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
706 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
708 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
709 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
710 // after the commitment transaction, so always connect the commitment transaction.
711 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
712 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
714 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
715 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
716 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
717 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
718 assert_eq!(as_htlc_timeout.len(), 1);
720 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
721 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
722 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
723 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
726 // Create a new channel on which to retry the payment before we fail the payment via the
727 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
728 // connecting several blocks while creating the channel (implying time has passed).
729 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
730 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
731 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
733 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
734 // confirming, we will fail as it's considered still-pending...
735 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
736 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
737 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
739 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
740 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
741 // (which should also still work).
742 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
743 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
744 // We set mpp_parts_remain to avoid having abandon_payment called
745 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
747 chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
748 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
749 chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
750 get_monitor!(nodes[0], chan_id_3).write(&mut chan_1_monitor_serialized).unwrap();
751 nodes_0_serialized = nodes[0].node.encode();
753 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
754 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
756 reload_node!(second_new_chain_monitor, second_nodes_0_deserialized, second_persister);
757 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
759 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
760 // the payment is not (spuriously) listed as still pending.
761 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
762 check_added_monitors!(nodes[0], 1);
763 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
764 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
766 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
767 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
769 chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
770 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
771 chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
772 get_monitor!(nodes[0], chan_id_3).write(&mut chan_1_monitor_serialized).unwrap();
773 nodes_0_serialized = nodes[0].node.encode();
775 // Ensure that after reload we cannot retry the payment.
776 reload_node!(third_new_chain_monitor, third_nodes_0_deserialized, third_persister);
777 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
779 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
780 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
784 fn test_completed_payment_not_retryable_on_reload() {
785 do_test_completed_payment_not_retryable_on_reload(true);
786 do_test_completed_payment_not_retryable_on_reload(false);
790 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
791 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
792 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
793 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
794 // the ChannelMonitor tells it to.
796 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
797 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
798 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
799 let chanmon_cfgs = create_chanmon_cfgs(2);
800 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
801 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
802 let persister: test_utils::TestPersister;
803 let new_chain_monitor: test_utils::TestChainMonitor;
804 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
805 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
807 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
809 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
811 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
812 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
813 check_closed_broadcast!(nodes[0], true);
814 check_added_monitors!(nodes[0], 1);
815 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
817 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
818 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
820 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
821 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
822 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
823 assert_eq!(node_txn.len(), 3);
824 assert_eq!(node_txn[0], node_txn[1]);
825 check_spends!(node_txn[1], funding_tx);
826 check_spends!(node_txn[2], node_txn[1]);
827 let timeout_txn = vec![node_txn[2].clone()];
829 nodes[1].node.claim_funds(payment_preimage);
830 check_added_monitors!(nodes[1], 1);
831 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
833 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
834 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
835 check_closed_broadcast!(nodes[1], true);
836 check_added_monitors!(nodes[1], 1);
837 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
838 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
839 assert_eq!(claim_txn.len(), 3);
840 check_spends!(claim_txn[0], node_txn[1]);
841 check_spends!(claim_txn[1], funding_tx);
842 check_spends!(claim_txn[2], claim_txn[1]);
844 header.prev_blockhash = nodes[0].best_block_hash();
845 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
847 if confirm_commitment_tx {
848 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
851 header.prev_blockhash = nodes[0].best_block_hash();
852 let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
855 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
856 connect_block(&nodes[0], &claim_block);
857 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
860 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
861 // returning InProgress. This should cause the claim event to never make its way to the
863 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
864 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
867 connect_blocks(&nodes[0], 1);
869 connect_block(&nodes[0], &claim_block);
872 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
873 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
874 .get_mut(&funding_txo).unwrap().drain().collect();
875 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice
876 assert!(mon_updates.len() == 1 || mon_updates.len() == 2);
877 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
878 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
880 // If we persist the ChannelManager here, we should get the PaymentSent event after
882 let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
883 if !persist_manager_post_event {
884 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
887 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
888 // payment sent event.
889 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
890 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
891 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
892 for update in mon_updates {
893 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
896 expect_payment_failed!(nodes[0], payment_hash, false);
898 expect_payment_sent!(nodes[0], payment_preimage);
901 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
903 if persist_manager_post_event {
904 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
907 // Now reload nodes[0]...
908 persister = test_utils::TestPersister::new();
909 let keys_manager = &chanmon_cfgs[0].keys_manager;
910 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);
911 nodes[0].chain_monitor = &new_chain_monitor;
912 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
913 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
914 &mut chan_0_monitor_read, keys_manager).unwrap();
915 assert!(chan_0_monitor_read.is_empty());
917 let (_, nodes_0_deserialized_tmp) = {
918 let mut channel_monitors = HashMap::new();
919 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
920 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
921 ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
922 default_config: Default::default(),
924 fee_estimator: node_cfgs[0].fee_estimator,
925 chain_monitor: nodes[0].chain_monitor,
926 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
927 logger: nodes[0].logger,
931 nodes_0_deserialized = nodes_0_deserialized_tmp;
933 assert_eq!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
934 ChannelMonitorUpdateStatus::Completed);
935 check_added_monitors!(nodes[0], 1);
936 nodes[0].node = &nodes_0_deserialized;
938 if persist_manager_post_event {
939 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
940 } else if payment_timeout {
941 expect_payment_failed!(nodes[0], payment_hash, false);
943 expect_payment_sent!(nodes[0], payment_preimage);
946 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
947 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
948 // payment events should kick in, leaving us with no pending events here.
949 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
950 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
951 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
955 fn test_dup_htlc_onchain_fails_on_reload() {
956 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
957 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
958 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
959 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
960 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
961 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
965 fn test_fulfill_restart_failure() {
966 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
967 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
968 // again, or fail it, giving us free money.
970 // Of course probably they won't fail it and give us free money, but because we have code to
971 // handle it, we should test the logic for it anyway. We do that here.
972 let chanmon_cfgs = create_chanmon_cfgs(2);
973 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
974 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
975 let persister: test_utils::TestPersister;
976 let new_chain_monitor: test_utils::TestChainMonitor;
977 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
978 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
980 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
981 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
983 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
984 // pre-fulfill, which we do by serializing it here.
985 let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
986 nodes[1].node.write(&mut chan_manager_serialized).unwrap();
987 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
988 get_monitor!(nodes[1], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
990 nodes[1].node.claim_funds(payment_preimage);
991 check_added_monitors!(nodes[1], 1);
992 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
994 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
995 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
996 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
998 // Now reload nodes[1]...
999 persister = test_utils::TestPersister::new();
1000 let keys_manager = &chanmon_cfgs[1].keys_manager;
1001 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);
1002 nodes[1].chain_monitor = &new_chain_monitor;
1003 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
1004 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
1005 &mut chan_0_monitor_read, keys_manager).unwrap();
1006 assert!(chan_0_monitor_read.is_empty());
1008 let (_, nodes_1_deserialized_tmp) = {
1009 let mut channel_monitors = HashMap::new();
1010 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
1011 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
1012 ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
1013 default_config: Default::default(),
1015 fee_estimator: node_cfgs[1].fee_estimator,
1016 chain_monitor: nodes[1].chain_monitor,
1017 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
1018 logger: nodes[1].logger,
1022 nodes_1_deserialized = nodes_1_deserialized_tmp;
1024 assert_eq!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor),
1025 ChannelMonitorUpdateStatus::Completed);
1026 check_added_monitors!(nodes[1], 1);
1027 nodes[1].node = &nodes_1_deserialized;
1029 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1030 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
1032 nodes[1].node.fail_htlc_backwards(&payment_hash);
1033 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1034 check_added_monitors!(nodes[1], 1);
1035 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1036 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1037 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1038 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1039 // it had already considered the payment fulfilled, and now they just got free money.
1040 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1044 fn get_ldk_payment_preimage() {
1045 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1046 let chanmon_cfgs = create_chanmon_cfgs(2);
1047 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1048 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1049 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1050 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1052 let amt_msat = 60_000;
1053 let expiry_secs = 60 * 60;
1054 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs).unwrap();
1056 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
1057 .with_features(channelmanager::provided_invoice_features());
1058 let scorer = test_utils::TestScorer::with_penalty(0);
1059 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1060 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1061 let route = get_route(
1062 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
1063 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
1064 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
1065 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1066 check_added_monitors!(nodes[0], 1);
1068 // Make sure to use `get_payment_preimage`
1069 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1070 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1071 assert_eq!(events.len(), 1);
1072 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1073 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1077 fn sent_probe_is_probe_of_sending_node() {
1078 let chanmon_cfgs = create_chanmon_cfgs(3);
1079 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1080 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1081 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1083 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1084 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1086 // First check we refuse to build a single-hop probe
1087 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1088 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1090 // Then build an actual two-hop probing path
1091 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1093 match nodes[0].node.send_probe(route.paths[0].clone()) {
1094 Ok((payment_hash, payment_id)) => {
1095 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1096 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1097 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1102 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1103 check_added_monitors!(nodes[0], 1);
1107 fn successful_probe_yields_event() {
1108 let chanmon_cfgs = create_chanmon_cfgs(3);
1109 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1110 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1111 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1113 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1114 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1116 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1118 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1120 // node[0] -- update_add_htlcs -> node[1]
1121 check_added_monitors!(nodes[0], 1);
1122 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1123 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1124 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1125 check_added_monitors!(nodes[1], 0);
1126 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1127 expect_pending_htlcs_forwardable!(nodes[1]);
1129 // node[1] -- update_add_htlcs -> node[2]
1130 check_added_monitors!(nodes[1], 1);
1131 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1132 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1133 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1134 check_added_monitors!(nodes[2], 0);
1135 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
1137 // node[1] <- update_fail_htlcs -- node[2]
1138 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1139 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1140 check_added_monitors!(nodes[1], 0);
1141 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1143 // node[0] <- update_fail_htlcs -- node[1]
1144 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1145 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1146 check_added_monitors!(nodes[0], 0);
1147 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1149 let mut events = nodes[0].node.get_and_clear_pending_events();
1150 assert_eq!(events.len(), 1);
1151 match events.drain(..).next().unwrap() {
1152 crate::util::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1153 assert_eq!(payment_id, ev_pid);
1154 assert_eq!(payment_hash, ev_ph);
1161 fn failed_probe_yields_event() {
1162 let chanmon_cfgs = create_chanmon_cfgs(3);
1163 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1164 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1165 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1167 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1168 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1170 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id());
1172 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
1174 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1176 // node[0] -- update_add_htlcs -> node[1]
1177 check_added_monitors!(nodes[0], 1);
1178 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1179 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1180 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1181 check_added_monitors!(nodes[1], 0);
1182 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1183 expect_pending_htlcs_forwardable!(nodes[1]);
1185 // node[0] <- update_fail_htlcs -- node[1]
1186 check_added_monitors!(nodes[1], 1);
1187 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1188 // Skip the PendingHTLCsForwardable event
1189 let _events = nodes[1].node.get_and_clear_pending_events();
1190 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1191 check_added_monitors!(nodes[0], 0);
1192 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1194 let mut events = nodes[0].node.get_and_clear_pending_events();
1195 assert_eq!(events.len(), 1);
1196 match events.drain(..).next().unwrap() {
1197 crate::util::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1198 assert_eq!(payment_id, ev_pid);
1199 assert_eq!(payment_hash, ev_ph);
1206 fn onchain_failed_probe_yields_event() {
1207 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1209 let chanmon_cfgs = create_chanmon_cfgs(3);
1210 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1211 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1212 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1214 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1215 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1217 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id());
1219 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1220 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1221 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1223 // node[0] -- update_add_htlcs -> node[1]
1224 check_added_monitors!(nodes[0], 1);
1225 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1226 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1227 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1228 check_added_monitors!(nodes[1], 0);
1229 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1230 expect_pending_htlcs_forwardable!(nodes[1]);
1232 check_added_monitors!(nodes[1], 1);
1233 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1235 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1236 // Node A, which after 6 confirmations should result in a probe failure event.
1237 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1238 confirm_transaction(&nodes[0], &bs_txn[0]);
1239 check_closed_broadcast!(&nodes[0], true);
1240 check_added_monitors!(nodes[0], 1);
1242 let mut events = nodes[0].node.get_and_clear_pending_events();
1243 assert_eq!(events.len(), 2);
1244 let mut found_probe_failed = false;
1245 for event in events.drain(..) {
1247 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1248 assert_eq!(payment_id, ev_pid);
1249 assert_eq!(payment_hash, ev_ph);
1250 found_probe_failed = true;
1252 Event::ChannelClosed { .. } => {},
1256 assert!(found_probe_failed);
1260 fn claimed_send_payment_idempotent() {
1261 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1262 let chanmon_cfgs = create_chanmon_cfgs(2);
1263 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1264 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1265 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1267 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1269 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1270 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1272 macro_rules! check_send_rejected {
1274 // If we try to resend a new payment with a different payment_hash but with the same
1275 // payment_id, it should be rejected.
1276 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1278 Err(PaymentSendFailure::ParameterError(APIError::RouteError { err: "Payment already in progress" })) => {},
1279 _ => panic!("Unexpected send result: {:?}", send_result),
1282 // Further, if we try to send a spontaneous payment with the same payment_id it should
1283 // also be rejected.
1284 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1286 Err(PaymentSendFailure::ParameterError(APIError::RouteError { err: "Payment already in progress" })) => {},
1287 _ => panic!("Unexpected send result: {:?}", send_result),
1292 check_send_rejected!();
1294 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1295 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1296 // we must remain just as idempotent as we were before.
1297 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1299 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1300 nodes[0].node.timer_tick_occurred();
1303 check_send_rejected!();
1305 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1306 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1307 // the payment complete. However, they could have called `send_payment` while the event was
1308 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1309 // after the event is handled a duplicate payment should sitll be rejected.
1310 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1311 check_send_rejected!();
1313 // If relatively little time has passed, a duplicate payment should still fail.
1314 nodes[0].node.timer_tick_occurred();
1315 check_send_rejected!();
1317 // However, after some time has passed (at least more than the one timer tick above), a
1318 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1319 // references to the old payment data.
1320 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1321 nodes[0].node.timer_tick_occurred();
1324 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1325 check_added_monitors!(nodes[0], 1);
1326 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1327 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);