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 chain::{ChannelMonitorUpdateErr, Confirm, Listen, Watch};
15 use chain::channelmonitor::{ANTI_REORG_DELAY, ChannelMonitor, LATENCY_GRACE_PERIOD_BLOCKS};
16 use chain::transaction::OutPoint;
17 use chain::keysinterface::KeysInterface;
18 use ln::channel::EXPIRE_PREV_CONFIG_TICKS;
19 use ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, ChannelManagerReadArgs, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure};
20 use ln::features::{InitFeatures, InvoiceFeatures};
22 use ln::msgs::ChannelMessageHandler;
23 use routing::router::{PaymentParameters, get_route};
24 use util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
26 use util::errors::APIError;
27 use util::enforcing_trait_impls::EnforcingSigner;
28 use util::ser::{ReadableArgs, Writeable};
31 use bitcoin::{Block, BlockHeader, BlockHash, TxMerkleNode};
32 use bitcoin::hashes::Hash;
33 use bitcoin::network::constants::Network;
37 use ln::functional_test_utils::*;
40 fn retry_single_path_payment() {
41 let chanmon_cfgs = create_chanmon_cfgs(3);
42 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
43 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
44 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
46 let _chan_0 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
47 let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1, InitFeatures::known(), InitFeatures::known());
48 // Rebalance to find a route
49 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
51 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
53 // Rebalance so that the first hop fails.
54 send_payment(&nodes[1], &vec!(&nodes[2])[..], 2_000_000);
56 // Make sure the payment fails on the first hop.
57 let payment_id = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
58 check_added_monitors!(nodes[0], 1);
59 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
60 assert_eq!(events.len(), 1);
61 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
62 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
63 check_added_monitors!(nodes[1], 0);
64 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
65 expect_pending_htlcs_forwardable!(nodes[1]);
66 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_1.2 }]);
67 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
68 assert!(htlc_updates.update_add_htlcs.is_empty());
69 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
70 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
71 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
72 check_added_monitors!(nodes[1], 1);
73 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
74 commitment_signed_dance!(nodes[0], nodes[1], htlc_updates.commitment_signed, false);
75 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
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, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
100 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
101 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
102 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
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, InitFeatures::known(), InitFeatures::known());
125 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
126 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
127 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2, InitFeatures::known(), InitFeatures::known());
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 = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
143 check_added_monitors!(nodes[0], 2); // one monitor per path
144 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
145 assert_eq!(events.len(), 2);
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, InitFeatures::known(), InitFeatures::known());
211 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
212 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
213 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
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 let _ = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
227 check_added_monitors!(nodes[0], 2); // one monitor per path
228 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
229 assert_eq!(events.len(), 2);
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, InitFeatures::known(), InitFeatures::known());
284 let chan_1 = create_announced_chan_between_nodes(&nodes, 2, 1, InitFeatures::known(), InitFeatures::known());
285 // Rebalance to find a route
286 send_payment(&nodes[2], &vec!(&nodes[1])[..], 3_000_000);
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 let payment_id = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
295 check_added_monitors!(nodes[0], 1);
296 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
297 assert_eq!(events.len(), 1);
298 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
299 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
300 check_added_monitors!(nodes[1], 0);
301 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
302 expect_pending_htlcs_forwardable!(nodes[1]);
303 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_1.2 }]);
304 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
305 assert!(htlc_updates.update_add_htlcs.is_empty());
306 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
307 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
308 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
309 check_added_monitors!(nodes[1], 1);
310 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
311 commitment_signed_dance!(nodes[0], nodes[1], htlc_updates.commitment_signed, false);
312 expect_payment_failed!(nodes[0], payment_hash, false);
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, payment_id) {
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, InitFeatures::known(), InitFeatures::known());
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)),
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<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
370 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
372 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
373 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
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 let payment_id = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).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 mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
412 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
414 persister = test_utils::TestPersister::new();
415 let keys_manager = &chanmon_cfgs[0].keys_manager;
416 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), nodes[0].logger, node_cfgs[0].fee_estimator, &persister, keys_manager);
417 nodes[0].chain_monitor = &new_chain_monitor;
418 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
419 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
420 &mut chan_0_monitor_read, keys_manager).unwrap();
421 assert!(chan_0_monitor_read.is_empty());
423 let mut nodes_0_read = &nodes_0_serialized[..];
424 let (_, nodes_0_deserialized_tmp) = {
425 let mut channel_monitors = HashMap::new();
426 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
427 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
428 default_config: test_default_channel_config(),
430 fee_estimator: node_cfgs[0].fee_estimator,
431 chain_monitor: nodes[0].chain_monitor,
432 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
433 logger: nodes[0].logger,
437 nodes_0_deserialized = nodes_0_deserialized_tmp;
438 assert!(nodes_0_read.is_empty());
440 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
441 nodes[0].node = &nodes_0_deserialized;
442 check_added_monitors!(nodes[0], 1);
444 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
445 // force-close the channel.
446 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
447 assert!(nodes[0].node.list_channels().is_empty());
448 assert!(nodes[0].node.has_pending_payments());
449 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
450 assert_eq!(as_broadcasted_txn.len(), 1);
451 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
453 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
454 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
455 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
457 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
458 // error, as the channel has hit the chain.
459 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
460 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
461 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
462 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
463 assert_eq!(as_err.len(), 1);
465 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
466 assert_eq!(node_id, nodes[1].node.get_our_node_id());
467 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
468 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_string() });
469 check_added_monitors!(nodes[1], 1);
470 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
472 _ => panic!("Unexpected event"),
474 check_closed_broadcast!(nodes[1], false);
476 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
477 // we close in a moment.
478 nodes[2].node.claim_funds(payment_preimage_1);
479 check_added_monitors!(nodes[2], 1);
480 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
482 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
483 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
484 check_added_monitors!(nodes[1], 1);
485 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
487 if confirm_before_reload {
488 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
489 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
492 // Create a new channel on which to retry the payment before we fail the payment via the
493 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
494 // connecting several blocks while creating the channel (implying time has passed).
495 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
496 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
498 mine_transaction(&nodes[1], &as_commitment_tx);
499 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
500 assert_eq!(bs_htlc_claim_txn.len(), 1);
501 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
502 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
504 if !confirm_before_reload {
505 mine_transaction(&nodes[0], &as_commitment_tx);
507 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
508 expect_payment_sent!(nodes[0], payment_preimage_1);
509 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
510 let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
511 assert_eq!(as_htlc_timeout_txn.len(), 3);
512 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = if as_htlc_timeout_txn[0] == as_commitment_tx {
513 (&as_htlc_timeout_txn[1], &as_htlc_timeout_txn[2])
515 assert_eq!(as_htlc_timeout_txn[2], as_commitment_tx);
516 (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1])
518 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
519 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
520 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
521 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
523 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
525 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
526 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
528 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
529 // reloaded) via a route over the new channel, which work without issue and eventually be
530 // received and claimed at the recipient just like any other payment.
531 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
533 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
534 // and not the original fee. We also update node[1]'s relevant config as
535 // do_claim_payment_along_route expects us to never overpay.
537 let mut channel_state = nodes[1].node.channel_state.lock().unwrap();
538 let mut channel = channel_state.by_id.get_mut(&chan_id_2).unwrap();
539 let mut new_config = channel.config();
540 new_config.forwarding_fee_base_msat += 100_000;
541 channel.update_config(&new_config);
542 new_route.paths[0][0].fee_msat += 100_000;
545 // Force expiration of the channel's previous config.
546 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
547 nodes[1].node.timer_tick_occurred();
550 assert!(nodes[0].node.retry_payment(&new_route, payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
551 nodes[0].node.retry_payment(&new_route, payment_id).unwrap();
552 check_added_monitors!(nodes[0], 1);
553 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
554 assert_eq!(events.len(), 1);
555 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
556 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
557 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
561 fn retry_with_no_persist() {
562 do_retry_with_no_persist(true);
563 do_retry_with_no_persist(false);
566 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
567 // Test that an off-chain completed payment is not retryable on restart. This was previously
568 // broken for dust payments, but we test for both dust and non-dust payments.
570 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
572 let chanmon_cfgs = create_chanmon_cfgs(3);
573 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
575 let mut manually_accept_config = test_default_channel_config();
576 manually_accept_config.manually_accept_inbound_channels = true;
578 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
580 let first_persister: test_utils::TestPersister;
581 let first_new_chain_monitor: test_utils::TestChainMonitor;
582 let first_nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
583 let second_persister: test_utils::TestPersister;
584 let second_new_chain_monitor: test_utils::TestChainMonitor;
585 let second_nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
586 let third_persister: test_utils::TestPersister;
587 let third_new_chain_monitor: test_utils::TestChainMonitor;
588 let third_nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
590 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
592 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
593 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
594 confirm_transaction(&nodes[0], &funding_tx);
595 confirm_transaction(&nodes[1], &funding_tx);
596 // Ignore the announcement_signatures messages
597 nodes[0].node.get_and_clear_pending_msg_events();
598 nodes[1].node.get_and_clear_pending_msg_events();
599 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
601 // Serialize the ChannelManager prior to sending payments
602 let mut nodes_0_serialized = nodes[0].node.encode();
604 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
605 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 });
607 // The ChannelMonitor should always be the latest version, as we're required to persist it
608 // during the `commitment_signed_dance!()`.
609 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
610 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
612 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
614 macro_rules! reload_node {
615 ($chain_monitor: ident, $chan_manager: ident, $persister: ident) => { {
616 $persister = test_utils::TestPersister::new();
617 let keys_manager = &chanmon_cfgs[0].keys_manager;
618 $chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), nodes[0].logger, node_cfgs[0].fee_estimator, &$persister, keys_manager);
619 nodes[0].chain_monitor = &$chain_monitor;
620 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
621 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
622 &mut chan_0_monitor_read, keys_manager).unwrap();
623 assert!(chan_0_monitor_read.is_empty());
625 let mut chan_1_monitor = None;
626 let mut channel_monitors = HashMap::new();
627 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
629 if !chan_1_monitor_serialized.0.is_empty() {
630 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
631 chan_1_monitor = Some(<(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
632 &mut chan_1_monitor_read, keys_manager).unwrap().1);
633 assert!(chan_1_monitor_read.is_empty());
634 channel_monitors.insert(chan_1_monitor.as_ref().unwrap().get_funding_txo().0, chan_1_monitor.as_mut().unwrap());
637 let mut nodes_0_read = &nodes_0_serialized[..];
638 let (_, nodes_0_deserialized_tmp) = {
639 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
640 default_config: test_default_channel_config(),
642 fee_estimator: node_cfgs[0].fee_estimator,
643 chain_monitor: nodes[0].chain_monitor,
644 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
645 logger: nodes[0].logger,
649 $chan_manager = nodes_0_deserialized_tmp;
650 assert!(nodes_0_read.is_empty());
652 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
653 if !chan_1_monitor_serialized.0.is_empty() {
654 let funding_txo = chan_1_monitor.as_ref().unwrap().get_funding_txo().0;
655 assert!(nodes[0].chain_monitor.watch_channel(funding_txo, chan_1_monitor.unwrap()).is_ok());
657 nodes[0].node = &$chan_manager;
658 check_added_monitors!(nodes[0], if !chan_1_monitor_serialized.0.is_empty() { 2 } else { 1 });
660 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
664 reload_node!(first_new_chain_monitor, first_nodes_0_deserialized, first_persister);
666 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
667 // force-close the channel.
668 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
669 assert!(nodes[0].node.list_channels().is_empty());
670 assert!(nodes[0].node.has_pending_payments());
671 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
673 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
674 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
676 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
677 // error, as the channel has hit the chain.
678 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
679 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
680 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
681 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
682 assert_eq!(as_err.len(), 1);
683 let bs_commitment_tx;
685 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
686 assert_eq!(node_id, nodes[1].node.get_our_node_id());
687 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
688 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_string() });
689 check_added_monitors!(nodes[1], 1);
690 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
692 _ => panic!("Unexpected event"),
694 check_closed_broadcast!(nodes[1], false);
696 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
697 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
698 // incoming HTLCs with the same payment hash later.
699 nodes[2].node.fail_htlc_backwards(&payment_hash);
700 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
701 check_added_monitors!(nodes[2], 1);
703 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
704 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
705 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
706 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
707 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
709 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
710 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
711 // after the commitment transaction, so always connect the commitment transaction.
712 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
713 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
715 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
716 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
717 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
718 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
719 assert_eq!(as_htlc_timeout.len(), 1);
721 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
722 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
723 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
724 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
727 // Create a new channel on which to retry the payment before we fail the payment via the
728 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
729 // connecting several blocks while creating the channel (implying time has passed).
730 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
731 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
732 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
734 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
735 // confirming, we will fail as it's considered still-pending...
736 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
737 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
738 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
740 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
741 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
742 // (which should also still work).
743 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
744 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
745 // We set mpp_parts_remain to avoid having abandon_payment called
746 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
748 chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
749 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
750 chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
751 get_monitor!(nodes[0], chan_id_3).write(&mut chan_1_monitor_serialized).unwrap();
752 nodes_0_serialized = nodes[0].node.encode();
754 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
755 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
757 reload_node!(second_new_chain_monitor, second_nodes_0_deserialized, second_persister);
758 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
760 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
761 // the payment is not (spuriously) listed as still pending.
762 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_ok());
763 check_added_monitors!(nodes[0], 1);
764 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
765 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
767 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
768 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
770 chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
771 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
772 chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
773 get_monitor!(nodes[0], chan_id_3).write(&mut chan_1_monitor_serialized).unwrap();
774 nodes_0_serialized = nodes[0].node.encode();
776 // Ensure that after reload we cannot retry the payment.
777 reload_node!(third_new_chain_monitor, third_nodes_0_deserialized, third_persister);
778 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
780 assert!(nodes[0].node.retry_payment(&new_route, payment_id).is_err());
781 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
785 fn test_completed_payment_not_retryable_on_reload() {
786 do_test_completed_payment_not_retryable_on_reload(true);
787 do_test_completed_payment_not_retryable_on_reload(false);
791 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
792 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
793 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
794 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
795 // the ChannelMonitor tells it to.
797 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
798 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
799 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
800 let chanmon_cfgs = create_chanmon_cfgs(2);
801 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
802 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
803 let persister: test_utils::TestPersister;
804 let new_chain_monitor: test_utils::TestChainMonitor;
805 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
806 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
808 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
810 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
812 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
813 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
814 check_closed_broadcast!(nodes[0], true);
815 check_added_monitors!(nodes[0], 1);
816 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
818 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
819 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
821 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
822 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
823 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
824 assert_eq!(node_txn.len(), 3);
825 assert_eq!(node_txn[0], node_txn[1]);
826 check_spends!(node_txn[1], funding_tx);
827 check_spends!(node_txn[2], node_txn[1]);
828 let timeout_txn = vec![node_txn[2].clone()];
830 nodes[1].node.claim_funds(payment_preimage);
831 check_added_monitors!(nodes[1], 1);
832 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
834 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
835 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
836 check_closed_broadcast!(nodes[1], true);
837 check_added_monitors!(nodes[1], 1);
838 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
839 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
840 assert_eq!(claim_txn.len(), 3);
841 check_spends!(claim_txn[0], node_txn[1]);
842 check_spends!(claim_txn[1], funding_tx);
843 check_spends!(claim_txn[2], claim_txn[1]);
845 header.prev_blockhash = nodes[0].best_block_hash();
846 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
848 if confirm_commitment_tx {
849 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
852 header.prev_blockhash = nodes[0].best_block_hash();
853 let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
856 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
857 connect_block(&nodes[0], &claim_block);
858 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
861 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
862 // returning TemporaryFailure. This should cause the claim event to never make its way to the
864 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
865 chanmon_cfgs[0].persister.set_update_ret(Err(ChannelMonitorUpdateErr::TemporaryFailure));
868 connect_blocks(&nodes[0], 1);
870 connect_block(&nodes[0], &claim_block);
873 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
874 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
875 .get_mut(&funding_txo).unwrap().drain().collect();
876 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice
877 assert!(mon_updates.len() == 1 || mon_updates.len() == 2);
878 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
879 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
881 // If we persist the ChannelManager here, we should get the PaymentSent event after
883 let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
884 if !persist_manager_post_event {
885 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
888 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
889 // payment sent event.
890 chanmon_cfgs[0].persister.set_update_ret(Ok(()));
891 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
892 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
893 for update in mon_updates {
894 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
897 expect_payment_failed!(nodes[0], payment_hash, false);
899 expect_payment_sent!(nodes[0], payment_preimage);
902 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
904 if persist_manager_post_event {
905 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
908 // Now reload nodes[0]...
909 persister = test_utils::TestPersister::new();
910 let keys_manager = &chanmon_cfgs[0].keys_manager;
911 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), nodes[0].logger, node_cfgs[0].fee_estimator, &persister, keys_manager);
912 nodes[0].chain_monitor = &new_chain_monitor;
913 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
914 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
915 &mut chan_0_monitor_read, keys_manager).unwrap();
916 assert!(chan_0_monitor_read.is_empty());
918 let (_, nodes_0_deserialized_tmp) = {
919 let mut channel_monitors = HashMap::new();
920 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
921 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
922 ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
923 default_config: Default::default(),
925 fee_estimator: node_cfgs[0].fee_estimator,
926 chain_monitor: nodes[0].chain_monitor,
927 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
928 logger: nodes[0].logger,
932 nodes_0_deserialized = nodes_0_deserialized_tmp;
934 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
935 check_added_monitors!(nodes[0], 1);
936 nodes[0].node = &nodes_0_deserialized;
938 if persist_manager_post_event {
939 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
940 } else if payment_timeout {
941 expect_payment_failed!(nodes[0], payment_hash, false);
943 expect_payment_sent!(nodes[0], payment_preimage);
946 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
947 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
948 // payment events should kick in, leaving us with no pending events here.
949 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
950 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
951 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
955 fn test_dup_htlc_onchain_fails_on_reload() {
956 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
957 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
958 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
959 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
960 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
961 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
965 fn test_fulfill_restart_failure() {
966 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
967 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
968 // again, or fail it, giving us free money.
970 // Of course probably they won't fail it and give us free money, but because we have code to
971 // handle it, we should test the logic for it anyway. We do that here.
972 let chanmon_cfgs = create_chanmon_cfgs(2);
973 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
974 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
975 let persister: test_utils::TestPersister;
976 let new_chain_monitor: test_utils::TestChainMonitor;
977 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
978 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
980 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
981 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
983 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
984 // pre-fulfill, which we do by serializing it here.
985 let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
986 nodes[1].node.write(&mut chan_manager_serialized).unwrap();
987 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
988 get_monitor!(nodes[1], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
990 nodes[1].node.claim_funds(payment_preimage);
991 check_added_monitors!(nodes[1], 1);
992 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
994 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
995 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
996 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
998 // Now reload nodes[1]...
999 persister = test_utils::TestPersister::new();
1000 let keys_manager = &chanmon_cfgs[1].keys_manager;
1001 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[1].chain_source), nodes[1].tx_broadcaster.clone(), nodes[1].logger, node_cfgs[1].fee_estimator, &persister, keys_manager);
1002 nodes[1].chain_monitor = &new_chain_monitor;
1003 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
1004 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
1005 &mut chan_0_monitor_read, keys_manager).unwrap();
1006 assert!(chan_0_monitor_read.is_empty());
1008 let (_, nodes_1_deserialized_tmp) = {
1009 let mut channel_monitors = HashMap::new();
1010 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
1011 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
1012 ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
1013 default_config: Default::default(),
1015 fee_estimator: node_cfgs[1].fee_estimator,
1016 chain_monitor: nodes[1].chain_monitor,
1017 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
1018 logger: nodes[1].logger,
1022 nodes_1_deserialized = nodes_1_deserialized_tmp;
1024 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
1025 check_added_monitors!(nodes[1], 1);
1026 nodes[1].node = &nodes_1_deserialized;
1028 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1029 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
1031 nodes[1].node.fail_htlc_backwards(&payment_hash);
1032 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
1033 check_added_monitors!(nodes[1], 1);
1034 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1035 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
1036 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
1037 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
1038 // it had already considered the payment fulfilled, and now they just got free money.
1039 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1043 fn get_ldk_payment_preimage() {
1044 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
1045 let chanmon_cfgs = create_chanmon_cfgs(2);
1046 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1047 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1048 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1049 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1051 let amt_msat = 60_000;
1052 let expiry_secs = 60 * 60;
1053 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs).unwrap();
1055 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
1056 .with_features(InvoiceFeatures::known());
1057 let scorer = test_utils::TestScorer::with_penalty(0);
1058 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
1059 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1060 let route = get_route(
1061 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
1062 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
1063 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
1064 let _payment_id = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1065 check_added_monitors!(nodes[0], 1);
1067 // Make sure to use `get_payment_preimage`
1068 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1069 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1070 assert_eq!(events.len(), 1);
1071 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
1072 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
1076 fn sent_probe_is_probe_of_sending_node() {
1077 let chanmon_cfgs = create_chanmon_cfgs(3);
1078 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1079 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1080 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1082 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1083 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1085 // First check we refuse to build a single-hop probe
1086 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
1087 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
1089 // Then build an actual two-hop probing path
1090 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1092 match nodes[0].node.send_probe(route.paths[0].clone()) {
1093 Ok((payment_hash, payment_id)) => {
1094 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
1095 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
1096 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
1101 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1102 check_added_monitors!(nodes[0], 1);
1106 fn successful_probe_yields_event() {
1107 let chanmon_cfgs = create_chanmon_cfgs(3);
1108 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1109 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1110 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1112 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1113 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1115 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
1117 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1119 // node[0] -- update_add_htlcs -> node[1]
1120 check_added_monitors!(nodes[0], 1);
1121 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1122 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1123 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1124 check_added_monitors!(nodes[1], 0);
1125 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1126 expect_pending_htlcs_forwardable!(nodes[1]);
1128 // node[1] -- update_add_htlcs -> node[2]
1129 check_added_monitors!(nodes[1], 1);
1130 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1131 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1132 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
1133 check_added_monitors!(nodes[2], 0);
1134 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
1136 // node[1] <- update_fail_htlcs -- node[2]
1137 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1138 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1139 check_added_monitors!(nodes[1], 0);
1140 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
1142 // node[0] <- update_fail_htlcs -- node[1]
1143 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1144 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1145 check_added_monitors!(nodes[0], 0);
1146 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1148 let mut events = nodes[0].node.get_and_clear_pending_events();
1149 assert_eq!(events.len(), 1);
1150 match events.drain(..).next().unwrap() {
1151 crate::util::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1152 assert_eq!(payment_id, ev_pid);
1153 assert_eq!(payment_hash, ev_ph);
1160 fn failed_probe_yields_event() {
1161 let chanmon_cfgs = create_chanmon_cfgs(3);
1162 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1163 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
1164 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1166 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1167 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000, InitFeatures::known(), InitFeatures::known());
1169 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id());
1171 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
1173 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1175 // node[0] -- update_add_htlcs -> node[1]
1176 check_added_monitors!(nodes[0], 1);
1177 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1178 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1179 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1180 check_added_monitors!(nodes[1], 0);
1181 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1182 expect_pending_htlcs_forwardable!(nodes[1]);
1184 // node[0] <- update_fail_htlcs -- node[1]
1185 check_added_monitors!(nodes[1], 1);
1186 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1187 // Skip the PendingHTLCsForwardable event
1188 let _events = nodes[1].node.get_and_clear_pending_events();
1189 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
1190 check_added_monitors!(nodes[0], 0);
1191 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
1193 let mut events = nodes[0].node.get_and_clear_pending_events();
1194 assert_eq!(events.len(), 1);
1195 match events.drain(..).next().unwrap() {
1196 crate::util::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1197 assert_eq!(payment_id, ev_pid);
1198 assert_eq!(payment_hash, ev_ph);
1205 fn onchain_failed_probe_yields_event() {
1206 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1208 let chanmon_cfgs = create_chanmon_cfgs(3);
1209 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1210 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1211 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1213 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
1214 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1216 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id());
1218 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1219 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1220 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1222 // node[0] -- update_add_htlcs -> node[1]
1223 check_added_monitors!(nodes[0], 1);
1224 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1225 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1226 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1227 check_added_monitors!(nodes[1], 0);
1228 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1229 expect_pending_htlcs_forwardable!(nodes[1]);
1231 check_added_monitors!(nodes[1], 1);
1232 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1234 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1235 // Node A, which after 6 confirmations should result in a probe failure event.
1236 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1237 confirm_transaction(&nodes[0], &bs_txn[0]);
1238 check_closed_broadcast!(&nodes[0], true);
1239 check_added_monitors!(nodes[0], 1);
1241 let mut events = nodes[0].node.get_and_clear_pending_events();
1242 assert_eq!(events.len(), 2);
1243 let mut found_probe_failed = false;
1244 for event in events.drain(..) {
1246 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1247 assert_eq!(payment_id, ev_pid);
1248 assert_eq!(payment_hash, ev_ph);
1249 found_probe_failed = true;
1251 Event::ChannelClosed { .. } => {},
1255 assert!(found_probe_failed);