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::keysinterface::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
19 use crate::ln::channelmanager::{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::gossip::RoutingFees;
23 use crate::routing::router::{get_route, PaymentParameters, RouteHint, RouteHintHop, RouteParameters};
24 use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
25 use crate::util::test_utils;
26 use crate::util::errors::APIError;
27 use crate::util::ser::Writeable;
29 use bitcoin::{Block, BlockHeader, TxMerkleNode};
30 use bitcoin::hashes::Hash;
31 use bitcoin::network::constants::Network;
33 use crate::prelude::*;
35 use crate::ln::functional_test_utils::*;
36 use crate::routing::gossip::NodeId;
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);
46 let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1);
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).0.contents.short_channel_id;
100 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
101 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
102 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).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);
125 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
126 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
127 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
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, mut events) = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &events);
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_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &events);
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);
212 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
213 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
214 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
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 let (node_1_msgs, mut events) = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &events);
234 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
236 if send_partial_mpp {
237 // Time out the partial MPP
238 for _ in 0..MPP_TIMEOUT_TICKS {
239 nodes[3].node.timer_tick_occurred();
242 // Failed HTLC from node 3 -> 1
243 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
244 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
245 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
246 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
247 check_added_monitors!(nodes[3], 1);
248 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
250 // Failed HTLC from node 1 -> 0
251 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 }]);
252 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
253 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
254 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
255 check_added_monitors!(nodes[1], 1);
256 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
258 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
260 // Pass half of the payment along the second path.
261 let (node_2_msgs, _events) = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &events);
262 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
264 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
265 for _ in 0..MPP_TIMEOUT_TICKS {
266 nodes[3].node.timer_tick_occurred();
269 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
274 fn mpp_receive_timeout() {
275 do_mpp_receive_timeout(true);
276 do_mpp_receive_timeout(false);
280 fn retry_expired_payment() {
281 let chanmon_cfgs = create_chanmon_cfgs(3);
282 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
283 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
284 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
286 let _chan_0 = create_announced_chan_between_nodes(&nodes, 0, 1);
287 let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1);
288 // Rebalance to find a route
289 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
291 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
293 // Rebalance so that the first hop fails.
294 send_payment(&nodes[1], &vec!(&nodes[2])[..], 2_000_000);
296 // Make sure the payment fails on the first hop.
297 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
298 check_added_monitors!(nodes[0], 1);
299 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
300 assert_eq!(events.len(), 1);
301 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
302 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
303 check_added_monitors!(nodes[1], 0);
304 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
305 expect_pending_htlcs_forwardable!(nodes[1]);
306 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 }]);
307 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
308 assert!(htlc_updates.update_add_htlcs.is_empty());
309 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
310 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
311 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
312 check_added_monitors!(nodes[1], 1);
313 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
314 commitment_signed_dance!(nodes[0], nodes[1], htlc_updates.commitment_signed, false);
315 expect_payment_failed!(nodes[0], payment_hash, false);
317 // Mine blocks so the payment will have expired.
318 connect_blocks(&nodes[0], 3);
320 // Retry the payment and make sure it errors as expected.
321 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = nodes[0].node.retry_payment(&route, PaymentId(payment_hash.0)) {
322 assert!(err.contains("not found"));
324 panic!("Unexpected error");
329 fn no_pending_leak_on_initial_send_failure() {
330 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
331 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
332 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
333 // pending payment forever and never time it out.
334 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
335 // try, and then check that no pending payment is being tracked.
336 let chanmon_cfgs = create_chanmon_cfgs(2);
337 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
338 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
339 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
341 create_announced_chan_between_nodes(&nodes, 0, 1);
343 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
345 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
346 nodes[1].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
348 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)),
349 true, APIError::ChannelUnavailable { ref err },
350 assert_eq!(err, "Peer for first hop currently disconnected/pending monitor update!"));
352 assert!(!nodes[0].node.has_pending_payments());
355 fn do_retry_with_no_persist(confirm_before_reload: bool) {
356 // If we send a pending payment and `send_payment` returns success, we should always either
357 // return a payment failure event or a payment success event, and on failure the payment should
360 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
361 // always persisted asynchronously), the ChannelManager has to reload some payment data from
362 // ChannelMonitor(s) in some cases. This tests that reloading.
364 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
365 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
366 // which has separate codepaths for "commitment transaction already confirmed" and not.
367 let chanmon_cfgs = create_chanmon_cfgs(3);
368 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
369 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
370 let persister: test_utils::TestPersister;
371 let new_chain_monitor: test_utils::TestChainMonitor;
372 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
373 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
375 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
376 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
378 // Serialize the ChannelManager prior to sending payments
379 let nodes_0_serialized = nodes[0].node.encode();
381 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
383 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
384 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
385 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
386 check_added_monitors!(nodes[0], 1);
388 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
389 assert_eq!(events.len(), 1);
390 let payment_event = SendEvent::from_event(events.pop().unwrap());
391 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
393 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
394 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
395 // which would prevent retry.
396 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
397 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
399 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
400 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
401 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
402 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
404 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
406 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
407 if confirm_before_reload {
408 mine_transaction(&nodes[0], &as_commitment_tx);
409 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
412 // The ChannelMonitor should always be the latest version, as we're required to persist it
413 // during the `commitment_signed_dance!()`.
414 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
415 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
417 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
418 // force-close the channel.
419 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
420 assert!(nodes[0].node.list_channels().is_empty());
421 assert!(nodes[0].node.has_pending_payments());
422 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
423 assert_eq!(as_broadcasted_txn.len(), 1);
424 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
426 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
427 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
428 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
430 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
431 // error, as the channel has hit the chain.
432 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
433 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
434 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
435 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
436 assert_eq!(as_err.len(), 1);
438 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
439 assert_eq!(node_id, nodes[1].node.get_our_node_id());
440 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
441 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", &nodes[1].node.get_our_node_id()) });
442 check_added_monitors!(nodes[1], 1);
443 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
445 _ => panic!("Unexpected event"),
447 check_closed_broadcast!(nodes[1], false);
449 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
450 // we close in a moment.
451 nodes[2].node.claim_funds(payment_preimage_1);
452 check_added_monitors!(nodes[2], 1);
453 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
455 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
456 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
457 check_added_monitors!(nodes[1], 1);
458 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
459 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
461 if confirm_before_reload {
462 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
463 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
466 // Create a new channel on which to retry the payment before we fail the payment via the
467 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
468 // connecting several blocks while creating the channel (implying time has passed).
469 create_announced_chan_between_nodes(&nodes, 0, 1);
470 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
472 mine_transaction(&nodes[1], &as_commitment_tx);
473 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
474 assert_eq!(bs_htlc_claim_txn.len(), 1);
475 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
477 if !confirm_before_reload {
478 mine_transaction(&nodes[0], &as_commitment_tx);
480 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
481 expect_payment_sent!(nodes[0], payment_preimage_1);
482 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
483 let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
484 assert_eq!(as_htlc_timeout_txn.len(), 2);
485 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1]);
486 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
487 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
488 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
489 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
491 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
493 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
494 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
496 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
497 // reloaded) via a route over the new channel, which work without issue and eventually be
498 // received and claimed at the recipient just like any other payment.
499 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
501 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
502 // and not the original fee. We also update node[1]'s relevant config as
503 // do_claim_payment_along_route expects us to never overpay.
505 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
506 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
507 .unwrap().lock().unwrap();
508 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
509 let mut new_config = channel.config();
510 new_config.forwarding_fee_base_msat += 100_000;
511 channel.update_config(&new_config);
512 new_route.paths[0][0].fee_msat += 100_000;
515 // Force expiration of the channel's previous config.
516 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
517 nodes[1].node.timer_tick_occurred();
520 assert!(nodes[0].node.retry_payment(&new_route, payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
521 nodes[0].node.retry_payment(&new_route, PaymentId(payment_hash.0)).unwrap();
522 check_added_monitors!(nodes[0], 1);
523 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
524 assert_eq!(events.len(), 1);
525 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
526 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
527 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
531 fn retry_with_no_persist() {
532 do_retry_with_no_persist(true);
533 do_retry_with_no_persist(false);
536 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
537 // Test that an off-chain completed payment is not retryable on restart. This was previously
538 // broken for dust payments, but we test for both dust and non-dust payments.
540 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
542 let chanmon_cfgs = create_chanmon_cfgs(3);
543 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
545 let mut manually_accept_config = test_default_channel_config();
546 manually_accept_config.manually_accept_inbound_channels = true;
548 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
550 let first_persister: test_utils::TestPersister;
551 let first_new_chain_monitor: test_utils::TestChainMonitor;
552 let first_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
553 let second_persister: test_utils::TestPersister;
554 let second_new_chain_monitor: test_utils::TestChainMonitor;
555 let second_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
556 let third_persister: test_utils::TestPersister;
557 let third_new_chain_monitor: test_utils::TestChainMonitor;
558 let third_nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
560 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
562 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
563 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
564 confirm_transaction(&nodes[0], &funding_tx);
565 confirm_transaction(&nodes[1], &funding_tx);
566 // Ignore the announcement_signatures messages
567 nodes[0].node.get_and_clear_pending_msg_events();
568 nodes[1].node.get_and_clear_pending_msg_events();
569 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
571 // Serialize the ChannelManager prior to sending payments
572 let mut nodes_0_serialized = nodes[0].node.encode();
574 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
575 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 });
577 // The ChannelMonitor should always be the latest version, as we're required to persist it
578 // during the `commitment_signed_dance!()`.
579 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
581 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);
582 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
584 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
585 // force-close the channel.
586 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
587 assert!(nodes[0].node.list_channels().is_empty());
588 assert!(nodes[0].node.has_pending_payments());
589 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
591 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }).unwrap();
592 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
594 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
595 // error, as the channel has hit the chain.
596 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }).unwrap();
597 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
598 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
599 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
600 assert_eq!(as_err.len(), 1);
601 let bs_commitment_tx;
603 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
604 assert_eq!(node_id, nodes[1].node.get_our_node_id());
605 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
606 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", &nodes[1].node.get_our_node_id()) });
607 check_added_monitors!(nodes[1], 1);
608 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
610 _ => panic!("Unexpected event"),
612 check_closed_broadcast!(nodes[1], false);
614 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
615 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
616 // incoming HTLCs with the same payment hash later.
617 nodes[2].node.fail_htlc_backwards(&payment_hash);
618 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
619 check_added_monitors!(nodes[2], 1);
621 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
622 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
623 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
624 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
625 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
627 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
628 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
629 // after the commitment transaction, so always connect the commitment transaction.
630 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
631 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
633 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
634 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
635 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
636 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
637 assert_eq!(as_htlc_timeout.len(), 1);
639 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
640 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
641 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
642 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
645 // Create a new channel on which to retry the payment before we fail the payment via the
646 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
647 // connecting several blocks while creating the channel (implying time has passed).
648 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
649 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
650 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
652 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
653 // confirming, we will fail as it's considered still-pending...
654 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
655 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
656 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
658 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
659 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
660 // (which should also still work).
661 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
662 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
663 // We set mpp_parts_remain to avoid having abandon_payment called
664 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
666 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
667 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
668 nodes_0_serialized = nodes[0].node.encode();
670 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
671 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
673 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);
674 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
676 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
678 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
679 // the payment is not (spuriously) listed as still pending.
680 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
681 check_added_monitors!(nodes[0], 1);
682 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
683 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
685 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
686 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
688 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
689 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
690 nodes_0_serialized = nodes[0].node.encode();
692 // Ensure that after reload we cannot retry the payment.
693 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);
694 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
696 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
698 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
699 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
703 fn test_completed_payment_not_retryable_on_reload() {
704 do_test_completed_payment_not_retryable_on_reload(true);
705 do_test_completed_payment_not_retryable_on_reload(false);
709 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
710 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
711 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
712 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
713 // the ChannelMonitor tells it to.
715 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
716 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
717 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
718 let chanmon_cfgs = create_chanmon_cfgs(2);
719 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
720 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
721 let persister: test_utils::TestPersister;
722 let new_chain_monitor: test_utils::TestChainMonitor;
723 let nodes_0_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
724 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
726 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
728 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
730 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
731 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
732 check_closed_broadcast!(nodes[0], true);
733 check_added_monitors!(nodes[0], 1);
734 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
736 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
737 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
739 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
740 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
741 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
742 assert_eq!(node_txn.len(), 3);
743 assert_eq!(node_txn[0], node_txn[1]);
744 check_spends!(node_txn[1], funding_tx);
745 check_spends!(node_txn[2], node_txn[1]);
746 let timeout_txn = vec![node_txn[2].clone()];
748 nodes[1].node.claim_funds(payment_preimage);
749 check_added_monitors!(nodes[1], 1);
750 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
752 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
753 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
754 check_closed_broadcast!(nodes[1], true);
755 check_added_monitors!(nodes[1], 1);
756 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
757 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
758 assert_eq!(claim_txn.len(), 1);
759 check_spends!(claim_txn[0], node_txn[1]);
761 header.prev_blockhash = nodes[0].best_block_hash();
762 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
764 if confirm_commitment_tx {
765 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
768 header.prev_blockhash = nodes[0].best_block_hash();
769 let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
772 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
773 connect_block(&nodes[0], &claim_block);
774 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
777 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
778 // returning InProgress. This should cause the claim event to never make its way to the
780 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
781 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
784 connect_blocks(&nodes[0], 1);
786 connect_block(&nodes[0], &claim_block);
789 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
790 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
791 .get_mut(&funding_txo).unwrap().drain().collect();
792 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
793 // If we're testing connection idempotency we may get substantially more.
794 assert!(mon_updates.len() >= 1);
795 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
796 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
798 // If we persist the ChannelManager here, we should get the PaymentSent event after
800 let mut chan_manager_serialized = Vec::new();
801 if !persist_manager_post_event {
802 chan_manager_serialized = nodes[0].node.encode();
805 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
806 // payment sent event.
807 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
808 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
809 for update in mon_updates {
810 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
813 expect_payment_failed!(nodes[0], payment_hash, false);
815 expect_payment_sent!(nodes[0], payment_preimage);
818 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
820 if persist_manager_post_event {
821 chan_manager_serialized = nodes[0].node.encode();
824 // Now reload nodes[0]...
825 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
827 if persist_manager_post_event {
828 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
829 } else if payment_timeout {
830 expect_payment_failed!(nodes[0], payment_hash, false);
832 expect_payment_sent!(nodes[0], payment_preimage);
835 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
836 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
837 // payment events should kick in, leaving us with no pending events here.
838 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
839 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
840 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
844 fn test_dup_htlc_onchain_fails_on_reload() {
845 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
846 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
847 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
848 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
849 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
850 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
854 fn test_fulfill_restart_failure() {
855 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
856 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
857 // again, or fail it, giving us free money.
859 // Of course probably they won't fail it and give us free money, but because we have code to
860 // handle it, we should test the logic for it anyway. We do that here.
861 let chanmon_cfgs = create_chanmon_cfgs(2);
862 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
863 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
864 let persister: test_utils::TestPersister;
865 let new_chain_monitor: test_utils::TestChainMonitor;
866 let nodes_1_deserialized: ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>;
867 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
869 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
870 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
872 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
873 // pre-fulfill, which we do by serializing it here.
874 let chan_manager_serialized = nodes[1].node.encode();
875 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
877 nodes[1].node.claim_funds(payment_preimage);
878 check_added_monitors!(nodes[1], 1);
879 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
881 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
882 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
883 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
885 // Now reload nodes[1]...
886 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
888 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
889 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
891 nodes[1].node.fail_htlc_backwards(&payment_hash);
892 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
893 check_added_monitors!(nodes[1], 1);
894 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
895 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
896 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
897 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
898 // it had already considered the payment fulfilled, and now they just got free money.
899 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
903 fn get_ldk_payment_preimage() {
904 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
905 let chanmon_cfgs = create_chanmon_cfgs(2);
906 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
907 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
908 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
909 create_announced_chan_between_nodes(&nodes, 0, 1);
911 let amt_msat = 60_000;
912 let expiry_secs = 60 * 60;
913 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs).unwrap();
915 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
916 .with_features(nodes[1].node.invoice_features());
917 let scorer = test_utils::TestScorer::with_penalty(0);
918 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
919 let random_seed_bytes = keys_manager.get_secure_random_bytes();
920 let route = get_route(
921 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
922 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
923 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
924 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
925 check_added_monitors!(nodes[0], 1);
927 // Make sure to use `get_payment_preimage`
928 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
929 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
930 assert_eq!(events.len(), 1);
931 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
932 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
936 fn sent_probe_is_probe_of_sending_node() {
937 let chanmon_cfgs = create_chanmon_cfgs(3);
938 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
939 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
940 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
942 create_announced_chan_between_nodes(&nodes, 0, 1);
943 create_announced_chan_between_nodes(&nodes, 1, 2);
945 // First check we refuse to build a single-hop probe
946 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
947 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
949 // Then build an actual two-hop probing path
950 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
952 match nodes[0].node.send_probe(route.paths[0].clone()) {
953 Ok((payment_hash, payment_id)) => {
954 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
955 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
956 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
961 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
962 check_added_monitors!(nodes[0], 1);
966 fn successful_probe_yields_event() {
967 let chanmon_cfgs = create_chanmon_cfgs(3);
968 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
969 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
970 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
972 create_announced_chan_between_nodes(&nodes, 0, 1);
973 create_announced_chan_between_nodes(&nodes, 1, 2);
975 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
977 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
979 // node[0] -- update_add_htlcs -> node[1]
980 check_added_monitors!(nodes[0], 1);
981 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
982 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
983 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
984 check_added_monitors!(nodes[1], 0);
985 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
986 expect_pending_htlcs_forwardable!(nodes[1]);
988 // node[1] -- update_add_htlcs -> node[2]
989 check_added_monitors!(nodes[1], 1);
990 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
991 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
992 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
993 check_added_monitors!(nodes[2], 0);
994 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
996 // node[1] <- update_fail_htlcs -- node[2]
997 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
998 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
999 check_added_monitors!(nodes[1], 0);
1000 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1002 // node[0] <- update_fail_htlcs -- node[1]
1003 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1004 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1005 check_added_monitors!(nodes[0], 0);
1006 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1008 let mut events = nodes[0].node.get_and_clear_pending_events();
1009 assert_eq!(events.len(), 1);
1010 match events.drain(..).next().unwrap() {
1011 crate::util::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1012 assert_eq!(payment_id, ev_pid);
1013 assert_eq!(payment_hash, ev_ph);
1020 fn failed_probe_yields_event() {
1021 let chanmon_cfgs = create_chanmon_cfgs(3);
1022 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1023 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1024 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1026 create_announced_chan_between_nodes(&nodes, 0, 1);
1027 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
1029 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id());
1031 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
1033 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1035 // node[0] -- update_add_htlcs -> node[1]
1036 check_added_monitors!(nodes[0], 1);
1037 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1038 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1039 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1040 check_added_monitors!(nodes[1], 0);
1041 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1042 expect_pending_htlcs_forwardable!(nodes[1]);
1044 // node[0] <- update_fail_htlcs -- node[1]
1045 check_added_monitors!(nodes[1], 1);
1046 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1047 // Skip the PendingHTLCsForwardable event
1048 let _events = nodes[1].node.get_and_clear_pending_events();
1049 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1050 check_added_monitors!(nodes[0], 0);
1051 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1053 let mut events = nodes[0].node.get_and_clear_pending_events();
1054 assert_eq!(events.len(), 1);
1055 match events.drain(..).next().unwrap() {
1056 crate::util::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1057 assert_eq!(payment_id, ev_pid);
1058 assert_eq!(payment_hash, ev_ph);
1065 fn onchain_failed_probe_yields_event() {
1066 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1068 let chanmon_cfgs = create_chanmon_cfgs(3);
1069 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1070 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1071 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1073 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1074 create_announced_chan_between_nodes(&nodes, 1, 2);
1076 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id());
1078 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1079 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1080 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1082 // node[0] -- update_add_htlcs -> node[1]
1083 check_added_monitors!(nodes[0], 1);
1084 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1085 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1086 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1087 check_added_monitors!(nodes[1], 0);
1088 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1089 expect_pending_htlcs_forwardable!(nodes[1]);
1091 check_added_monitors!(nodes[1], 1);
1092 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1094 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1095 // Node A, which after 6 confirmations should result in a probe failure event.
1096 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1097 confirm_transaction(&nodes[0], &bs_txn[0]);
1098 check_closed_broadcast!(&nodes[0], true);
1099 check_added_monitors!(nodes[0], 1);
1101 let mut events = nodes[0].node.get_and_clear_pending_events();
1102 assert_eq!(events.len(), 2);
1103 let mut found_probe_failed = false;
1104 for event in events.drain(..) {
1106 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1107 assert_eq!(payment_id, ev_pid);
1108 assert_eq!(payment_hash, ev_ph);
1109 found_probe_failed = true;
1111 Event::ChannelClosed { .. } => {},
1115 assert!(found_probe_failed);
1119 fn claimed_send_payment_idempotent() {
1120 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1121 let chanmon_cfgs = create_chanmon_cfgs(2);
1122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1124 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1126 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1128 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1129 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1131 macro_rules! check_send_rejected {
1133 // If we try to resend a new payment with a different payment_hash but with the same
1134 // payment_id, it should be rejected.
1135 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1137 Err(PaymentSendFailure::DuplicatePayment) => {},
1138 _ => panic!("Unexpected send result: {:?}", send_result),
1141 // Further, if we try to send a spontaneous payment with the same payment_id it should
1142 // also be rejected.
1143 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1145 Err(PaymentSendFailure::DuplicatePayment) => {},
1146 _ => panic!("Unexpected send result: {:?}", send_result),
1151 check_send_rejected!();
1153 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1154 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1155 // we must remain just as idempotent as we were before.
1156 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1158 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1159 nodes[0].node.timer_tick_occurred();
1162 check_send_rejected!();
1164 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1165 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1166 // the payment complete. However, they could have called `send_payment` while the event was
1167 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1168 // after the event is handled a duplicate payment should sitll be rejected.
1169 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1170 check_send_rejected!();
1172 // If relatively little time has passed, a duplicate payment should still fail.
1173 nodes[0].node.timer_tick_occurred();
1174 check_send_rejected!();
1176 // However, after some time has passed (at least more than the one timer tick above), a
1177 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1178 // references to the old payment data.
1179 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1180 nodes[0].node.timer_tick_occurred();
1183 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1184 check_added_monitors!(nodes[0], 1);
1185 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1186 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1190 fn abandoned_send_payment_idempotent() {
1191 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1193 let chanmon_cfgs = create_chanmon_cfgs(2);
1194 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1195 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1196 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1198 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1200 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1201 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1203 macro_rules! check_send_rejected {
1205 // If we try to resend a new payment with a different payment_hash but with the same
1206 // payment_id, it should be rejected.
1207 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1209 Err(PaymentSendFailure::DuplicatePayment) => {},
1210 _ => panic!("Unexpected send result: {:?}", send_result),
1213 // Further, if we try to send a spontaneous payment with the same payment_id it should
1214 // also be rejected.
1215 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1217 Err(PaymentSendFailure::DuplicatePayment) => {},
1218 _ => panic!("Unexpected send result: {:?}", send_result),
1223 check_send_rejected!();
1225 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1226 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1228 pass_failed_payment_back_no_abandon(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash);
1229 check_send_rejected!();
1231 // Until we abandon the payment, no matter how many timer ticks pass, we still cannot reuse the
1233 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1234 nodes[0].node.timer_tick_occurred();
1236 check_send_rejected!();
1238 nodes[0].node.abandon_payment(payment_id);
1239 get_event!(nodes[0], Event::PaymentFailed);
1241 // However, we can reuse the PaymentId immediately after we `abandon_payment`.
1242 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1243 check_added_monitors!(nodes[0], 1);
1244 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1245 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1248 #[derive(PartialEq)]
1249 enum InterceptTest {
1256 fn test_trivial_inflight_htlc_tracking(){
1257 // In this test, we test three scenarios:
1258 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1259 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1260 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1261 let chanmon_cfgs = create_chanmon_cfgs(3);
1262 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1263 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1264 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1266 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1267 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1269 // Send and claim the payment. Inflight HTLCs should be empty.
1270 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 500000);
1272 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1274 let mut node_0_per_peer_lock;
1275 let mut node_0_peer_state_lock;
1276 let mut node_1_per_peer_lock;
1277 let mut node_1_peer_state_lock;
1278 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1279 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1281 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1282 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1283 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1284 channel_1.get_short_channel_id().unwrap()
1286 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1287 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1288 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1289 channel_2.get_short_channel_id().unwrap()
1292 assert_eq!(chan_1_used_liquidity, None);
1293 assert_eq!(chan_2_used_liquidity, None);
1296 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1297 let (payment_preimage, _, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 500000);
1299 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1301 let mut node_0_per_peer_lock;
1302 let mut node_0_peer_state_lock;
1303 let mut node_1_per_peer_lock;
1304 let mut node_1_peer_state_lock;
1305 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1306 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1308 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1309 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1310 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1311 channel_1.get_short_channel_id().unwrap()
1313 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1314 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1315 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1316 channel_2.get_short_channel_id().unwrap()
1319 // First hop accounts for expected 1000 msat fee
1320 assert_eq!(chan_1_used_liquidity, Some(501000));
1321 assert_eq!(chan_2_used_liquidity, Some(500000));
1324 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1325 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1327 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1329 let mut node_0_per_peer_lock;
1330 let mut node_0_peer_state_lock;
1331 let mut node_1_per_peer_lock;
1332 let mut node_1_peer_state_lock;
1333 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1334 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1336 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1337 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1338 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1339 channel_1.get_short_channel_id().unwrap()
1341 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1342 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1343 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1344 channel_2.get_short_channel_id().unwrap()
1347 assert_eq!(chan_1_used_liquidity, None);
1348 assert_eq!(chan_2_used_liquidity, None);
1353 fn test_holding_cell_inflight_htlcs() {
1354 let chanmon_cfgs = create_chanmon_cfgs(2);
1355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1357 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1358 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1360 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1361 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1363 // Queue up two payments - one will be delivered right away, one immediately goes into the
1364 // holding cell as nodes[0] is AwaitingRAA.
1366 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1367 check_added_monitors!(nodes[0], 1);
1368 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1369 check_added_monitors!(nodes[0], 0);
1372 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1375 let mut node_0_per_peer_lock;
1376 let mut node_0_peer_state_lock;
1377 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1379 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1380 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1381 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1382 channel.get_short_channel_id().unwrap()
1385 assert_eq!(used_liquidity, Some(2000000));
1388 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1389 nodes[0].node.get_and_clear_pending_msg_events();
1393 fn intercepted_payment() {
1394 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1395 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1396 // payment or (b) fail the payment.
1397 do_test_intercepted_payment(InterceptTest::Forward);
1398 do_test_intercepted_payment(InterceptTest::Fail);
1399 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1400 do_test_intercepted_payment(InterceptTest::Timeout);
1403 fn do_test_intercepted_payment(test: InterceptTest) {
1404 let chanmon_cfgs = create_chanmon_cfgs(3);
1405 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1407 let mut zero_conf_chan_config = test_default_channel_config();
1408 zero_conf_chan_config.manually_accept_inbound_channels = true;
1409 let mut intercept_forwards_config = test_default_channel_config();
1410 intercept_forwards_config.accept_intercept_htlcs = true;
1411 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1413 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1414 let scorer = test_utils::TestScorer::with_penalty(0);
1415 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1417 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1419 let amt_msat = 100_000;
1420 let intercept_scid = nodes[1].node.get_intercept_scid();
1421 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1422 .with_route_hints(vec![
1423 RouteHint(vec![RouteHintHop {
1424 src_node_id: nodes[1].node.get_our_node_id(),
1425 short_channel_id: intercept_scid,
1428 proportional_millionths: 0,
1430 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1431 htlc_minimum_msat: None,
1432 htlc_maximum_msat: None,
1435 .with_features(nodes[2].node.invoice_features());
1436 let route_params = RouteParameters {
1438 final_value_msat: amt_msat,
1439 final_cltv_expiry_delta: TEST_FINAL_CLTV,
1441 let route = get_route(
1442 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1443 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1444 route_params.final_cltv_expiry_delta, nodes[0].logger, &scorer, &random_seed_bytes
1447 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60).unwrap();
1448 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1449 let payment_event = {
1451 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1452 assert_eq!(added_monitors.len(), 1);
1453 added_monitors.clear();
1455 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1456 assert_eq!(events.len(), 1);
1457 SendEvent::from_event(events.remove(0))
1459 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1460 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1462 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1463 let events = nodes[1].node.get_and_clear_pending_events();
1464 assert_eq!(events.len(), 1);
1465 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1466 crate::util::events::Event::HTLCIntercepted {
1467 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1469 assert_eq!(pmt_hash, payment_hash);
1470 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1471 assert_eq!(short_channel_id, intercept_scid);
1472 (intercept_id, expected_outbound_amount_msat)
1477 // Check for unknown channel id error.
1478 let unknown_chan_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &[42; 32], nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1479 assert_eq!(unknown_chan_id_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!([42; 32]), nodes[2].node.get_our_node_id()) });
1481 if test == InterceptTest::Fail {
1482 // Ensure we can fail the intercepted payment back.
1483 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1484 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1485 nodes[1].node.process_pending_htlc_forwards();
1486 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1487 check_added_monitors!(&nodes[1], 1);
1488 assert!(update_fail.update_fail_htlcs.len() == 1);
1489 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1490 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1491 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1493 // Ensure the payment fails with the expected error.
1494 let fail_conditions = PaymentFailedConditions::new()
1495 .blamed_scid(intercept_scid)
1496 .blamed_chan_closed(true)
1497 .expected_htlc_error_data(0x4000 | 10, &[]);
1498 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1499 } else if test == InterceptTest::Forward {
1500 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1501 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1502 let unusable_chan_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &temp_chan_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1503 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1504 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1506 // Open the just-in-time channel so the payment can then be forwarded.
1507 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1509 // Finally, forward the intercepted payment through and claim it.
1510 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1511 expect_pending_htlcs_forwardable!(nodes[1]);
1513 let payment_event = {
1515 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1516 assert_eq!(added_monitors.len(), 1);
1517 added_monitors.clear();
1519 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1520 assert_eq!(events.len(), 1);
1521 SendEvent::from_event(events.remove(0))
1523 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1524 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1525 expect_pending_htlcs_forwardable!(nodes[2]);
1527 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1528 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1529 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1530 let events = nodes[0].node.get_and_clear_pending_events();
1531 assert_eq!(events.len(), 2);
1533 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1534 assert_eq!(payment_preimage, *ev_preimage);
1535 assert_eq!(payment_hash, *ev_hash);
1536 assert_eq!(fee_paid_msat, &Some(1000));
1538 _ => panic!("Unexpected event")
1541 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1542 assert_eq!(hash, Some(payment_hash));
1544 _ => panic!("Unexpected event")
1546 } else if test == InterceptTest::Timeout {
1547 let mut block = Block {
1548 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1551 connect_block(&nodes[0], &block);
1552 connect_block(&nodes[1], &block);
1553 for _ in 0..TEST_FINAL_CLTV {
1554 block.header.prev_blockhash = block.block_hash();
1555 connect_block(&nodes[0], &block);
1556 connect_block(&nodes[1], &block);
1558 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1559 check_added_monitors!(nodes[1], 1);
1560 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1561 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1562 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1563 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1564 assert!(htlc_timeout_updates.update_fee.is_none());
1566 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1567 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1568 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1570 // Check for unknown intercept id error.
1571 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1572 let unknown_intercept_id_err = nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap_err();
1573 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1574 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1575 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });