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, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::chain::transaction::OutPoint;
17 use crate::chain::keysinterface::KeysInterface;
18 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
19 use crate::ln::channelmanager::{self, BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS};
21 use crate::ln::msgs::ChannelMessageHandler;
22 use crate::routing::router::{PaymentParameters, get_route};
23 use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
24 use crate::util::test_utils;
25 use crate::util::errors::APIError;
26 use crate::util::ser::Writeable;
28 use bitcoin::{Block, BlockHeader, TxMerkleNode};
29 use bitcoin::hashes::Hash;
30 use bitcoin::network::constants::Network;
32 use crate::prelude::*;
34 use crate::ln::functional_test_utils::*;
35 use crate::routing::gossip::NodeId;
38 fn retry_single_path_payment() {
39 let chanmon_cfgs = create_chanmon_cfgs(3);
40 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
41 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
42 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
44 let _chan_0 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
45 let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
46 // Rebalance to find a route
47 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
49 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
51 // Rebalance so that the first hop fails.
52 send_payment(&nodes[1], &vec!(&nodes[2])[..], 2_000_000);
54 // Make sure the payment fails on the first hop.
55 let payment_id = PaymentId(payment_hash.0);
56 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), payment_id).unwrap();
57 check_added_monitors!(nodes[0], 1);
58 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
59 assert_eq!(events.len(), 1);
60 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
61 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
62 check_added_monitors!(nodes[1], 0);
63 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
64 expect_pending_htlcs_forwardable!(nodes[1]);
65 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 }]);
66 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
67 assert!(htlc_updates.update_add_htlcs.is_empty());
68 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
69 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
70 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
71 check_added_monitors!(nodes[1], 1);
72 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
73 commitment_signed_dance!(nodes[0], nodes[1], htlc_updates.commitment_signed, false);
74 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
76 // Rebalance the channel so the retry succeeds.
77 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
79 // Mine two blocks (we expire retries after 3, so this will check that we don't expire early)
80 connect_blocks(&nodes[0], 2);
82 // Retry the payment and make sure it succeeds.
83 nodes[0].node.retry_payment(&route, payment_id).unwrap();
84 check_added_monitors!(nodes[0], 1);
85 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
86 assert_eq!(events.len(), 1);
87 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 100_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
88 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
93 let chanmon_cfgs = create_chanmon_cfgs(4);
94 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
95 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
96 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
98 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;
99 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;
100 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;
101 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;
103 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
104 let path = route.paths[0].clone();
105 route.paths.push(path);
106 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
107 route.paths[0][0].short_channel_id = chan_1_id;
108 route.paths[0][1].short_channel_id = chan_3_id;
109 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
110 route.paths[1][0].short_channel_id = chan_2_id;
111 route.paths[1][1].short_channel_id = chan_4_id;
112 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
113 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
118 let chanmon_cfgs = create_chanmon_cfgs(4);
119 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
120 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
121 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
123 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
124 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
125 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
126 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
128 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
130 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 1_000_000);
131 let path = route.paths[0].clone();
132 route.paths.push(path);
133 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
134 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
135 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
136 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
137 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
138 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
140 // Initiate the MPP payment.
141 let payment_id = PaymentId(payment_hash.0);
142 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), payment_id).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);
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);
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())
162 _ => panic!("Unexpected event"),
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);
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());
180 // Rebalance the channel so the second half of the payment can succeed.
181 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
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"); }
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"); }
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);
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);
210 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
211 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
212 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
213 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3, channelmanager::provided_init_features(), channelmanager::provided_init_features());
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;
225 // Initiate the MPP payment.
226 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).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);
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);
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();
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);
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);
256 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
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);
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();
266 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
271 fn mpp_receive_timeout() {
272 do_mpp_receive_timeout(true);
273 do_mpp_receive_timeout(false);
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);
283 let _chan_0 = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
284 let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
285 // Rebalance to find a route
286 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
288 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
290 // Rebalance so that the first hop fails.
291 send_payment(&nodes[1], &vec!(&nodes[2])[..], 2_000_000);
293 // Make sure the payment fails on the first hop.
294 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).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);
314 // Mine blocks so the payment will have expired.
315 connect_blocks(&nodes[0], 3);
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, PaymentId(payment_hash.0)) {
319 assert!(err.contains("not found"));
321 panic!("Unexpected error");
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);
338 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
340 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
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);
345 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)),
346 true, APIError::ChannelUnavailable { ref err },
347 assert_eq!(err, "Peer for first hop currently disconnected/pending monitor update!"));
349 assert!(!nodes[0].node.has_pending_payments());
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
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.
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<&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);
372 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
373 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
375 // Serialize the ChannelManager prior to sending payments
376 let nodes_0_serialized = nodes[0].node.encode();
378 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
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 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
383 check_added_monitors!(nodes[0], 1);
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());
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);
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());
401 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
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();
409 // The ChannelMonitor should always be the latest version, as we're required to persist it
410 // during the `commitment_signed_dance!()`.
411 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
412 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
414 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
415 // force-close the channel.
416 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
417 assert!(nodes[0].node.list_channels().is_empty());
418 assert!(nodes[0].node.has_pending_payments());
419 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
420 assert_eq!(as_broadcasted_txn.len(), 1);
421 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
423 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
424 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
425 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
427 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
428 // error, as the channel has hit the chain.
429 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
430 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
431 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
432 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
433 assert_eq!(as_err.len(), 1);
435 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
436 assert_eq!(node_id, nodes[1].node.get_our_node_id());
437 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
438 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_string() });
439 check_added_monitors!(nodes[1], 1);
440 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
442 _ => panic!("Unexpected event"),
444 check_closed_broadcast!(nodes[1], false);
446 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
447 // we close in a moment.
448 nodes[2].node.claim_funds(payment_preimage_1);
449 check_added_monitors!(nodes[2], 1);
450 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
452 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
453 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
454 check_added_monitors!(nodes[1], 1);
455 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
456 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
458 if confirm_before_reload {
459 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
460 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
463 // Create a new channel on which to retry the payment before we fail the payment via the
464 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
465 // connecting several blocks while creating the channel (implying time has passed).
466 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
467 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
469 mine_transaction(&nodes[1], &as_commitment_tx);
470 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
471 assert_eq!(bs_htlc_claim_txn.len(), 1);
472 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
474 if !confirm_before_reload {
475 mine_transaction(&nodes[0], &as_commitment_tx);
477 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
478 expect_payment_sent!(nodes[0], payment_preimage_1);
479 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
480 let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
481 assert_eq!(as_htlc_timeout_txn.len(), 2);
482 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1]);
483 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
484 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
485 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
486 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
488 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
490 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
491 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
493 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
494 // reloaded) via a route over the new channel, which work without issue and eventually be
495 // received and claimed at the recipient just like any other payment.
496 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
498 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
499 // and not the original fee. We also update node[1]'s relevant config as
500 // do_claim_payment_along_route expects us to never overpay.
502 let mut channel_state = nodes[1].node.channel_state.lock().unwrap();
503 let mut channel = channel_state.by_id.get_mut(&chan_id_2).unwrap();
504 let mut new_config = channel.config();
505 new_config.forwarding_fee_base_msat += 100_000;
506 channel.update_config(&new_config);
507 new_route.paths[0][0].fee_msat += 100_000;
510 // Force expiration of the channel's previous config.
511 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
512 nodes[1].node.timer_tick_occurred();
515 assert!(nodes[0].node.retry_payment(&new_route, payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
516 nodes[0].node.retry_payment(&new_route, PaymentId(payment_hash.0)).unwrap();
517 check_added_monitors!(nodes[0], 1);
518 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
519 assert_eq!(events.len(), 1);
520 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
521 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
522 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
526 fn retry_with_no_persist() {
527 do_retry_with_no_persist(true);
528 do_retry_with_no_persist(false);
531 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
532 // Test that an off-chain completed payment is not retryable on restart. This was previously
533 // broken for dust payments, but we test for both dust and non-dust payments.
535 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
537 let chanmon_cfgs = create_chanmon_cfgs(3);
538 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
540 let mut manually_accept_config = test_default_channel_config();
541 manually_accept_config.manually_accept_inbound_channels = true;
543 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
545 let first_persister: test_utils::TestPersister;
546 let first_new_chain_monitor: test_utils::TestChainMonitor;
547 let first_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
548 let second_persister: test_utils::TestPersister;
549 let second_new_chain_monitor: test_utils::TestChainMonitor;
550 let second_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
551 let third_persister: test_utils::TestPersister;
552 let third_new_chain_monitor: test_utils::TestChainMonitor;
553 let third_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
555 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
557 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
558 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
559 confirm_transaction(&nodes[0], &funding_tx);
560 confirm_transaction(&nodes[1], &funding_tx);
561 // Ignore the announcement_signatures messages
562 nodes[0].node.get_and_clear_pending_msg_events();
563 nodes[1].node.get_and_clear_pending_msg_events();
564 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
566 // Serialize the ChannelManager prior to sending payments
567 let mut nodes_0_serialized = nodes[0].node.encode();
569 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
570 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 });
572 // The ChannelMonitor should always be the latest version, as we're required to persist it
573 // during the `commitment_signed_dance!()`.
574 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
576 reload_node!(nodes[0], test_default_channel_config(), nodes_0_serialized, &[&chan_0_monitor_serialized], first_persister, first_new_chain_monitor, first_nodes_0_deserialized);
577 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
579 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
580 // force-close the channel.
581 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
582 assert!(nodes[0].node.list_channels().is_empty());
583 assert!(nodes[0].node.has_pending_payments());
584 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
586 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
587 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
589 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
590 // error, as the channel has hit the chain.
591 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
592 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
593 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
594 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
595 assert_eq!(as_err.len(), 1);
596 let bs_commitment_tx;
598 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
599 assert_eq!(node_id, nodes[1].node.get_our_node_id());
600 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
601 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_string() });
602 check_added_monitors!(nodes[1], 1);
603 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
605 _ => panic!("Unexpected event"),
607 check_closed_broadcast!(nodes[1], false);
609 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
610 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
611 // incoming HTLCs with the same payment hash later.
612 nodes[2].node.fail_htlc_backwards(&payment_hash);
613 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
614 check_added_monitors!(nodes[2], 1);
616 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
617 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
618 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
619 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
620 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
622 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
623 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
624 // after the commitment transaction, so always connect the commitment transaction.
625 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
626 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
628 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
629 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
630 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
631 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
632 assert_eq!(as_htlc_timeout.len(), 1);
634 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
635 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
636 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
637 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
640 // Create a new channel on which to retry the payment before we fail the payment via the
641 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
642 // connecting several blocks while creating the channel (implying time has passed).
643 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
644 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
645 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
647 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
648 // confirming, we will fail as it's considered still-pending...
649 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
650 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
651 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
653 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
654 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
655 // (which should also still work).
656 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
657 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
658 // We set mpp_parts_remain to avoid having abandon_payment called
659 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
661 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
662 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
663 nodes_0_serialized = nodes[0].node.encode();
665 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
666 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
668 reload_node!(nodes[0], test_default_channel_config(), nodes_0_serialized, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], second_persister, second_new_chain_monitor, second_nodes_0_deserialized);
669 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
671 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
673 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
674 // the payment is not (spuriously) listed as still pending.
675 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
676 check_added_monitors!(nodes[0], 1);
677 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
678 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
680 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
681 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
683 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
684 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
685 nodes_0_serialized = nodes[0].node.encode();
687 // Ensure that after reload we cannot retry the payment.
688 reload_node!(nodes[0], test_default_channel_config(), nodes_0_serialized, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], third_persister, third_new_chain_monitor, third_nodes_0_deserialized);
689 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
691 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
693 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
694 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
698 fn test_completed_payment_not_retryable_on_reload() {
699 do_test_completed_payment_not_retryable_on_reload(true);
700 do_test_completed_payment_not_retryable_on_reload(false);
704 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
705 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
706 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
707 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
708 // the ChannelMonitor tells it to.
710 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
711 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
712 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
713 let chanmon_cfgs = create_chanmon_cfgs(2);
714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
716 let persister: test_utils::TestPersister;
717 let new_chain_monitor: test_utils::TestChainMonitor;
718 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
719 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
721 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
723 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
725 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
726 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
727 check_closed_broadcast!(nodes[0], true);
728 check_added_monitors!(nodes[0], 1);
729 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
731 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
732 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
734 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
735 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
736 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
737 assert_eq!(node_txn.len(), 3);
738 assert_eq!(node_txn[0], node_txn[1]);
739 check_spends!(node_txn[1], funding_tx);
740 check_spends!(node_txn[2], node_txn[1]);
741 let timeout_txn = vec![node_txn[2].clone()];
743 nodes[1].node.claim_funds(payment_preimage);
744 check_added_monitors!(nodes[1], 1);
745 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
747 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
748 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
749 check_closed_broadcast!(nodes[1], true);
750 check_added_monitors!(nodes[1], 1);
751 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
752 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
753 assert_eq!(claim_txn.len(), 3);
754 check_spends!(claim_txn[0], node_txn[1]);
755 check_spends!(claim_txn[1], funding_tx);
756 check_spends!(claim_txn[2], claim_txn[1]);
758 header.prev_blockhash = nodes[0].best_block_hash();
759 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
761 if confirm_commitment_tx {
762 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
765 header.prev_blockhash = nodes[0].best_block_hash();
766 let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
769 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
770 connect_block(&nodes[0], &claim_block);
771 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
774 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
775 // returning InProgress. This should cause the claim event to never make its way to the
777 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
778 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
781 connect_blocks(&nodes[0], 1);
783 connect_block(&nodes[0], &claim_block);
786 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
787 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
788 .get_mut(&funding_txo).unwrap().drain().collect();
789 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
790 // If we're testing connection idempotency we may get substantially more.
791 assert!(mon_updates.len() >= 1);
792 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
793 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
795 // If we persist the ChannelManager here, we should get the PaymentSent event after
797 let mut chan_manager_serialized = Vec::new();
798 if !persist_manager_post_event {
799 chan_manager_serialized = nodes[0].node.encode();
802 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
803 // payment sent event.
804 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
805 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
806 for update in mon_updates {
807 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
810 expect_payment_failed!(nodes[0], payment_hash, false);
812 expect_payment_sent!(nodes[0], payment_preimage);
815 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
817 if persist_manager_post_event {
818 chan_manager_serialized = nodes[0].node.encode();
821 // Now reload nodes[0]...
822 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
824 if persist_manager_post_event {
825 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
826 } else if payment_timeout {
827 expect_payment_failed!(nodes[0], payment_hash, false);
829 expect_payment_sent!(nodes[0], payment_preimage);
832 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
833 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
834 // payment events should kick in, leaving us with no pending events here.
835 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
836 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
837 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
841 fn test_dup_htlc_onchain_fails_on_reload() {
842 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
843 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
844 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
845 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
846 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
847 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
851 fn test_fulfill_restart_failure() {
852 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
853 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
854 // again, or fail it, giving us free money.
856 // Of course probably they won't fail it and give us free money, but because we have code to
857 // handle it, we should test the logic for it anyway. We do that here.
858 let chanmon_cfgs = create_chanmon_cfgs(2);
859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
861 let persister: test_utils::TestPersister;
862 let new_chain_monitor: test_utils::TestChainMonitor;
863 let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
864 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
866 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
867 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
869 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
870 // pre-fulfill, which we do by serializing it here.
871 let chan_manager_serialized = nodes[1].node.encode();
872 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
874 nodes[1].node.claim_funds(payment_preimage);
875 check_added_monitors!(nodes[1], 1);
876 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
878 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
879 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
880 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
882 // Now reload nodes[1]...
883 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
885 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
886 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
888 nodes[1].node.fail_htlc_backwards(&payment_hash);
889 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
890 check_added_monitors!(nodes[1], 1);
891 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
892 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
893 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
894 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
895 // it had already considered the payment fulfilled, and now they just got free money.
896 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
900 fn get_ldk_payment_preimage() {
901 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
902 let chanmon_cfgs = create_chanmon_cfgs(2);
903 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
904 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
905 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
906 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
908 let amt_msat = 60_000;
909 let expiry_secs = 60 * 60;
910 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs).unwrap();
912 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
913 .with_features(channelmanager::provided_invoice_features());
914 let scorer = test_utils::TestScorer::with_penalty(0);
915 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
916 let random_seed_bytes = keys_manager.get_secure_random_bytes();
917 let route = get_route(
918 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
919 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
920 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
921 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
922 check_added_monitors!(nodes[0], 1);
924 // Make sure to use `get_payment_preimage`
925 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
926 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
927 assert_eq!(events.len(), 1);
928 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
929 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
933 fn sent_probe_is_probe_of_sending_node() {
934 let chanmon_cfgs = create_chanmon_cfgs(3);
935 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
936 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
937 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
939 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
940 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
942 // First check we refuse to build a single-hop probe
943 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
944 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
946 // Then build an actual two-hop probing path
947 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
949 match nodes[0].node.send_probe(route.paths[0].clone()) {
950 Ok((payment_hash, payment_id)) => {
951 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
952 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
953 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
958 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
959 check_added_monitors!(nodes[0], 1);
963 fn successful_probe_yields_event() {
964 let chanmon_cfgs = create_chanmon_cfgs(3);
965 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
966 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
967 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
969 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
970 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
972 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
974 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
976 // node[0] -- update_add_htlcs -> node[1]
977 check_added_monitors!(nodes[0], 1);
978 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
979 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
980 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
981 check_added_monitors!(nodes[1], 0);
982 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
983 expect_pending_htlcs_forwardable!(nodes[1]);
985 // node[1] -- update_add_htlcs -> node[2]
986 check_added_monitors!(nodes[1], 1);
987 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
988 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
989 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
990 check_added_monitors!(nodes[2], 0);
991 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
993 // node[1] <- update_fail_htlcs -- node[2]
994 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
995 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
996 check_added_monitors!(nodes[1], 0);
997 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
999 // node[0] <- update_fail_htlcs -- node[1]
1000 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1001 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1002 check_added_monitors!(nodes[0], 0);
1003 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1005 let mut events = nodes[0].node.get_and_clear_pending_events();
1006 assert_eq!(events.len(), 1);
1007 match events.drain(..).next().unwrap() {
1008 crate::util::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1009 assert_eq!(payment_id, ev_pid);
1010 assert_eq!(payment_hash, ev_ph);
1017 fn failed_probe_yields_event() {
1018 let chanmon_cfgs = create_chanmon_cfgs(3);
1019 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1020 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1021 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1023 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1024 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1026 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id());
1028 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
1030 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1032 // node[0] -- update_add_htlcs -> node[1]
1033 check_added_monitors!(nodes[0], 1);
1034 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1035 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1036 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1037 check_added_monitors!(nodes[1], 0);
1038 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1039 expect_pending_htlcs_forwardable!(nodes[1]);
1041 // node[0] <- update_fail_htlcs -- node[1]
1042 check_added_monitors!(nodes[1], 1);
1043 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1044 // Skip the PendingHTLCsForwardable event
1045 let _events = nodes[1].node.get_and_clear_pending_events();
1046 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1047 check_added_monitors!(nodes[0], 0);
1048 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1050 let mut events = nodes[0].node.get_and_clear_pending_events();
1051 assert_eq!(events.len(), 1);
1052 match events.drain(..).next().unwrap() {
1053 crate::util::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1054 assert_eq!(payment_id, ev_pid);
1055 assert_eq!(payment_hash, ev_ph);
1062 fn onchain_failed_probe_yields_event() {
1063 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1065 let chanmon_cfgs = create_chanmon_cfgs(3);
1066 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1067 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1068 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1070 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1071 create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1073 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id());
1075 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1076 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1077 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1079 // node[0] -- update_add_htlcs -> node[1]
1080 check_added_monitors!(nodes[0], 1);
1081 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1082 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1083 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1084 check_added_monitors!(nodes[1], 0);
1085 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1086 expect_pending_htlcs_forwardable!(nodes[1]);
1088 check_added_monitors!(nodes[1], 1);
1089 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1091 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1092 // Node A, which after 6 confirmations should result in a probe failure event.
1093 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1094 confirm_transaction(&nodes[0], &bs_txn[0]);
1095 check_closed_broadcast!(&nodes[0], true);
1096 check_added_monitors!(nodes[0], 1);
1098 let mut events = nodes[0].node.get_and_clear_pending_events();
1099 assert_eq!(events.len(), 2);
1100 let mut found_probe_failed = false;
1101 for event in events.drain(..) {
1103 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1104 assert_eq!(payment_id, ev_pid);
1105 assert_eq!(payment_hash, ev_ph);
1106 found_probe_failed = true;
1108 Event::ChannelClosed { .. } => {},
1112 assert!(found_probe_failed);
1116 fn claimed_send_payment_idempotent() {
1117 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1118 let chanmon_cfgs = create_chanmon_cfgs(2);
1119 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1120 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1121 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1123 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1125 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1126 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1128 macro_rules! check_send_rejected {
1130 // If we try to resend a new payment with a different payment_hash but with the same
1131 // payment_id, it should be rejected.
1132 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1134 Err(PaymentSendFailure::DuplicatePayment) => {},
1135 _ => panic!("Unexpected send result: {:?}", send_result),
1138 // Further, if we try to send a spontaneous payment with the same payment_id it should
1139 // also be rejected.
1140 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1142 Err(PaymentSendFailure::DuplicatePayment) => {},
1143 _ => panic!("Unexpected send result: {:?}", send_result),
1148 check_send_rejected!();
1150 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1151 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1152 // we must remain just as idempotent as we were before.
1153 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1155 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1156 nodes[0].node.timer_tick_occurred();
1159 check_send_rejected!();
1161 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1162 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1163 // the payment complete. However, they could have called `send_payment` while the event was
1164 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1165 // after the event is handled a duplicate payment should sitll be rejected.
1166 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1167 check_send_rejected!();
1169 // If relatively little time has passed, a duplicate payment should still fail.
1170 nodes[0].node.timer_tick_occurred();
1171 check_send_rejected!();
1173 // However, after some time has passed (at least more than the one timer tick above), a
1174 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1175 // references to the old payment data.
1176 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1177 nodes[0].node.timer_tick_occurred();
1180 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1181 check_added_monitors!(nodes[0], 1);
1182 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1183 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1187 fn abandoned_send_payment_idempotent() {
1188 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1190 let chanmon_cfgs = create_chanmon_cfgs(2);
1191 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1192 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1193 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1195 create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1197 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1198 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1200 macro_rules! check_send_rejected {
1202 // If we try to resend a new payment with a different payment_hash but with the same
1203 // payment_id, it should be rejected.
1204 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1206 Err(PaymentSendFailure::DuplicatePayment) => {},
1207 _ => panic!("Unexpected send result: {:?}", send_result),
1210 // Further, if we try to send a spontaneous payment with the same payment_id it should
1211 // also be rejected.
1212 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1214 Err(PaymentSendFailure::DuplicatePayment) => {},
1215 _ => panic!("Unexpected send result: {:?}", send_result),
1220 check_send_rejected!();
1222 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1223 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1225 pass_failed_payment_back_no_abandon(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash);
1226 check_send_rejected!();
1228 // Until we abandon the payment, no matter how many timer ticks pass, we still cannot reuse the
1230 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1231 nodes[0].node.timer_tick_occurred();
1233 check_send_rejected!();
1235 nodes[0].node.abandon_payment(payment_id);
1236 get_event!(nodes[0], Event::PaymentFailed);
1238 // However, we can reuse the PaymentId immediately after we `abandon_payment`.
1239 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1240 check_added_monitors!(nodes[0], 1);
1241 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1242 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1246 fn test_trivial_inflight_htlc_tracking(){
1247 // In this test, we test three scenarios:
1248 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1249 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1250 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1251 let chanmon_cfgs = create_chanmon_cfgs(3);
1252 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1253 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1254 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1256 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1257 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1259 // Send and claim the payment. Inflight HTLCs should be empty.
1260 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 500000);
1262 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1264 let node_0_channel_lock = nodes[0].node.channel_state.lock().unwrap();
1265 let node_1_channel_lock = nodes[1].node.channel_state.lock().unwrap();
1266 let channel_1 = node_0_channel_lock.by_id.get(&chan_1_id).unwrap();
1267 let channel_2 = node_1_channel_lock.by_id.get(&chan_2_id).unwrap();
1269 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1270 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1271 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1272 channel_1.get_short_channel_id().unwrap()
1274 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1275 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1276 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1277 channel_2.get_short_channel_id().unwrap()
1280 assert_eq!(chan_1_used_liquidity, None);
1281 assert_eq!(chan_2_used_liquidity, None);
1284 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1285 let (payment_preimage, _, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 500000);
1287 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1289 let node_0_channel_lock = nodes[0].node.channel_state.lock().unwrap();
1290 let node_1_channel_lock = nodes[1].node.channel_state.lock().unwrap();
1291 let channel_1 = node_0_channel_lock.by_id.get(&chan_1_id).unwrap();
1292 let channel_2 = node_1_channel_lock.by_id.get(&chan_2_id).unwrap();
1294 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1295 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1296 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1297 channel_1.get_short_channel_id().unwrap()
1299 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1300 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1301 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1302 channel_2.get_short_channel_id().unwrap()
1305 // First hop accounts for expected 1000 msat fee
1306 assert_eq!(chan_1_used_liquidity, Some(501000));
1307 assert_eq!(chan_2_used_liquidity, Some(500000));
1310 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1311 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1313 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1315 let node_0_channel_lock = nodes[0].node.channel_state.lock().unwrap();
1316 let node_1_channel_lock = nodes[1].node.channel_state.lock().unwrap();
1317 let channel_1 = node_0_channel_lock.by_id.get(&chan_1_id).unwrap();
1318 let channel_2 = node_1_channel_lock.by_id.get(&chan_2_id).unwrap();
1320 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1321 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1322 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1323 channel_1.get_short_channel_id().unwrap()
1325 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1326 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1327 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1328 channel_2.get_short_channel_id().unwrap()
1331 assert_eq!(chan_1_used_liquidity, None);
1332 assert_eq!(chan_2_used_liquidity, None);
1337 fn test_holding_cell_inflight_htlcs() {
1338 let chanmon_cfgs = create_chanmon_cfgs(2);
1339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1341 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1342 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, channelmanager::provided_init_features(), channelmanager::provided_init_features()).2;
1344 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1345 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1347 // Queue up two payments - one will be delivered right away, one immediately goes into the
1348 // holding cell as nodes[0] is AwaitingRAA.
1350 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1351 check_added_monitors!(nodes[0], 1);
1352 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1353 check_added_monitors!(nodes[0], 0);
1356 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1359 let channel_lock = nodes[0].node.channel_state.lock().unwrap();
1360 let channel = channel_lock.by_id.get(&channel_id).unwrap();
1362 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1363 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1364 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1365 channel.get_short_channel_id().unwrap()
1368 assert_eq!(used_liquidity, Some(2000000));
1371 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1372 nodes[0].node.get_and_clear_pending_msg_events();