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, RecentPaymentDetails};
20 use crate::ln::features::InvoiceFeatures;
22 use crate::ln::msgs::ChannelMessageHandler;
23 use crate::ln::outbound_payment::Retry;
24 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
25 use crate::routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RouteParameters};
26 use crate::routing::scoring::ChannelUsage;
27 use crate::util::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
28 use crate::util::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
32 use bitcoin::{Block, BlockHeader, TxMerkleNode};
33 use bitcoin::hashes::Hash;
34 use bitcoin::network::constants::Network;
36 use crate::prelude::*;
38 use crate::ln::functional_test_utils::*;
39 use crate::routing::gossip::NodeId;
40 #[cfg(feature = "std")]
42 crate::util::time::tests::SinceEpoch,
43 std::time::{SystemTime, Duration}
48 let chanmon_cfgs = create_chanmon_cfgs(4);
49 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
50 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
51 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
53 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
54 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
55 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
56 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
58 let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
59 let path = route.paths[0].clone();
60 route.paths.push(path);
61 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
62 route.paths[0][0].short_channel_id = chan_1_id;
63 route.paths[0][1].short_channel_id = chan_3_id;
64 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
65 route.paths[1][0].short_channel_id = chan_2_id;
66 route.paths[1][1].short_channel_id = chan_4_id;
67 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
68 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
73 let chanmon_cfgs = create_chanmon_cfgs(4);
74 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
75 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
76 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
78 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
79 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
80 let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
81 let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
83 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
85 let amt_msat = 1_000_000;
86 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
87 let path = route.paths[0].clone();
88 route.paths.push(path);
89 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
90 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
91 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
92 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
93 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
94 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
96 // Initiate the MPP payment.
97 let payment_id = PaymentId(payment_hash.0);
98 let mut route_params = RouteParameters {
99 payment_params: route.payment_params.clone().unwrap(),
100 final_value_msat: amt_msat,
101 final_cltv_expiry_delta: TEST_FINAL_CLTV,
104 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
105 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
106 check_added_monitors!(nodes[0], 2); // one monitor per path
107 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
108 assert_eq!(events.len(), 2);
110 // Pass half of the payment along the success path.
111 let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
112 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
114 // Add the HTLC along the first hop.
115 let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
116 let (update_add, commitment_signed) = match fail_path_msgs_1 {
117 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 } } => {
118 assert_eq!(update_add_htlcs.len(), 1);
119 assert!(update_fail_htlcs.is_empty());
120 assert!(update_fulfill_htlcs.is_empty());
121 assert!(update_fail_malformed_htlcs.is_empty());
122 assert!(update_fee.is_none());
123 (update_add_htlcs[0].clone(), commitment_signed.clone())
125 _ => panic!("Unexpected event"),
127 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
128 commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
130 // Attempt to forward the payment and complete the 2nd path's failure.
131 expect_pending_htlcs_forwardable!(&nodes[2]);
132 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 }]);
133 let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
134 assert!(htlc_updates.update_add_htlcs.is_empty());
135 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
136 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
137 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
138 check_added_monitors!(nodes[2], 1);
139 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
140 commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
141 let mut events = nodes[0].node.get_and_clear_pending_events();
143 Event::PendingHTLCsForwardable { .. } => {},
144 _ => panic!("Unexpected event")
147 expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
149 // Rebalance the channel so the second half of the payment can succeed.
150 send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
152 // Retry the second half of the payment and make sure it succeeds.
153 route.paths.remove(0);
154 route_params.final_value_msat = 1_000_000;
155 route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
156 nodes[0].router.expect_find_route(route_params, Ok(route));
157 nodes[0].node.process_pending_htlc_forwards();
158 check_added_monitors!(nodes[0], 1);
159 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
160 assert_eq!(events.len(), 1);
161 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
162 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
165 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
166 let chanmon_cfgs = create_chanmon_cfgs(4);
167 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
168 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
169 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
171 let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
172 let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
173 let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
174 let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
176 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
177 let path = route.paths[0].clone();
178 route.paths.push(path);
179 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
180 route.paths[0][0].short_channel_id = chan_1_update.contents.short_channel_id;
181 route.paths[0][1].short_channel_id = chan_3_update.contents.short_channel_id;
182 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
183 route.paths[1][0].short_channel_id = chan_2_update.contents.short_channel_id;
184 route.paths[1][1].short_channel_id = chan_4_update.contents.short_channel_id;
186 // Initiate the MPP payment.
187 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
188 check_added_monitors!(nodes[0], 2); // one monitor per path
189 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
190 assert_eq!(events.len(), 2);
192 // Pass half of the payment along the first path.
193 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
194 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
196 if send_partial_mpp {
197 // Time out the partial MPP
198 for _ in 0..MPP_TIMEOUT_TICKS {
199 nodes[3].node.timer_tick_occurred();
202 // Failed HTLC from node 3 -> 1
203 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
204 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
205 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
206 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
207 check_added_monitors!(nodes[3], 1);
208 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
210 // Failed HTLC from node 1 -> 0
211 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 }]);
212 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
213 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
214 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
215 check_added_monitors!(nodes[1], 1);
216 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
218 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
220 // Pass half of the payment along the second path.
221 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
222 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
224 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
225 for _ in 0..MPP_TIMEOUT_TICKS {
226 nodes[3].node.timer_tick_occurred();
229 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
234 fn mpp_receive_timeout() {
235 do_mpp_receive_timeout(true);
236 do_mpp_receive_timeout(false);
240 fn no_pending_leak_on_initial_send_failure() {
241 // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
242 // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
243 // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
244 // pending payment forever and never time it out.
245 // Here we test exactly that - retrying a payment when a peer was disconnected on the first
246 // try, and then check that no pending payment is being tracked.
247 let chanmon_cfgs = create_chanmon_cfgs(2);
248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
250 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
252 create_announced_chan_between_nodes(&nodes, 0, 1);
254 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
256 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
257 nodes[1].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
259 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)),
260 true, APIError::ChannelUnavailable { ref err },
261 assert_eq!(err, "Peer for first hop currently disconnected/pending monitor update!"));
263 assert!(!nodes[0].node.has_pending_payments());
266 fn do_retry_with_no_persist(confirm_before_reload: bool) {
267 // If we send a pending payment and `send_payment` returns success, we should always either
268 // return a payment failure event or a payment success event, and on failure the payment should
271 // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
272 // always persisted asynchronously), the ChannelManager has to reload some payment data from
273 // ChannelMonitor(s) in some cases. This tests that reloading.
275 // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
276 // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
277 // which has separate codepaths for "commitment transaction already confirmed" and not.
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 persister: test_utils::TestPersister;
282 let new_chain_monitor: test_utils::TestChainMonitor;
283 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>;
284 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
286 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
287 let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
289 // Serialize the ChannelManager prior to sending payments
290 let nodes_0_serialized = nodes[0].node.encode();
292 // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
294 let amt_msat = 1_000_000;
295 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
296 let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
297 let route_params = RouteParameters {
298 payment_params: route.payment_params.clone().unwrap(),
299 final_value_msat: amt_msat,
300 final_cltv_expiry_delta: TEST_FINAL_CLTV,
302 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
303 check_added_monitors!(nodes[0], 1);
305 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
306 assert_eq!(events.len(), 1);
307 let payment_event = SendEvent::from_event(events.pop().unwrap());
308 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
310 // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
311 // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
312 // which would prevent retry.
313 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
314 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
316 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
317 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
318 // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
319 let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
321 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
323 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
324 if confirm_before_reload {
325 mine_transaction(&nodes[0], &as_commitment_tx);
326 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
329 // The ChannelMonitor should always be the latest version, as we're required to persist it
330 // during the `commitment_signed_dance!()`.
331 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
332 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
334 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
335 // force-close the channel.
336 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
337 assert!(nodes[0].node.list_channels().is_empty());
338 assert!(nodes[0].node.has_pending_payments());
339 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
340 assert_eq!(as_broadcasted_txn.len(), 1);
341 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
343 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
344 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();
345 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
347 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
348 // error, as the channel has hit the chain.
349 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();
350 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
351 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
352 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
353 assert_eq!(as_err.len(), 1);
355 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
356 assert_eq!(node_id, nodes[1].node.get_our_node_id());
357 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
358 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()) });
359 check_added_monitors!(nodes[1], 1);
360 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
362 _ => panic!("Unexpected event"),
364 check_closed_broadcast!(nodes[1], false);
366 // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
367 // we close in a moment.
368 nodes[2].node.claim_funds(payment_preimage_1);
369 check_added_monitors!(nodes[2], 1);
370 expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
372 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
373 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
374 check_added_monitors!(nodes[1], 1);
375 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
376 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
378 if confirm_before_reload {
379 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
380 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
383 // Create a new channel on which to retry the payment before we fail the payment via the
384 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
385 // connecting several blocks while creating the channel (implying time has passed).
386 create_announced_chan_between_nodes(&nodes, 0, 1);
387 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
389 mine_transaction(&nodes[1], &as_commitment_tx);
390 let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
391 assert_eq!(bs_htlc_claim_txn.len(), 1);
392 check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
394 if !confirm_before_reload {
395 mine_transaction(&nodes[0], &as_commitment_tx);
397 mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
398 expect_payment_sent!(nodes[0], payment_preimage_1);
399 connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
400 let as_htlc_timeout_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
401 assert_eq!(as_htlc_timeout_txn.len(), 2);
402 let (first_htlc_timeout_tx, second_htlc_timeout_tx) = (&as_htlc_timeout_txn[0], &as_htlc_timeout_txn[1]);
403 check_spends!(first_htlc_timeout_tx, as_commitment_tx);
404 check_spends!(second_htlc_timeout_tx, as_commitment_tx);
405 if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
406 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
408 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
410 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
411 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
413 // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
414 // reloaded) via a route over the new channel, which work without issue and eventually be
415 // received and claimed at the recipient just like any other payment.
416 let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
418 // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
419 // and not the original fee. We also update node[1]'s relevant config as
420 // do_claim_payment_along_route expects us to never overpay.
422 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
423 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
424 .unwrap().lock().unwrap();
425 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
426 let mut new_config = channel.config();
427 new_config.forwarding_fee_base_msat += 100_000;
428 channel.update_config(&new_config);
429 new_route.paths[0][0].fee_msat += 100_000;
432 // Force expiration of the channel's previous config.
433 for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
434 nodes[1].node.timer_tick_occurred();
437 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id_1).is_err()); // Shouldn't be allowed to retry a fulfilled payment
438 nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
439 check_added_monitors!(nodes[0], 1);
440 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
441 assert_eq!(events.len(), 1);
442 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
443 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
444 expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0][0].fee_msat));
448 fn retry_with_no_persist() {
449 do_retry_with_no_persist(true);
450 do_retry_with_no_persist(false);
453 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
454 // Test that an off-chain completed payment is not retryable on restart. This was previously
455 // broken for dust payments, but we test for both dust and non-dust payments.
457 // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
459 let chanmon_cfgs = create_chanmon_cfgs(3);
460 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
462 let mut manually_accept_config = test_default_channel_config();
463 manually_accept_config.manually_accept_inbound_channels = true;
465 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
467 let first_persister: test_utils::TestPersister;
468 let first_new_chain_monitor: test_utils::TestChainMonitor;
469 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>;
470 let second_persister: test_utils::TestPersister;
471 let second_new_chain_monitor: test_utils::TestChainMonitor;
472 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>;
473 let third_persister: test_utils::TestPersister;
474 let third_new_chain_monitor: test_utils::TestChainMonitor;
475 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>;
477 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
479 // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
480 let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
481 confirm_transaction(&nodes[0], &funding_tx);
482 confirm_transaction(&nodes[1], &funding_tx);
483 // Ignore the announcement_signatures messages
484 nodes[0].node.get_and_clear_pending_msg_events();
485 nodes[1].node.get_and_clear_pending_msg_events();
486 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
488 // Serialize the ChannelManager prior to sending payments
489 let mut nodes_0_serialized = nodes[0].node.encode();
491 let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
492 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 });
494 // The ChannelMonitor should always be the latest version, as we're required to persist it
495 // during the `commitment_signed_dance!()`.
496 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
498 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);
499 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
501 // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
502 // force-close the channel.
503 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
504 assert!(nodes[0].node.list_channels().is_empty());
505 assert!(nodes[0].node.has_pending_payments());
506 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
508 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();
509 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
511 // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
512 // error, as the channel has hit the chain.
513 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();
514 let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
515 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
516 let as_err = nodes[0].node.get_and_clear_pending_msg_events();
517 assert_eq!(as_err.len(), 1);
518 let bs_commitment_tx;
520 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
521 assert_eq!(node_id, nodes[1].node.get_our_node_id());
522 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
523 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()) });
524 check_added_monitors!(nodes[1], 1);
525 bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
527 _ => panic!("Unexpected event"),
529 check_closed_broadcast!(nodes[1], false);
531 // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
532 // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
533 // incoming HTLCs with the same payment hash later.
534 nodes[2].node.fail_htlc_backwards(&payment_hash);
535 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
536 check_added_monitors!(nodes[2], 1);
538 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
539 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
540 commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
541 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
542 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
544 // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
545 // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
546 // after the commitment transaction, so always connect the commitment transaction.
547 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
548 mine_transaction(&nodes[1], &bs_commitment_tx[0]);
550 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
551 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
552 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
553 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
554 assert_eq!(as_htlc_timeout.len(), 1);
556 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
557 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
558 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
559 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
562 // Create a new channel on which to retry the payment before we fail the payment via the
563 // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
564 // connecting several blocks while creating the channel (implying time has passed).
565 // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
566 let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
567 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
569 // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
570 // confirming, we will fail as it's considered still-pending...
571 let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
572 match nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id) {
573 Err(PaymentSendFailure::DuplicatePayment) => {},
574 _ => panic!("Unexpected error")
576 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
578 // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
579 // again. We serialize the node first as we'll then test retrying the HTLC after a restart
580 // (which should also still work).
581 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
582 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
583 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
585 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
586 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
587 nodes_0_serialized = nodes[0].node.encode();
589 // After the payment failed, we're free to send it again.
590 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id).is_ok());
591 assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
593 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);
594 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
596 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
598 // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
599 // the payment is not (spuriously) listed as still pending.
600 assert!(nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id).is_ok());
601 check_added_monitors!(nodes[0], 1);
602 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
603 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
605 match nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id) {
606 Err(PaymentSendFailure::DuplicatePayment) => {},
607 _ => panic!("Unexpected error")
609 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
611 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
612 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
613 nodes_0_serialized = nodes[0].node.encode();
615 // Check that after reload we can send the payment again (though we shouldn't, since it was
616 // claimed previously).
617 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);
618 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
620 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
622 match nodes[0].node.send_payment(&new_route, payment_hash, &Some(payment_secret), payment_id) {
623 Err(PaymentSendFailure::DuplicatePayment) => {},
624 _ => panic!("Unexpected error")
626 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
630 fn test_completed_payment_not_retryable_on_reload() {
631 do_test_completed_payment_not_retryable_on_reload(true);
632 do_test_completed_payment_not_retryable_on_reload(false);
636 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
637 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
638 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
639 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
640 // the ChannelMonitor tells it to.
642 // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
643 // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
644 // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
645 let chanmon_cfgs = create_chanmon_cfgs(2);
646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
648 let persister: test_utils::TestPersister;
649 let new_chain_monitor: test_utils::TestChainMonitor;
650 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>;
651 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
653 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
655 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
657 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
658 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
659 check_closed_broadcast!(nodes[0], true);
660 check_added_monitors!(nodes[0], 1);
661 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
663 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
664 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
666 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
667 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
668 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
669 assert_eq!(node_txn.len(), 3);
670 assert_eq!(node_txn[0], node_txn[1]);
671 check_spends!(node_txn[1], funding_tx);
672 check_spends!(node_txn[2], node_txn[1]);
673 let timeout_txn = vec![node_txn[2].clone()];
675 nodes[1].node.claim_funds(payment_preimage);
676 check_added_monitors!(nodes[1], 1);
677 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
679 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
680 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
681 check_closed_broadcast!(nodes[1], true);
682 check_added_monitors!(nodes[1], 1);
683 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
684 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
685 assert_eq!(claim_txn.len(), 1);
686 check_spends!(claim_txn[0], node_txn[1]);
688 header.prev_blockhash = nodes[0].best_block_hash();
689 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
691 if confirm_commitment_tx {
692 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
695 header.prev_blockhash = nodes[0].best_block_hash();
696 let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
699 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
700 connect_block(&nodes[0], &claim_block);
701 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
704 // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
705 // returning InProgress. This should cause the claim event to never make its way to the
707 chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
708 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
711 connect_blocks(&nodes[0], 1);
713 connect_block(&nodes[0], &claim_block);
716 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
717 let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
718 .get_mut(&funding_txo).unwrap().drain().collect();
719 // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
720 // If we're testing connection idempotency we may get substantially more.
721 assert!(mon_updates.len() >= 1);
722 assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
723 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
725 // If we persist the ChannelManager here, we should get the PaymentSent event after
727 let mut chan_manager_serialized = Vec::new();
728 if !persist_manager_post_event {
729 chan_manager_serialized = nodes[0].node.encode();
732 // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
733 // payment sent event.
734 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
735 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
736 for update in mon_updates {
737 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
740 expect_payment_failed!(nodes[0], payment_hash, false);
742 expect_payment_sent!(nodes[0], payment_preimage);
745 // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
747 if persist_manager_post_event {
748 chan_manager_serialized = nodes[0].node.encode();
751 // Now reload nodes[0]...
752 reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
754 if persist_manager_post_event {
755 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
756 } else if payment_timeout {
757 expect_payment_failed!(nodes[0], payment_hash, false);
759 expect_payment_sent!(nodes[0], payment_preimage);
762 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
763 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
764 // payment events should kick in, leaving us with no pending events here.
765 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
766 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
767 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
771 fn test_dup_htlc_onchain_fails_on_reload() {
772 do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
773 do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
774 do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
775 do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
776 do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
777 do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
781 fn test_fulfill_restart_failure() {
782 // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
783 // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
784 // again, or fail it, giving us free money.
786 // Of course probably they won't fail it and give us free money, but because we have code to
787 // handle it, we should test the logic for it anyway. We do that here.
788 let chanmon_cfgs = create_chanmon_cfgs(2);
789 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
790 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
791 let persister: test_utils::TestPersister;
792 let new_chain_monitor: test_utils::TestChainMonitor;
793 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>;
794 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
796 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
797 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
799 // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
800 // pre-fulfill, which we do by serializing it here.
801 let chan_manager_serialized = nodes[1].node.encode();
802 let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
804 nodes[1].node.claim_funds(payment_preimage);
805 check_added_monitors!(nodes[1], 1);
806 expect_payment_claimed!(nodes[1], payment_hash, 100_000);
808 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
809 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
810 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
812 // Now reload nodes[1]...
813 reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
815 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
816 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
818 nodes[1].node.fail_htlc_backwards(&payment_hash);
819 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
820 check_added_monitors!(nodes[1], 1);
821 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
822 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
823 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
824 // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
825 // it had already considered the payment fulfilled, and now they just got free money.
826 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
830 fn get_ldk_payment_preimage() {
831 // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
832 let chanmon_cfgs = create_chanmon_cfgs(2);
833 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
834 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
835 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
836 create_announced_chan_between_nodes(&nodes, 0, 1);
838 let amt_msat = 60_000;
839 let expiry_secs = 60 * 60;
840 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
842 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
843 .with_features(nodes[1].node.invoice_features());
844 let scorer = test_utils::TestScorer::new();
845 let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
846 let random_seed_bytes = keys_manager.get_secure_random_bytes();
847 let route = get_route(
848 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
849 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
850 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
851 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
852 check_added_monitors!(nodes[0], 1);
854 // Make sure to use `get_payment_preimage`
855 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
856 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
857 assert_eq!(events.len(), 1);
858 pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
859 claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
863 fn sent_probe_is_probe_of_sending_node() {
864 let chanmon_cfgs = create_chanmon_cfgs(3);
865 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
866 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
867 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
869 create_announced_chan_between_nodes(&nodes, 0, 1);
870 create_announced_chan_between_nodes(&nodes, 1, 2);
872 // First check we refuse to build a single-hop probe
873 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
874 assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
876 // Then build an actual two-hop probing path
877 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
879 match nodes[0].node.send_probe(route.paths[0].clone()) {
880 Ok((payment_hash, payment_id)) => {
881 assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
882 assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
883 assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
888 get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
889 check_added_monitors!(nodes[0], 1);
893 fn successful_probe_yields_event() {
894 let chanmon_cfgs = create_chanmon_cfgs(3);
895 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
896 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
897 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
899 create_announced_chan_between_nodes(&nodes, 0, 1);
900 create_announced_chan_between_nodes(&nodes, 1, 2);
902 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
904 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
906 // node[0] -- update_add_htlcs -> node[1]
907 check_added_monitors!(nodes[0], 1);
908 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
909 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
910 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
911 check_added_monitors!(nodes[1], 0);
912 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
913 expect_pending_htlcs_forwardable!(nodes[1]);
915 // node[1] -- update_add_htlcs -> node[2]
916 check_added_monitors!(nodes[1], 1);
917 let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
918 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
919 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
920 check_added_monitors!(nodes[2], 0);
921 commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
923 // node[1] <- update_fail_htlcs -- node[2]
924 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
925 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
926 check_added_monitors!(nodes[1], 0);
927 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
929 // node[0] <- update_fail_htlcs -- node[1]
930 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
931 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
932 check_added_monitors!(nodes[0], 0);
933 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
935 let mut events = nodes[0].node.get_and_clear_pending_events();
936 assert_eq!(events.len(), 1);
937 match events.drain(..).next().unwrap() {
938 crate::util::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
939 assert_eq!(payment_id, ev_pid);
940 assert_eq!(payment_hash, ev_ph);
947 fn failed_probe_yields_event() {
948 let chanmon_cfgs = create_chanmon_cfgs(3);
949 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
950 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
951 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
953 create_announced_chan_between_nodes(&nodes, 0, 1);
954 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
956 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
958 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
960 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
962 // node[0] -- update_add_htlcs -> node[1]
963 check_added_monitors!(nodes[0], 1);
964 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
965 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
966 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
967 check_added_monitors!(nodes[1], 0);
968 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
969 expect_pending_htlcs_forwardable!(nodes[1]);
971 // node[0] <- update_fail_htlcs -- node[1]
972 check_added_monitors!(nodes[1], 1);
973 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
974 // Skip the PendingHTLCsForwardable event
975 let _events = nodes[1].node.get_and_clear_pending_events();
976 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
977 check_added_monitors!(nodes[0], 0);
978 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
980 let mut events = nodes[0].node.get_and_clear_pending_events();
981 assert_eq!(events.len(), 1);
982 match events.drain(..).next().unwrap() {
983 crate::util::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
984 assert_eq!(payment_id, ev_pid);
985 assert_eq!(payment_hash, ev_ph);
992 fn onchain_failed_probe_yields_event() {
993 // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
995 let chanmon_cfgs = create_chanmon_cfgs(3);
996 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
997 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
998 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1000 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1001 create_announced_chan_between_nodes(&nodes, 1, 2);
1003 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1005 // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1006 let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1007 let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1009 // node[0] -- update_add_htlcs -> node[1]
1010 check_added_monitors!(nodes[0], 1);
1011 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1012 let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1013 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1014 check_added_monitors!(nodes[1], 0);
1015 commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1016 expect_pending_htlcs_forwardable!(nodes[1]);
1018 check_added_monitors!(nodes[1], 1);
1019 let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1021 // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1022 // Node A, which after 6 confirmations should result in a probe failure event.
1023 let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1024 confirm_transaction(&nodes[0], &bs_txn[0]);
1025 check_closed_broadcast!(&nodes[0], true);
1026 check_added_monitors!(nodes[0], 1);
1028 let mut events = nodes[0].node.get_and_clear_pending_events();
1029 assert_eq!(events.len(), 2);
1030 let mut found_probe_failed = false;
1031 for event in events.drain(..) {
1033 Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1034 assert_eq!(payment_id, ev_pid);
1035 assert_eq!(payment_hash, ev_ph);
1036 found_probe_failed = true;
1038 Event::ChannelClosed { .. } => {},
1042 assert!(found_probe_failed);
1046 fn claimed_send_payment_idempotent() {
1047 // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1048 let chanmon_cfgs = create_chanmon_cfgs(2);
1049 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1050 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1051 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1053 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1055 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1056 let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1058 macro_rules! check_send_rejected {
1060 // If we try to resend a new payment with a different payment_hash but with the same
1061 // payment_id, it should be rejected.
1062 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1064 Err(PaymentSendFailure::DuplicatePayment) => {},
1065 _ => panic!("Unexpected send result: {:?}", send_result),
1068 // Further, if we try to send a spontaneous payment with the same payment_id it should
1069 // also be rejected.
1070 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1072 Err(PaymentSendFailure::DuplicatePayment) => {},
1073 _ => panic!("Unexpected send result: {:?}", send_result),
1078 check_send_rejected!();
1080 // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1081 // not been seen by the user. At this point, from the user perspective nothing has changed, so
1082 // we must remain just as idempotent as we were before.
1083 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1085 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1086 nodes[0].node.timer_tick_occurred();
1089 check_send_rejected!();
1091 // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1092 // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1093 // the payment complete. However, they could have called `send_payment` while the event was
1094 // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1095 // after the event is handled a duplicate payment should sitll be rejected.
1096 expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1097 check_send_rejected!();
1099 // If relatively little time has passed, a duplicate payment should still fail.
1100 nodes[0].node.timer_tick_occurred();
1101 check_send_rejected!();
1103 // However, after some time has passed (at least more than the one timer tick above), a
1104 // duplicate payment should go through, as ChannelManager should no longer have any remaining
1105 // references to the old payment data.
1106 for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1107 nodes[0].node.timer_tick_occurred();
1110 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1111 check_added_monitors!(nodes[0], 1);
1112 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1113 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1117 fn abandoned_send_payment_idempotent() {
1118 // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1120 let chanmon_cfgs = create_chanmon_cfgs(2);
1121 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1122 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1123 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1125 create_announced_chan_between_nodes(&nodes, 0, 1).2;
1127 let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1128 let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1130 macro_rules! check_send_rejected {
1132 // If we try to resend a new payment with a different payment_hash but with the same
1133 // payment_id, it should be rejected.
1134 let send_result = nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id);
1136 Err(PaymentSendFailure::DuplicatePayment) => {},
1137 _ => panic!("Unexpected send result: {:?}", send_result),
1140 // Further, if we try to send a spontaneous payment with the same payment_id it should
1141 // also be rejected.
1142 let send_result = nodes[0].node.send_spontaneous_payment(&route, None, payment_id);
1144 Err(PaymentSendFailure::DuplicatePayment) => {},
1145 _ => panic!("Unexpected send result: {:?}", send_result),
1150 check_send_rejected!();
1152 nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1153 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1155 // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1157 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1158 nodes[0].node.timer_tick_occurred();
1160 check_send_rejected!();
1162 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash);
1164 // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1165 // failed payment back.
1166 nodes[0].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), payment_id).unwrap();
1167 check_added_monitors!(nodes[0], 1);
1168 pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1169 claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1172 #[derive(PartialEq)]
1173 enum InterceptTest {
1180 fn test_trivial_inflight_htlc_tracking(){
1181 // In this test, we test three scenarios:
1182 // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1183 // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1184 // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1185 let chanmon_cfgs = create_chanmon_cfgs(3);
1186 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1187 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1188 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1190 let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1191 let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1193 // Send and claim the payment. Inflight HTLCs should be empty.
1194 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 500000);
1195 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1196 check_added_monitors!(nodes[0], 1);
1197 pass_along_route(&nodes[0], &[&vec!(&nodes[1], &nodes[2])[..]], 500000, payment_hash, payment_secret);
1198 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], payment_preimage);
1200 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1202 let mut node_0_per_peer_lock;
1203 let mut node_0_peer_state_lock;
1204 let mut node_1_per_peer_lock;
1205 let mut node_1_peer_state_lock;
1206 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1207 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1209 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1210 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1211 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1212 channel_1.get_short_channel_id().unwrap()
1214 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1215 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1216 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1217 channel_2.get_short_channel_id().unwrap()
1220 assert_eq!(chan_1_used_liquidity, None);
1221 assert_eq!(chan_2_used_liquidity, None);
1223 let pending_payments = nodes[0].node.list_recent_payments();
1224 assert_eq!(pending_payments.len(), 1);
1225 assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1227 // Remove fulfilled payment
1228 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1229 nodes[0].node.timer_tick_occurred();
1232 // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1233 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 500000);
1235 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1237 let mut node_0_per_peer_lock;
1238 let mut node_0_peer_state_lock;
1239 let mut node_1_per_peer_lock;
1240 let mut node_1_peer_state_lock;
1241 let channel_1 = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1242 let channel_2 = get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1244 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1245 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1246 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1247 channel_1.get_short_channel_id().unwrap()
1249 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1250 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1251 &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1252 channel_2.get_short_channel_id().unwrap()
1255 // First hop accounts for expected 1000 msat fee
1256 assert_eq!(chan_1_used_liquidity, Some(501000));
1257 assert_eq!(chan_2_used_liquidity, Some(500000));
1259 let pending_payments = nodes[0].node.list_recent_payments();
1260 assert_eq!(pending_payments.len(), 1);
1261 assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1263 // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1264 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1266 // Remove fulfilled payment
1267 for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1268 nodes[0].node.timer_tick_occurred();
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 let pending_payments = nodes[0].node.list_recent_payments();
1297 assert_eq!(pending_payments.len(), 0);
1301 fn test_holding_cell_inflight_htlcs() {
1302 let chanmon_cfgs = create_chanmon_cfgs(2);
1303 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1304 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1305 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1306 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1308 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1309 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1311 // Queue up two payments - one will be delivered right away, one immediately goes into the
1312 // holding cell as nodes[0] is AwaitingRAA.
1314 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1315 check_added_monitors!(nodes[0], 1);
1316 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1317 check_added_monitors!(nodes[0], 0);
1320 let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1323 let mut node_0_per_peer_lock;
1324 let mut node_0_peer_state_lock;
1325 let channel = get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1327 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1328 &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1329 &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1330 channel.get_short_channel_id().unwrap()
1333 assert_eq!(used_liquidity, Some(2000000));
1336 // Clear pending events so test doesn't throw a "Had excess message on node..." error
1337 nodes[0].node.get_and_clear_pending_msg_events();
1341 fn intercepted_payment() {
1342 // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1343 // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1344 // payment or (b) fail the payment.
1345 do_test_intercepted_payment(InterceptTest::Forward);
1346 do_test_intercepted_payment(InterceptTest::Fail);
1347 // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1348 do_test_intercepted_payment(InterceptTest::Timeout);
1351 fn do_test_intercepted_payment(test: InterceptTest) {
1352 let chanmon_cfgs = create_chanmon_cfgs(3);
1353 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1355 let mut zero_conf_chan_config = test_default_channel_config();
1356 zero_conf_chan_config.manually_accept_inbound_channels = true;
1357 let mut intercept_forwards_config = test_default_channel_config();
1358 intercept_forwards_config.accept_intercept_htlcs = true;
1359 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1361 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1362 let scorer = test_utils::TestScorer::new();
1363 let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1365 let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1367 let amt_msat = 100_000;
1368 let intercept_scid = nodes[1].node.get_intercept_scid();
1369 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1370 .with_route_hints(vec![
1371 RouteHint(vec![RouteHintHop {
1372 src_node_id: nodes[1].node.get_our_node_id(),
1373 short_channel_id: intercept_scid,
1376 proportional_millionths: 0,
1378 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1379 htlc_minimum_msat: None,
1380 htlc_maximum_msat: None,
1383 .with_features(nodes[2].node.invoice_features());
1384 let route_params = RouteParameters {
1386 final_value_msat: amt_msat,
1387 final_cltv_expiry_delta: TEST_FINAL_CLTV,
1389 let route = get_route(
1390 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1391 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1392 route_params.final_cltv_expiry_delta, nodes[0].logger, &scorer, &random_seed_bytes
1395 let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1396 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1397 let payment_event = {
1399 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1400 assert_eq!(added_monitors.len(), 1);
1401 added_monitors.clear();
1403 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1404 assert_eq!(events.len(), 1);
1405 SendEvent::from_event(events.remove(0))
1407 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1408 commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1410 // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1411 let events = nodes[1].node.get_and_clear_pending_events();
1412 assert_eq!(events.len(), 1);
1413 let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1414 crate::util::events::Event::HTLCIntercepted {
1415 intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1417 assert_eq!(pmt_hash, payment_hash);
1418 assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1419 assert_eq!(short_channel_id, intercept_scid);
1420 (intercept_id, expected_outbound_amount_msat)
1425 // Check for unknown channel id error.
1426 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();
1427 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()) });
1429 if test == InterceptTest::Fail {
1430 // Ensure we can fail the intercepted payment back.
1431 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1432 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1433 nodes[1].node.process_pending_htlc_forwards();
1434 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1435 check_added_monitors!(&nodes[1], 1);
1436 assert!(update_fail.update_fail_htlcs.len() == 1);
1437 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1438 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1439 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1441 // Ensure the payment fails with the expected error.
1442 let fail_conditions = PaymentFailedConditions::new()
1443 .blamed_scid(intercept_scid)
1444 .blamed_chan_closed(true)
1445 .expected_htlc_error_data(0x4000 | 10, &[]);
1446 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1447 } else if test == InterceptTest::Forward {
1448 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1449 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1450 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();
1451 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1452 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1454 // Open the just-in-time channel so the payment can then be forwarded.
1455 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1457 // Finally, forward the intercepted payment through and claim it.
1458 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1459 expect_pending_htlcs_forwardable!(nodes[1]);
1461 let payment_event = {
1463 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1464 assert_eq!(added_monitors.len(), 1);
1465 added_monitors.clear();
1467 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1468 assert_eq!(events.len(), 1);
1469 SendEvent::from_event(events.remove(0))
1471 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1472 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1473 expect_pending_htlcs_forwardable!(nodes[2]);
1475 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1476 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1477 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1478 let events = nodes[0].node.get_and_clear_pending_events();
1479 assert_eq!(events.len(), 2);
1481 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1482 assert_eq!(payment_preimage, *ev_preimage);
1483 assert_eq!(payment_hash, *ev_hash);
1484 assert_eq!(fee_paid_msat, &Some(1000));
1486 _ => panic!("Unexpected event")
1489 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1490 assert_eq!(hash, Some(payment_hash));
1492 _ => panic!("Unexpected event")
1494 } else if test == InterceptTest::Timeout {
1495 let mut block = Block {
1496 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1499 connect_block(&nodes[0], &block);
1500 connect_block(&nodes[1], &block);
1501 for _ in 0..TEST_FINAL_CLTV {
1502 block.header.prev_blockhash = block.block_hash();
1503 connect_block(&nodes[0], &block);
1504 connect_block(&nodes[1], &block);
1506 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1507 check_added_monitors!(nodes[1], 1);
1508 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1509 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1510 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1511 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1512 assert!(htlc_timeout_updates.update_fee.is_none());
1514 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1515 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1516 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1518 // Check for unknown intercept id error.
1519 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1520 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();
1521 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1522 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1523 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1527 #[derive(PartialEq)]
1538 fn automatic_retries() {
1539 do_automatic_retries(AutoRetry::Success);
1540 do_automatic_retries(AutoRetry::Spontaneous);
1541 do_automatic_retries(AutoRetry::FailAttempts);
1542 do_automatic_retries(AutoRetry::FailTimeout);
1543 do_automatic_retries(AutoRetry::FailOnRestart);
1544 do_automatic_retries(AutoRetry::FailOnRetry);
1546 fn do_automatic_retries(test: AutoRetry) {
1547 // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1549 let chanmon_cfgs = create_chanmon_cfgs(3);
1550 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1551 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1554 let new_chain_monitor;
1555 let node_0_deserialized;
1557 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1558 let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1559 let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1561 // Marshall data to send the payment
1562 #[cfg(feature = "std")]
1563 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1564 #[cfg(not(feature = "std"))]
1565 let payment_expiry_secs = 60 * 60;
1566 let amt_msat = 1000;
1567 let mut invoice_features = InvoiceFeatures::empty();
1568 invoice_features.set_variable_length_onion_required();
1569 invoice_features.set_payment_secret_required();
1570 invoice_features.set_basic_mpp_optional();
1571 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1572 .with_expiry_time(payment_expiry_secs as u64)
1573 .with_features(invoice_features);
1574 let route_params = RouteParameters {
1576 final_value_msat: amt_msat,
1577 final_cltv_expiry_delta: TEST_FINAL_CLTV,
1579 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1581 macro_rules! pass_failed_attempt_with_retry_along_path {
1582 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1583 // Send a payment attempt that fails due to lack of liquidity on the second hop
1584 check_added_monitors!(nodes[0], 1);
1585 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1586 let mut update_add = update_0.update_add_htlcs[0].clone();
1587 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1588 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1589 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1590 nodes[1].node.process_pending_htlc_forwards();
1591 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1592 vec![HTLCDestination::NextHopChannel {
1593 node_id: Some(nodes[2].node.get_our_node_id()),
1594 channel_id: $failing_channel_id,
1596 nodes[1].node.process_pending_htlc_forwards();
1597 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1598 check_added_monitors!(&nodes[1], 1);
1599 assert!(update_1.update_fail_htlcs.len() == 1);
1600 let fail_msg = update_1.update_fail_htlcs[0].clone();
1601 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1602 commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1604 // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1605 let mut events = nodes[0].node.get_and_clear_pending_events();
1606 assert_eq!(events.len(), 2);
1608 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
1609 assert_eq!(payment_hash, ev_payment_hash);
1610 assert_eq!(payment_failed_permanently, false);
1612 _ => panic!("Unexpected event"),
1614 if $expect_pending_htlcs_forwardable {
1616 Event::PendingHTLCsForwardable { .. } => {},
1617 _ => panic!("Unexpected event"),
1621 Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1622 assert_eq!(payment_hash, ev_payment_hash);
1624 _ => panic!("Unexpected event"),
1630 if test == AutoRetry::Success {
1631 // Test that we can succeed on the first retry.
1632 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1633 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1635 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1636 // attempt, since the initial second hop channel will be excluded from pathfinding
1637 create_announced_chan_between_nodes(&nodes, 1, 2);
1639 // We retry payments in `process_pending_htlc_forwards`
1640 nodes[0].node.process_pending_htlc_forwards();
1641 check_added_monitors!(nodes[0], 1);
1642 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1643 assert_eq!(msg_events.len(), 1);
1644 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1645 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1646 } else if test == AutoRetry::Spontaneous {
1647 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1648 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1650 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1651 // attempt, since the initial second hop channel will be excluded from pathfinding
1652 create_announced_chan_between_nodes(&nodes, 1, 2);
1654 // We retry payments in `process_pending_htlc_forwards`
1655 nodes[0].node.process_pending_htlc_forwards();
1656 check_added_monitors!(nodes[0], 1);
1657 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1658 assert_eq!(msg_events.len(), 1);
1659 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1660 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1661 } else if test == AutoRetry::FailAttempts {
1662 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1663 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1664 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1666 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1667 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1668 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1670 // We retry payments in `process_pending_htlc_forwards`
1671 nodes[0].node.process_pending_htlc_forwards();
1672 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1674 // Ensure we won't retry a second time.
1675 nodes[0].node.process_pending_htlc_forwards();
1676 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1677 assert_eq!(msg_events.len(), 0);
1678 } else if test == AutoRetry::FailTimeout {
1679 #[cfg(not(feature = "no-std"))] {
1680 // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1681 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
1682 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1684 // Advance the time so the second attempt fails due to timeout.
1685 SinceEpoch::advance(Duration::from_secs(61));
1687 // Make sure we don't retry again.
1688 nodes[0].node.process_pending_htlc_forwards();
1689 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1690 assert_eq!(msg_events.len(), 0);
1692 let mut events = nodes[0].node.get_and_clear_pending_events();
1693 assert_eq!(events.len(), 1);
1695 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1696 assert_eq!(payment_hash, *ev_payment_hash);
1697 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1699 _ => panic!("Unexpected event"),
1702 } else if test == AutoRetry::FailOnRestart {
1703 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1704 // attempts remaining prior to restart.
1705 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1706 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1708 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1709 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1710 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1712 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1713 nodes[0].node.process_pending_htlc_forwards();
1714 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1716 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1717 let node_encoded = nodes[0].node.encode();
1718 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1719 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1721 // Make sure we don't retry again.
1722 nodes[0].node.process_pending_htlc_forwards();
1723 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1724 assert_eq!(msg_events.len(), 0);
1726 let mut events = nodes[0].node.get_and_clear_pending_events();
1727 assert_eq!(events.len(), 1);
1729 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1730 assert_eq!(payment_hash, *ev_payment_hash);
1731 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1733 _ => panic!("Unexpected event"),
1735 } else if test == AutoRetry::FailOnRetry {
1736 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1737 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1739 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1740 // fail to find a route.
1741 nodes[0].node.process_pending_htlc_forwards();
1742 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1743 assert_eq!(msg_events.len(), 0);
1745 let mut events = nodes[0].node.get_and_clear_pending_events();
1746 assert_eq!(events.len(), 1);
1748 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
1749 assert_eq!(payment_hash, *ev_payment_hash);
1750 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1752 _ => panic!("Unexpected event"),
1758 fn auto_retry_partial_failure() {
1759 // Test that we'll retry appropriately on send partial failure and retry partial failure.
1760 let chanmon_cfgs = create_chanmon_cfgs(2);
1761 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1762 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1763 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1765 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1766 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1767 let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1769 // Marshall data to send the payment
1770 let amt_msat = 20_000;
1771 let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1772 #[cfg(feature = "std")]
1773 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1774 #[cfg(not(feature = "std"))]
1775 let payment_expiry_secs = 60 * 60;
1776 let mut invoice_features = InvoiceFeatures::empty();
1777 invoice_features.set_variable_length_onion_required();
1778 invoice_features.set_payment_secret_required();
1779 invoice_features.set_basic_mpp_optional();
1780 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1781 .with_expiry_time(payment_expiry_secs as u64)
1782 .with_features(invoice_features);
1783 let route_params = RouteParameters {
1785 final_value_msat: amt_msat,
1786 final_cltv_expiry_delta: TEST_FINAL_CLTV,
1789 // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1790 // second (for the initial send path2 over chan_2) fails.
1791 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1792 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1793 // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1794 // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1795 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1796 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1797 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1799 // Configure the initial send, retry1 and retry2's paths.
1800 let send_route = Route {
1803 pubkey: nodes[1].node.get_our_node_id(),
1804 node_features: nodes[1].node.node_features(),
1805 short_channel_id: chan_1_id,
1806 channel_features: nodes[1].node.channel_features(),
1807 fee_msat: amt_msat / 2,
1808 cltv_expiry_delta: 100,
1811 pubkey: nodes[1].node.get_our_node_id(),
1812 node_features: nodes[1].node.node_features(),
1813 short_channel_id: chan_2_id,
1814 channel_features: nodes[1].node.channel_features(),
1815 fee_msat: amt_msat / 2,
1816 cltv_expiry_delta: 100,
1819 payment_params: Some(route_params.payment_params.clone()),
1821 let retry_1_route = Route {
1824 pubkey: nodes[1].node.get_our_node_id(),
1825 node_features: nodes[1].node.node_features(),
1826 short_channel_id: chan_1_id,
1827 channel_features: nodes[1].node.channel_features(),
1828 fee_msat: amt_msat / 4,
1829 cltv_expiry_delta: 100,
1832 pubkey: nodes[1].node.get_our_node_id(),
1833 node_features: nodes[1].node.node_features(),
1834 short_channel_id: chan_3_id,
1835 channel_features: nodes[1].node.channel_features(),
1836 fee_msat: amt_msat / 4,
1837 cltv_expiry_delta: 100,
1840 payment_params: Some(route_params.payment_params.clone()),
1842 let retry_2_route = Route {
1845 pubkey: nodes[1].node.get_our_node_id(),
1846 node_features: nodes[1].node.node_features(),
1847 short_channel_id: chan_1_id,
1848 channel_features: nodes[1].node.channel_features(),
1849 fee_msat: amt_msat / 4,
1850 cltv_expiry_delta: 100,
1853 payment_params: Some(route_params.payment_params.clone()),
1855 nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1856 nodes[0].router.expect_find_route(RouteParameters {
1857 payment_params: route_params.payment_params.clone(),
1858 final_value_msat: amt_msat / 2, final_cltv_expiry_delta: TEST_FINAL_CLTV
1859 }, Ok(retry_1_route));
1860 nodes[0].router.expect_find_route(RouteParameters {
1861 payment_params: route_params.payment_params.clone(),
1862 final_value_msat: amt_msat / 4, final_cltv_expiry_delta: TEST_FINAL_CLTV
1863 }, Ok(retry_2_route));
1865 // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1866 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1867 let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1868 assert_eq!(closed_chan_events.len(), 2);
1869 match closed_chan_events[0] {
1870 Event::ChannelClosed { .. } => {},
1871 _ => panic!("Unexpected event"),
1873 match closed_chan_events[1] {
1874 Event::ChannelClosed { .. } => {},
1875 _ => panic!("Unexpected event"),
1878 // Pass the first part of the payment along the path.
1879 check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1880 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1882 // First message is the first update_add, remaining messages are broadcasting channel updates and
1883 // errors for the permfailed channels
1884 assert_eq!(msg_events.len(), 5);
1885 let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1887 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1888 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1889 check_added_monitors!(nodes[1], 1);
1890 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1892 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1893 check_added_monitors!(nodes[0], 1);
1894 let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1896 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1897 check_added_monitors!(nodes[0], 1);
1898 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1900 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1901 check_added_monitors!(nodes[1], 1);
1903 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1904 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1906 check_added_monitors!(nodes[1], 1);
1907 let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1909 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1910 check_added_monitors!(nodes[0], 1);
1912 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
1913 check_added_monitors!(nodes[0], 1);
1914 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1916 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1917 check_added_monitors!(nodes[1], 1);
1919 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1920 nodes[1].node.process_pending_htlc_forwards();
1921 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
1922 nodes[1].node.claim_funds(payment_preimage);
1923 expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
1924 let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1925 assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
1927 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
1928 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
1929 check_added_monitors!(nodes[0], 1);
1930 let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1932 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1933 check_added_monitors!(nodes[1], 4);
1934 let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1936 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1937 check_added_monitors!(nodes[1], 1);
1938 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1940 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1941 check_added_monitors!(nodes[0], 1);
1943 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
1944 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
1945 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
1946 check_added_monitors!(nodes[0], 1);
1947 let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1949 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
1950 check_added_monitors!(nodes[1], 1);
1952 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1953 check_added_monitors!(nodes[1], 1);
1954 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1956 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1957 check_added_monitors!(nodes[0], 1);
1958 expect_payment_sent!(nodes[0], payment_preimage);
1962 fn auto_retry_zero_attempts_send_error() {
1963 let chanmon_cfgs = create_chanmon_cfgs(2);
1964 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1965 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1966 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1968 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1969 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1971 // Marshall data to send the payment
1972 let amt_msat = 20_000;
1973 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1974 #[cfg(feature = "std")]
1975 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1976 #[cfg(not(feature = "std"))]
1977 let payment_expiry_secs = 60 * 60;
1978 let mut invoice_features = InvoiceFeatures::empty();
1979 invoice_features.set_variable_length_onion_required();
1980 invoice_features.set_payment_secret_required();
1981 invoice_features.set_basic_mpp_optional();
1982 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1983 .with_expiry_time(payment_expiry_secs as u64)
1984 .with_features(invoice_features);
1985 let route_params = RouteParameters {
1987 final_value_msat: amt_msat,
1988 final_cltv_expiry_delta: TEST_FINAL_CLTV,
1991 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1992 let err = nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap_err();
1993 if let PaymentSendFailure::AllFailedResendSafe(_) = err {
1994 } else { panic!("Unexpected error"); }
1995 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
1996 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 1); // channel close event
1997 check_added_monitors!(nodes[0], 2);
2001 fn fails_paying_after_rejected_by_payee() {
2002 let chanmon_cfgs = create_chanmon_cfgs(2);
2003 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2004 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2005 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2007 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2009 // Marshall data to send the payment
2010 let amt_msat = 20_000;
2011 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2012 #[cfg(feature = "std")]
2013 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2014 #[cfg(not(feature = "std"))]
2015 let payment_expiry_secs = 60 * 60;
2016 let mut invoice_features = InvoiceFeatures::empty();
2017 invoice_features.set_variable_length_onion_required();
2018 invoice_features.set_payment_secret_required();
2019 invoice_features.set_basic_mpp_optional();
2020 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2021 .with_expiry_time(payment_expiry_secs as u64)
2022 .with_features(invoice_features);
2023 let route_params = RouteParameters {
2025 final_value_msat: amt_msat,
2026 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2029 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2030 check_added_monitors!(nodes[0], 1);
2031 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2032 assert_eq!(events.len(), 1);
2033 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2034 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2035 check_added_monitors!(nodes[1], 0);
2036 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2037 expect_pending_htlcs_forwardable!(nodes[1]);
2038 expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2040 nodes[1].node.fail_htlc_backwards(&payment_hash);
2041 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2042 pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash);
2046 fn retry_multi_path_single_failed_payment() {
2047 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2048 let chanmon_cfgs = create_chanmon_cfgs(2);
2049 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2050 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2051 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2053 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2054 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2056 let amt_msat = 100_010_000;
2058 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2059 #[cfg(feature = "std")]
2060 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2061 #[cfg(not(feature = "std"))]
2062 let payment_expiry_secs = 60 * 60;
2063 let mut invoice_features = InvoiceFeatures::empty();
2064 invoice_features.set_variable_length_onion_required();
2065 invoice_features.set_payment_secret_required();
2066 invoice_features.set_basic_mpp_optional();
2067 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2068 .with_expiry_time(payment_expiry_secs as u64)
2069 .with_features(invoice_features);
2070 let route_params = RouteParameters {
2071 payment_params: payment_params.clone(),
2072 final_value_msat: amt_msat,
2073 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2076 let chans = nodes[0].node.list_usable_channels();
2077 let mut route = Route {
2080 pubkey: nodes[1].node.get_our_node_id(),
2081 node_features: nodes[1].node.node_features(),
2082 short_channel_id: chans[0].short_channel_id.unwrap(),
2083 channel_features: nodes[1].node.channel_features(),
2085 cltv_expiry_delta: 100,
2088 pubkey: nodes[1].node.get_our_node_id(),
2089 node_features: nodes[1].node.node_features(),
2090 short_channel_id: chans[1].short_channel_id.unwrap(),
2091 channel_features: nodes[1].node.channel_features(),
2092 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2093 cltv_expiry_delta: 100,
2096 payment_params: Some(payment_params),
2098 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2099 // On retry, split the payment across both channels.
2100 route.paths[0][0].fee_msat = 50_000_001;
2101 route.paths[1][0].fee_msat = 50_000_000;
2102 nodes[0].router.expect_find_route(RouteParameters {
2103 payment_params: route.payment_params.clone().unwrap(),
2104 // Note that the second request here requests the amount we originally failed to send,
2105 // not the amount remaining on the full payment, which should be changed.
2106 final_value_msat: 100_000_001, final_cltv_expiry_delta: TEST_FINAL_CLTV
2107 }, Ok(route.clone()));
2110 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2111 // The initial send attempt, 2 paths
2112 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2113 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2114 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2115 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2116 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2119 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2120 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2121 assert_eq!(htlc_msgs.len(), 2);
2122 check_added_monitors!(nodes[0], 2);
2126 fn immediate_retry_on_failure() {
2127 // Tests that we can/will retry immediately after a failure
2128 let chanmon_cfgs = create_chanmon_cfgs(2);
2129 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2130 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2131 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2133 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2134 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2136 let amt_msat = 100_000_001;
2137 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2138 #[cfg(feature = "std")]
2139 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2140 #[cfg(not(feature = "std"))]
2141 let payment_expiry_secs = 60 * 60;
2142 let mut invoice_features = InvoiceFeatures::empty();
2143 invoice_features.set_variable_length_onion_required();
2144 invoice_features.set_payment_secret_required();
2145 invoice_features.set_basic_mpp_optional();
2146 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2147 .with_expiry_time(payment_expiry_secs as u64)
2148 .with_features(invoice_features);
2149 let route_params = RouteParameters {
2151 final_value_msat: amt_msat,
2152 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2155 let chans = nodes[0].node.list_usable_channels();
2156 let mut route = Route {
2159 pubkey: nodes[1].node.get_our_node_id(),
2160 node_features: nodes[1].node.node_features(),
2161 short_channel_id: chans[0].short_channel_id.unwrap(),
2162 channel_features: nodes[1].node.channel_features(),
2163 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2164 cltv_expiry_delta: 100,
2167 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2169 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2170 // On retry, split the payment across both channels.
2171 route.paths.push(route.paths[0].clone());
2172 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2173 route.paths[0][0].fee_msat = 50_000_000;
2174 route.paths[1][0].fee_msat = 50_000_001;
2175 nodes[0].router.expect_find_route(RouteParameters {
2176 payment_params: route_params.payment_params.clone(),
2177 final_value_msat: amt_msat, final_cltv_expiry_delta: TEST_FINAL_CLTV
2178 }, Ok(route.clone()));
2180 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2181 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2182 assert_eq!(htlc_msgs.len(), 2);
2183 check_added_monitors!(nodes[0], 2);
2187 fn no_extra_retries_on_back_to_back_fail() {
2188 // In a previous release, we had a race where we may exceed the payment retry count if we
2189 // get two failures in a row with the second having `all_paths_failed` set.
2190 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2191 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2192 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2193 // pending which we will see later. Thus, when we previously removed the retry tracking map
2194 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2195 // retry entry even though more events for the same payment were still pending. This led to
2196 // us retrying a payment again even though we'd already given up on it.
2198 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2199 // is used to remove the payment retry counter entries instead. This tests for the specific
2200 // excess-retry case while also testing `PaymentFailed` generation.
2202 let chanmon_cfgs = create_chanmon_cfgs(3);
2203 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2204 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2205 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2207 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2208 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2210 let amt_msat = 200_000_000;
2211 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2212 #[cfg(feature = "std")]
2213 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2214 #[cfg(not(feature = "std"))]
2215 let payment_expiry_secs = 60 * 60;
2216 let mut invoice_features = InvoiceFeatures::empty();
2217 invoice_features.set_variable_length_onion_required();
2218 invoice_features.set_payment_secret_required();
2219 invoice_features.set_basic_mpp_optional();
2220 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2221 .with_expiry_time(payment_expiry_secs as u64)
2222 .with_features(invoice_features);
2223 let route_params = RouteParameters {
2225 final_value_msat: amt_msat,
2226 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2229 let mut route = Route {
2232 pubkey: nodes[1].node.get_our_node_id(),
2233 node_features: nodes[1].node.node_features(),
2234 short_channel_id: chan_1_scid,
2235 channel_features: nodes[1].node.channel_features(),
2236 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2237 cltv_expiry_delta: 100,
2239 pubkey: nodes[2].node.get_our_node_id(),
2240 node_features: nodes[2].node.node_features(),
2241 short_channel_id: chan_2_scid,
2242 channel_features: nodes[2].node.channel_features(),
2243 fee_msat: 100_000_000,
2244 cltv_expiry_delta: 100,
2247 pubkey: nodes[1].node.get_our_node_id(),
2248 node_features: nodes[1].node.node_features(),
2249 short_channel_id: chan_1_scid,
2250 channel_features: nodes[1].node.channel_features(),
2251 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2252 cltv_expiry_delta: 100,
2254 pubkey: nodes[2].node.get_our_node_id(),
2255 node_features: nodes[2].node.node_features(),
2256 short_channel_id: chan_2_scid,
2257 channel_features: nodes[2].node.channel_features(),
2258 fee_msat: 100_000_000,
2259 cltv_expiry_delta: 100,
2262 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2264 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2265 let mut second_payment_params = route_params.payment_params.clone();
2266 second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2267 // On retry, we'll only return one path
2268 route.paths.remove(1);
2269 route.paths[0][1].fee_msat = amt_msat;
2270 nodes[0].router.expect_find_route(RouteParameters {
2271 payment_params: second_payment_params,
2272 final_value_msat: amt_msat, final_cltv_expiry_delta: TEST_FINAL_CLTV,
2273 }, Ok(route.clone()));
2275 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2276 let htlc_updates = SendEvent::from_node(&nodes[0]);
2277 check_added_monitors!(nodes[0], 1);
2278 assert_eq!(htlc_updates.msgs.len(), 1);
2280 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2281 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2282 check_added_monitors!(nodes[1], 1);
2283 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2285 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2286 check_added_monitors!(nodes[0], 1);
2287 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2289 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2290 check_added_monitors!(nodes[0], 1);
2291 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2293 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2294 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2295 check_added_monitors!(nodes[1], 1);
2296 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2298 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2299 check_added_monitors!(nodes[1], 1);
2300 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2302 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2303 check_added_monitors!(nodes[0], 1);
2305 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2306 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2307 check_added_monitors!(nodes[0], 1);
2308 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2310 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2311 check_added_monitors!(nodes[1], 1);
2312 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2314 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2315 check_added_monitors!(nodes[1], 1);
2316 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2318 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2319 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2320 check_added_monitors!(nodes[0], 1);
2322 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2323 check_added_monitors!(nodes[0], 1);
2324 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2326 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2327 check_added_monitors!(nodes[1], 1);
2328 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2329 check_added_monitors!(nodes[1], 1);
2330 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2332 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2333 check_added_monitors!(nodes[0], 1);
2335 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2336 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2339 // Previously, we retried payments in an event consumer, which would retry each
2340 // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2341 // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2342 // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2343 // by adding the `PaymentFailed` event.
2345 // Because we now retry payments as a batch, we simply return a single-path route in the
2346 // second, batched, request, have that fail, ensure the payment was abandoned.
2347 let mut events = nodes[0].node.get_and_clear_pending_events();
2348 assert_eq!(events.len(), 4);
2350 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2351 assert_eq!(payment_hash, ev_payment_hash);
2352 assert_eq!(payment_failed_permanently, false);
2354 _ => panic!("Unexpected event"),
2357 Event::PendingHTLCsForwardable { .. } => {},
2358 _ => panic!("Unexpected event"),
2361 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2362 assert_eq!(payment_hash, ev_payment_hash);
2363 assert_eq!(payment_failed_permanently, false);
2365 _ => panic!("Unexpected event"),
2368 Event::PendingHTLCsForwardable { .. } => {},
2369 _ => panic!("Unexpected event"),
2372 nodes[0].node.process_pending_htlc_forwards();
2373 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2374 check_added_monitors!(nodes[0], 1);
2376 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2377 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2378 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2379 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2380 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2382 let mut events = nodes[0].node.get_and_clear_pending_events();
2383 assert_eq!(events.len(), 2);
2385 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2386 assert_eq!(payment_hash, ev_payment_hash);
2387 assert_eq!(payment_failed_permanently, false);
2389 _ => panic!("Unexpected event"),
2392 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id } => {
2393 assert_eq!(payment_hash, *ev_payment_hash);
2394 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2396 _ => panic!("Unexpected event"),
2401 fn test_simple_partial_retry() {
2402 // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2403 // full amount of the payment, rather than only the missing amount. Here we simply test for
2404 // this by sending a payment with two parts, failing one, and retrying the second. Note that
2405 // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2407 let chanmon_cfgs = create_chanmon_cfgs(3);
2408 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2409 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2410 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2412 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2413 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2415 let amt_msat = 200_000_000;
2416 let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2417 #[cfg(feature = "std")]
2418 let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2419 #[cfg(not(feature = "std"))]
2420 let payment_expiry_secs = 60 * 60;
2421 let mut invoice_features = InvoiceFeatures::empty();
2422 invoice_features.set_variable_length_onion_required();
2423 invoice_features.set_payment_secret_required();
2424 invoice_features.set_basic_mpp_optional();
2425 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2426 .with_expiry_time(payment_expiry_secs as u64)
2427 .with_features(invoice_features);
2428 let route_params = RouteParameters {
2430 final_value_msat: amt_msat,
2431 final_cltv_expiry_delta: TEST_FINAL_CLTV,
2434 let mut route = Route {
2437 pubkey: nodes[1].node.get_our_node_id(),
2438 node_features: nodes[1].node.node_features(),
2439 short_channel_id: chan_1_scid,
2440 channel_features: nodes[1].node.channel_features(),
2441 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2442 cltv_expiry_delta: 100,
2444 pubkey: nodes[2].node.get_our_node_id(),
2445 node_features: nodes[2].node.node_features(),
2446 short_channel_id: chan_2_scid,
2447 channel_features: nodes[2].node.channel_features(),
2448 fee_msat: 100_000_000,
2449 cltv_expiry_delta: 100,
2452 pubkey: nodes[1].node.get_our_node_id(),
2453 node_features: nodes[1].node.node_features(),
2454 short_channel_id: chan_1_scid,
2455 channel_features: nodes[1].node.channel_features(),
2457 cltv_expiry_delta: 100,
2459 pubkey: nodes[2].node.get_our_node_id(),
2460 node_features: nodes[2].node.node_features(),
2461 short_channel_id: chan_2_scid,
2462 channel_features: nodes[2].node.channel_features(),
2463 fee_msat: 100_000_000,
2464 cltv_expiry_delta: 100,
2467 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2469 nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2470 let mut second_payment_params = route_params.payment_params.clone();
2471 second_payment_params.previously_failed_channels = vec![chan_2_scid];
2472 // On retry, we'll only be asked for one path (or 100k sats)
2473 route.paths.remove(0);
2474 nodes[0].router.expect_find_route(RouteParameters {
2475 payment_params: second_payment_params,
2476 final_value_msat: amt_msat / 2, final_cltv_expiry_delta: TEST_FINAL_CLTV,
2477 }, Ok(route.clone()));
2479 nodes[0].node.send_payment_with_retry(payment_hash, &Some(payment_secret), PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2480 let htlc_updates = SendEvent::from_node(&nodes[0]);
2481 check_added_monitors!(nodes[0], 1);
2482 assert_eq!(htlc_updates.msgs.len(), 1);
2484 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2485 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2486 check_added_monitors!(nodes[1], 1);
2487 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2489 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2490 check_added_monitors!(nodes[0], 1);
2491 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2493 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2494 check_added_monitors!(nodes[0], 1);
2495 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2497 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2498 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2499 check_added_monitors!(nodes[1], 1);
2500 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2502 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2503 check_added_monitors!(nodes[1], 1);
2504 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2506 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2507 check_added_monitors!(nodes[0], 1);
2509 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2510 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2511 check_added_monitors!(nodes[0], 1);
2512 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2514 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2515 check_added_monitors!(nodes[1], 1);
2517 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2518 check_added_monitors!(nodes[1], 1);
2520 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2522 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2523 check_added_monitors!(nodes[0], 1);
2525 let mut events = nodes[0].node.get_and_clear_pending_events();
2526 assert_eq!(events.len(), 2);
2528 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, .. } => {
2529 assert_eq!(payment_hash, ev_payment_hash);
2530 assert_eq!(payment_failed_permanently, false);
2532 _ => panic!("Unexpected event"),
2535 Event::PendingHTLCsForwardable { .. } => {},
2536 _ => panic!("Unexpected event"),
2539 nodes[0].node.process_pending_htlc_forwards();
2540 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2541 check_added_monitors!(nodes[0], 1);
2543 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2544 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2546 expect_pending_htlcs_forwardable!(nodes[1]);
2547 check_added_monitors!(nodes[1], 1);
2549 let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2550 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2551 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2552 commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2554 expect_pending_htlcs_forwardable!(nodes[2]);
2555 expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);